Get Adjacent Squares on a Grid
I’m writing a game!
That’s right, I’m writing a (puzzle?) game in JavaScript at the moment. I’ve come across a few features that seem difficult to implement but actually have very simple solutions, so I thought I’d share the first one.
A list of adjacent squares
The grid
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 coordinates (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 coordinate (for example [2,2]). To get a square adjacent to another, it’s pretty simple with this system:
 Take one from the x coordinate [x1,y]
 Add one to the x coordinate [x+1,y]
 Add one to the y coordinate [x,y+1]
 Take one from the y coordinate [x,y1]


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 coordinate is greater than or equal to 1, but is also less than or equal to the width of the grid
 Check the y coordinate is greater than or equal to 1, but is also less than or equal to the height of the grid


The solution


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 :)