From b0cf4cb8818c8440462e24c7b553bc4b90b3a8a2 Mon Sep 17 00:00:00 2001 From: Steph Enders Date: Sat, 10 Dec 2022 23:42:30 -0500 Subject: Move enemies that have no path If there is no path to the player, the enemy will move in best effort --- dnglib/algs.lua | 39 ++++++++++++++++++++++++++++++++++++++- maps/lvl2/dng.map | 12 ++++++------ 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/dnglib/algs.lua b/dnglib/algs.lua index 9bb2542..0b66604 100644 --- a/dnglib/algs.lua +++ b/dnglib/algs.lua @@ -113,6 +113,41 @@ local function push_moves(x, y, origin, map, queue, target_pos) return false end +--- +---@param start_pos table [x, y] +---@param target_pos table [x, y] +---@param map table 2D map array +---@return table best move to target [x, y] +--- +local function best_effort_move(start_pos, target_pos, map) + local diff_x = target_pos.x - start_pos.x + local diff_y = target_pos.y - start_pos.y + + local move = { dx = 0, dy = 0 } + + if (math.abs(diff_x) > math.abs(diff_y)) then + -- do x moves first + if diff_x > 0 and can_move(start_pos.x + 1, start_pos.y, map) then + move.dx = 1 + return move + elseif diff_x < 0 and can_move(start_pos.x - 1, start_pos.y, map) then + move.dx = -1 + return move + end + else -- y moves + if diff_y > 0 and can_move(start_pos.x, start_pos.y + 1, map) then + move.dy = 1 + return move + elseif diff_y < 0 and can_move(start_pos.y, start_pos.y - 1, map) then + move.dy = -1 + return move + end + end + -- return 0, 0 move + return move +end + + --- ---@param start_pos table [x, y] ---@param target_pos table [x, y] @@ -142,7 +177,9 @@ local function pathfind(start_pos, target_pos, map) return { dx = origin.x - start_pos.x, dy = origin.y - start_pos.y } end end - return { dx = 0, dy = 0 } + + --- cannot find path - just move "towards" player + return best_effort_move(start_pos, target_pos, map) end return { diff --git a/maps/lvl2/dng.map b/maps/lvl2/dng.map index 26467e0..7c5ff80 100644 --- a/maps/lvl2/dng.map +++ b/maps/lvl2/dng.map @@ -4,15 +4,15 @@ w e 0 0 0 t 0 0 0 0 0 0 w 0 0 0 w w 0 0 0 0 0 0 0 0 0 0 0 w t 0 0 w w 0 w w w w w w w w 0 w w w w 0 w w 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 w -w 0 w w w w w w w w 0 w w 0 0 0 w -w e 0 0 0 0 0 0 0 0 0 w 0 0 0 0 w -w w 0 w w w w w w w 0 w w w w w w -w t 0 w 0 0 w 0 0 0 0 w w w w 0 w -w 0 w w 0 0 0 0 0 0 0 w e w w 0 w +w 0 w w w w w w w w 0 w w w w w w +w e 0 0 0 0 0 0 0 0 0 w 0 e 0 0 w +w w 0 w w w w w w w 0 w 0 w 0 w w +w t 0 w 0 0 w 0 0 0 0 w 0 0 w 0 w +w 0 w w 0 0 0 0 0 0 0 w 0 0 w 0 w w 0 0 0 0 w w w w 0 w w w w w 0 w w t w w w 0 0 0 0 0 0 0 0 0 0 0 w w w w w w 0 w 0 0 0 0 0 w 0 w w w w 0 0 0 0 0 0 0 0 0 0 0 w 0 0 0 w w p w w w w w w w w w w w w w 0 w w 0 0 0 0 0 0 0 t 0 0 0 0 0 0 0 w -w w w w w w w w w w w w w w w w w \ No newline at end of file +w w w w w w w w w w w w w w w w w -- cgit v1.2.3-54-g00ecf