Situación:
Tengo un contenedor con una cuadrícula simple de 3x3 como esta: 
Pregunta:
Cuando hago clic en un mosaico, quiero obtener los mosaicos adyacentes en una matriz.
Ejemplo 1:
Si se selecciona el mosaico central, quiero estos mosaicos en la matriz: 
Ejemplo 2:
Si se selecciona el mosaico correcto en la fila del medio, quiero estos mosaicos en la matriz: 
Solución actual:
Actualmente hago esto:
battlefieldSlotscurrentSlotIndexslotTargetsEsto funciona, pero el enfoque parece un poco torpe. Especialmente porque eventualmente me gustaría tener una solución que funcione con diferentes cuadrículas (por ejemplo, 4x4, 3x5, 7x7). No puedo pensar en una buena manera de abordar esto.
Cualquier ayuda apreciada.
var slotTargets = []; if (currentSlotIndex == 2) { slotTargets.push(null); slotTargets.push(null); slotTargets.push(battlefieldSlots.item(currentSlotIndex + 3)); slotTargets.push(battlefieldSlots.item(currentSlotIndex - 1)); } else if (currentSlotIndex == 3) { slotTargets.push(battlefieldSlots.item(currentSlotIndex - 3)); slotTargets.push(battlefieldSlots.item(currentSlotIndex + 1)); slotTargets.push(battlefieldSlots.item(currentSlotIndex + 3)); slotTargets.push(null); } else if (currentSlotIndex == 5) { slotTargets.push(battlefieldSlots.item(currentSlotIndex - 3)); slotTargets.push(null); slotTargets.push(battlefieldSlots.item(currentSlotIndex + 3)); slotTargets.push(battlefieldSlots.item(currentSlotIndex - 1)); } else if (currentSlotIndex == 6) { slotTargets.push(battlefieldSlots.item(currentSlotIndex - 3)); slotTargets.push(battlefieldSlots.item(currentSlotIndex + 1)); slotTargets.push(null); slotTargets.push(null); } else { slotTargets.push(battlefieldSlots.item(currentSlotIndex - 3)); slotTargets.push(battlefieldSlots.item(currentSlotIndex + 1)); slotTargets.push(battlefieldSlots.item(currentSlotIndex + 3)); slotTargets.push(battlefieldSlots.item(currentSlotIndex - 1)); }Dado que está utilizando una estructura de datos de 1D array para almacenar su cuadrícula, es un poco complicado verificar si un índice está fuera de límite. 3 por ejemplo, no tenemos idea si es (0, 1) o (3, 0) , por lo que necesitamos tener 4 variables para verificar las condiciones de borde.
Si desea que la solución sea más elegante, usar una 2D array podría ayudar
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; }Si asumimos que tiene una posición x e y para sus mosaicos (con 0,0 arriba a la izquierda en este ejemplo), es algo fácil encontrar los mosaicos adyacentes
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)));