Thursday, March 31, 2016

javascript - Approaches for storing grid-like information



I am drawing this simple grid on my NodeJS server:


var grid = [];

for(var x = 0; x < 20; x++){
grid[x] = [];
for(var y = 0; y < 20; y++){
grid[x][y] = 0;

}
}


console.log(grid);

The outcome looks like this:


enter image description here


I know, pretty right?!


0 is supposed to indicate FREE, thus if a player requests to move to a field with 0, he will!


The problems come when I want to add more then just Free/Occupied, for instance I would like to give each Array Element an ID number for the Client Updates, or certain features on the field to be stored.


I tried to assign { something: N, something2: N}


But thought it looked rather performance expensive in the long run. (On a big Grid)



I read about using a single Object for several elements, but I cannot find this any more..


Should I perhaps use an Array of Objects, or an Additional Array inside each X,Y element?


Any performance / convenience / anything goes tips are welcome :D


Edit: Thank you for the ideas so far, I was now thinking to perhaps using Strings. Storing Variable_A + "," + Variable_B and then later using the .split to use the information. Any thoughts on this?



Answer



You seem to match this frequent use case :



  • a big map with each cell having a few characteristics

  • some objects being somewhere in the map



I suppose the map is big because you ask about performances. If the map is small, then both the question and my answer seem less relevant.


I usually use



  • a grid containing an int for each cell, this int being able to carry up to 32 flags (using bitwise operation)

  • a list of objects (may be an array or database records), each one having an x and an y


Not referencing the objects from the grid avoid coherency/race problems and is lighter.


A frequent practice is also to use a monodimensional array and to address the cells as a[x+W*y];. It makes many operation (like the cloning of the whole map or any range operation independent of the position) easier and faster. I'm not really familiar with node.js but I suppose the Buffer class should be used.


As I suppose you'll want to use a browser as final interface, here's a trick I use : I encode my maps as PNG, with each color of the palette simply being one of the possible flag combinations. This makes




  • storage and transmission very efficient (PNG is compressed)

  • map operations easy with image based operations

  • fast rendering at low resolution easy in the browser using image rendering


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...