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. One reason for that is when the frog on a lily pad is selected, I can highlight the lily pads the frog can hop to.
For example, in the following level map:
…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:
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.