I’m working on an update to Froggy Went A Hoppin’ and want to make some things generic that I hardcoded in the first version. One of those is being able to see the “neighbors” of a given lily pad in the pond. For example, in the following level map:

1,1,0,4,1,0,1,1,0,4,1,

1,2,1,2,0,1,1,2,1,2,0,

1,1,0,1,1,0,1,1,0,1,1,

2,0,1,1,0,2,2,0,1,1,0,

1,1,0,4,1,0,1,1,0,4,1,

1,2,1,2,0,1,1,2,1,2,0,

1,1,0,1,1,0,1,1,0,1,1

…I wanted to know which lily pads were next to (left, right, up, down, and diagonal) any specified lily pad. *(Note: I don’t want to know the values of those locations, I want to know the indexes into that grid — if I have that I can get the value, set it, etc.)*

I ended up with this code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
--============================================================== -- 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 |

If I pass a 1 into that function (using a grid that’s 11 wide by 7 tall) I get back a table containing 2, 12, and 13 — the neighbors for that location. If I pass in 12, I get back a table containing 1, 2, 13, 23, 24.

I was hoping to find a “clever” way to find the neighbors, but that’s what I’ve ended up with for now. I’ve only tested it with a couple different sized grids, but I think it should work for just about any.

Thanks to Mark in beautiful West Wellow — he pointed me in the right direction for the modulo thing I was thinking of. So the two functions toward the top now look like this:

So much nicer. Just the one line in each function.

Just for the sake of history, this is what they looked like before Mark stepped in.

It worked, but wasn’t optimal. 😉