Javascript - How to find adjacent tiles in a grid?
Solution 1:
Since you are using a 1D array
data structure to store your grid, it's a little complicated to check if an index is out-of-bound. 3
for example, we have no idea if it is (0, 1)
or (3, 0)
, so we need to have 4 variables to check edge conditions.
If you want the solution to be more elegant, using a 2D array
might help
const col = 3; // width of your grid
const row = 3; // height of your grid
function getAround(index) {
let around = [];
// For Edge Condition
index = Number( index );
if( isNaN( index ) ) {
throw new Error("Index should be a number.");
}
const leftEdge = index % col === 0; // Tile on very left edge
const rightEdge = (index+1) % col === 0; // Tile on right edge
const topEdge = Math.floor( index / col ) === 0; // Tile on top edge
const bottomEdge = Math.floor( index / col ) === (row - 1); // Tile on bottom edge
if( ! leftEdge ) around.push( index - 1 );
if( ! rightEdge ) around.push( index + 1 );
if( ! topEdge ) around.push( index - col );
if( ! bottomEdge ) around.push( index + col );
return around;
}
Solution 2:
If we assume you have an x & y position for your tiles (with 0,0 being top left in this example) it's somewhat easy to find the adjacent tiles
function findAdjacentTiles(x,y,gridWidth,gridheight){
return [[-1,0],[1,0],[0,-1],[0,1]] // all the possible directions
.map( ([xd,yd]) => ([x+xd,y+yd]) ) // adjust the starting point
.filter( ([x,y]) => x>=0 && x<gridWidth && y>=0 && y<gridheight) // filter out those out of bounds
}
console.log("for [1,1]:", JSON.stringify(findAdjacentTiles(1,1,3,3)));
console.log("for [2,1]:", JSON.stringify(findAdjacentTiles(2,1,3,3)));