Created
April 9, 2015 09:43
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--============================================================== | |
-- 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