Skip to content

Instantly share code, notes, and snippets.

@thykka
Last active January 30, 2023 19:09
Show Gist options
  • Save thykka/f1210023bd2e202bf4c077f9d119a03b to your computer and use it in GitHub Desktop.
Save thykka/f1210023bd2e202bf4c077f9d119a03b to your computer and use it in GitHub Desktop.
Grid neighbor search
--[[
Given a 1D-array of cells in a 2D-grid,
and a target cell with x and y coordinates,
it returns a table of neigboring cells.
Given a truthy third parameter,
it also returns diagonally adjacent cells.
]]
function get_adjacent(board,cell,diagonals)
local left_edge, right_edge,
top_edge, bottom_edge=
cell.x==0, cell.x==board_width-1,
cell.y==0, cell.y==board_height-1
local offsets={}
if(not top_edge) add(offsets,-board_width)
if(not bottom_edge) add(offsets, board_width)
if(not left_edge) add(offsets,-1)
if(not right_edge) add(offsets, 1)
if diagonals then
if not top_edge then
if not left_edge then
add(offsets,-board_width-1)
end
if not right_edge then
add(offsets,-board_width+1)
end
end
if not bottom_edge then
if not left_edge then
add(offsets,board_width-1)
end
if not right_edge then
add(offsets,board_width+1)
end
end
end
local adjacents={}
local cell_index=find_index(board,cell)
for offset in all(offsets) do
if board[cell_index+offset] then
add(adjacents, board[cell_index+offset])
end
end
return adjacents
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment