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 co-ordinates (starting from the top left first, as that’s how my brain works these days - thank HTML).

1
2
3
4
5
6
[1,1] [2,1] [3,1] [4,1] [5,1] ..
[1,2] [2,2] [3,2] [4,2] [5,2] ..
[1,3] [2,3] [3,3] [4,3] [5,3] ..
[1,4] [2,4] [3,4] [4,4] [5,4] ..
[1,5] [2,5] [3,5] [4,5] [5,5] ..
.. .. .. .. .. ..

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]
1
var adjacents = [[x-1,y],[x+1,y],[x,y+1],[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
1
x >= 1 && x <= width && y >= 1 && y <= height

The solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var width = 5,
height = 5;
function isSquareOnGrid(square) {
var x = square[0],
y = square[1];
return x >= 1 && x <= width && y >= 1 && y <= height;
}
function getAdjacents(square) {
var x = square[0],
y = square[1],
adjacents = [[x-1,y],[x+1,y],[x,y+1],[x,y-1]];
return adjacents.filter(isSquareOnGrid);
}

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:

1
2
getAdjacents([2,2]); // [1,2],[3,2],[2,3],[2,1]
getAdjacents([5,3]); // [4,3],[5,4],[5,2]

Hopefully you’re also now interested in what on earth I’m writing :)