Skip to content

Instantly share code, notes, and snippets.

@OutlawGameTools
Created April 9, 2015 09:43
Show Gist options
  • Save OutlawGameTools/23a9dd15bc93b6462aad to your computer and use it in GitHub Desktop.
Save OutlawGameTools/23a9dd15bc93b6462aad to your computer and use it in GitHub Desktop.
Pass in an index into a 2-dimensional square grid and get back a table containing the index of all neighbor squares.
--==============================================================
-- pass in a lily pad number and get back a
-- table containing all the neighbors for
-- that lily pad.
local numCols = 11
local numRows = 7
local function getNeighbors(padNum)
local neighbors = {}
local function inLeftColumn()
return ((padNum-1) % numCols) == 0
end
local function inRightColumn()
return (padNum % numCols) == 0
end
local inLeft = inLeftColumn()
local inRight = inRightColumn()
-- number above, above left/right
if padNum > numCols then
neighbors[#neighbors+1] = padNum - numCols
if not inLeft then
neighbors[#neighbors+1] = padNum - numCols - 1
end
if not inRight then
neighbors[#neighbors+1] = padNum - numCols + 1
end
end
-- number below & below left/right
if padNum <= (numCols * (numRows-1)) then
neighbors[#neighbors+1] = padNum + numCols -- number below
if not inLeft then
neighbors[#neighbors+1] = padNum + numCols - 1
end
if not inRight then
neighbors[#neighbors+1] = padNum + numCols + 1
end
end
-- number to right
if not inRight then
neighbors[#neighbors+1] = padNum + 1
end
-- number to left
if not inLeft then
neighbors[#neighbors+1] = padNum - 1
end
return neighbors
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment