Search code examples
javascriptperformancegrid-layout

Find adjacent tiles in a two-dimensional grid


I have a two-dimensional grid, in which all tiles are defined by two coordinates x and y. I'm storing the tiles in an array like this var tiles = [];. Each tile is an object with an x and y property:

Tile = {
   x: ...,
   y: ...
}

For drawing purposes (canvas) I want to find out which tiles are adjacent to each other. I could do that by looping through each element and check if it is adjacent. Since that would take n^n number of accesses I don't think this is the right way to do it. I think there would be a more efficient algorithm.

I also thought that maybe storing the data in a different way would help, but again, I wouldn't know how.


Solution

  • You have 2 ways to create a grid :

    • Using a 2 dimensional Array which must be the easier thing for a grid
    • Store adjacent Tile of a Tile in it with something like that :

      var tile0 = {
        x:0, y:1
      }
      
      var tile1 = {
        x:1,y:1, tileLeft : tile0
      }
      

    It can be useful if you want to create Pentagonal or Hexagonal... grid, ofcourse create your grid automatically with a for loop.

    EDIT

    A two dimensional array is simply an Array of Array

    var arr = new Array()
    for(var i = 0 ; i < 10 ; i++){
        arr[i] = new Array()
    }
    

    Now you can set value like in a grid, for example :

    arr[0][2] = {x:2,y:2}  //It's a bit useless since indexes can be use for x and y
    

    In that case, i have 10 Array stored in one Array so :

    arr[10][0] 
    

    Will return following error : Uncaught TypeError: Cannot set property '2' of undefined, because index of arr are only define between 0 and 9.