Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

379
Views
Javascript: ¿cómo encontrar mosaicos adyacentes en una cuadrícula?

Situación:

Tengo un contenedor con una cuadrícula simple de 3x3 como esta: ingrese la descripción de la imagen aquí

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: ingrese la descripción de la imagen aquí

Ejemplo 2:

Si se selecciona el mosaico correcto en la fila del medio, quiero estos mosaicos en la matriz: ingrese la descripción de la imagen aquí

Solución actual:

Actualmente hago esto:

  1. obtener todas las fichas en una matriz llamada battlefieldSlots
  2. obtener el índice de mosaicos seleccionados en currentSlotIndex
  3. empuje los mosaicos que necesito a una matriz llamada slotTargets

Esto 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)); }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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; }
about 4 years ago · Juan Pablo Isaza Report

0

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)));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!