Assuming a 2D array is used, the immediate neighbors of any tile #n (i,j) in a 25x25 grid can be found as follows:
main.swift275 chars24 lines
The above code assumes that n
is the index of the tile, starting from 0. It calculates the indices i
and j
of the tile in the 2D array. Then, it checks whether the tile has a neighbor in the north, south, west, or east direction, and calculates the index of that neighbor in the array. The neighbor indexes are calculated based on the assumption that the array is arranged row by row, from top to bottom.
Note that the code does not handle corner cases, where a tile does not have a neighbor in some direction. In those cases, the corresponding neighbor variables will not be defined.
gistlibby LogSnag