I’m writing a game!
A list of adjacent squares
Let’s say we have a grid of size x by y, the best way to represent this grid is as an array of x and y co-ordinates (starting from the top left first, as that’s how my brain works these days - thank HTML).
This is actually a two dimensional array, which in reality is just an array of arrays. It’s crucial to represent the grid like this, it allows for simpler calculations. Don’t attempt to use a one dimensional array of size x * y, as it’ll just overcomplicate things.
Get adjacent squares
Using the above logic, we represent a square as an array containing one x and one y co-ordinate (for example [2,2]). To get a square adjacent to another, it’s pretty simple with this system:
- Take one from the x co-ordinate [x-1,y]
- Add one to the x co-ordinate [x+1,y]
- Add one to the y co-ordinate [x,y+1]
- Take one from the y co-ordinate [x,y-1]
There is a maximum possibility of 4 adjacent squares to any other square.
Off the grid!
Squares that are on the edge of the grid might only have 2 or 3 adjacent squares, so we need to check that a possible adjacent is valid:
- Check the x co-ordinate is greater than or equal to 1, but is also less than or equal to the width of the grid
- Check the y co-ordinate is greater than or equal to 1, but is also less than or equal to the height of the grid
I’ve set the height and width of the grid to 5, but they can be anything. To get an array of adjacent squares, you pass the
getAdjacents() function a square:
Hopefully you’re also now interested in what on earth I’m writing :)