diff options
author | Steph Enders <smenders@gmail.com> | 2022-12-10 23:42:30 -0500 |
---|---|---|
committer | Steph Enders <smenders@gmail.com> | 2022-12-10 23:42:30 -0500 |
commit | b0cf4cb8818c8440462e24c7b553bc4b90b3a8a2 (patch) | |
tree | 4f387c88d939b7d7340b164ae1db450f730c0648 /dnglib | |
parent | 1a786066286e112d196b24e17c41b75215edafd1 (diff) |
Move enemies that have no path
If there is no path to the player, the enemy will move in best effort
Diffstat (limited to 'dnglib')
-rw-r--r-- | dnglib/algs.lua | 39 |
1 files changed, 38 insertions, 1 deletions
diff --git a/dnglib/algs.lua b/dnglib/algs.lua index 9bb2542..0b66604 100644 --- a/dnglib/algs.lua +++ b/dnglib/algs.lua @@ -119,6 +119,41 @@ end ---@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] +---@param map table 2D map array +---@return table best move to target [x, y] +--- local function pathfind(start_pos, target_pos, map) local queue = Queue:new() local visit_map = {} @@ -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 { |