If I'm using a 1d array to represent a square board, how can I take my index and check the sqaures a
- by FrankTheTank
If I have a 4x4 gameboard which I'm representing in my program as a 1d integer array of size 16.
How can I get the indexs of the squares above, below, to the left and to the right any given index?
So, for example:
A = { 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 }
Which represents this board
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Lets say I am currently on index #8 in the board (value = 7). How can I get the index for 4 (value = 3) , 5 (value = 6), 10 (value = 11) and realize that there is no right square because it is on the right hand edge of the board.
I know I need to use some modulus math but I'm failing to come up with the right way to get the indexes for adjacent squares.
I'm thinking something like...
if ((i % 4) + 1 < 3) right = i + 1;
if ((i % 4) - 1 > 0) left = i - 1;
if ((i % 4) + 4 < 15) bottom = i + 4;
if ((i % 4) - 4 > 0 ) top = i - 4;
Does this seem like it is the right approach?