I am creating a game where I represent boxes with a two dimensional array of their id.
var grid = [[X,X,X,X,X,X,X,X,X,X],
[X,X,4,4,4,4,X,X,X,X],
[X,3,3,3,3,X,X,X,X,X],
[X,X,X,2,2,2,2,X,X,X],
[X,1,1,1,1,5,5,5,5,5]];
The boxes stack on top of each other, and X represents a blank spot.
If one of the boxes are deleted I want any of the boxes above (That can fit) to shift down. So they are always neatly stacked.
So if I was to delete the box with ID: 1 I would get a new grid like this:
var grid = [[X,X,X,X,X,X,X,X,X,X],
[X,X,4,4,4,4,X,X,X,X],
[X,3,3,3,3,X,X,X,X,X],
[X,X,X,2,2,2,2,X,X,X],
[X,X,X,X,X,5,5,5,5,5]];
Then I would want Box: 3 to slide down into its spot like so:
var grid = [[X,X,X,X,X,X,X,X,X,X],
[X,X,4,4,4,4,X,X,X,X],
[X,X,X,X,X,X,X,X,X,X],
[X,X,X,2,2,2,2,X,X,X],
[X,3,3,3,3,5,5,5,5,5]];
Finally Box: 4 should move down into where 3 was:
var grid = [[X,X,X,X,X,X,X,X,X,X],
[X,X,X,X,X,X,X,X,X,X],
[X,X,4,4,4,4,X,X,X,X],
[X,X,X,2,2,2,2,X,X,X],
[X,3,3,3,3,5,5,5,5,5]];
Is there an easy way of doing this? I was thinking of a callback that checks the grid when a box is destroyed but what I came up with was mostly IF statements. Is there something elegant out there?
The box class itself also has the start position and its length:
box = {id: 3,
start: 1,
length: 4};
This is actually not an easy task. I created a little fiddle that does what you wanted to achieve (i think).
I extended the
box prototypewith some functions. My solution relies on the variablesgridandblocks, but you could abstract that even more if you like to.The functions
testFunctionalityandprintGridToElementare just there for testing purposes.My new Box prototype:
and the usage of it:
NOTE: I designed the grid with 0 being the lowest row