We can consider a square grid with a one-dimensional array, with sides of n
length. Here's an example of how to calculate immediate neighbors:
main.swift575 chars26 lines
Assuming n
is the tile number we want to find the neighbors of, and sideLength
is the length of a side of the square grid (i.e. the number of columns/rows).
n - sideLength
only if n is not in the top row.n + 1
only if n is not in the last column.n + sideLength
only if n is not in the bottom row.n - 1
only if n is not in the first column.The above function returns an array of tile numbers of immediate neighbors, so we can use it as follows:
main.swift150 chars5 lines
This means that the tile number 5 has the neighbors 1 (to the north), 4 (to the west), 6 (to the east), and 9 (to the south).
gistlibby LogSnag