Game Development Reference
In-Depth Information
been removed below them. For this reason, we are going to iterate backwards though the
board
2D array. This means that we will be testing the right-most and bottom-most blocks first. By
testing in that direction, we can be sure that we have counted the proper number of missing
blocks below each block. We don't care how many blocks are missing above it, because the
blocks above don't affect how far a block must fall to get into position. This little trick saves us
tons of code and extra iterations though the
board
array.
We start by iterating through the columns in
board
, backward. For each column, we will then
iterate through the rows in that column.
public function moveBlocksDown():void {
var collength:int = BLOCK_COLS-1;
for (var c:int = collength; c >= 0; c--) {
var rowlength:int = BLOCK_ROWS-1;
var missing:Number = 0;
for (var r:int = rowlength; r >= 0; r--) {
tempBlock=board[r][c];
When we find a row, col combination that is not null, we then we go ahead and test to see how
many
Block
objects below it in the board 2D array are missing. We do this by creating another for
loop that iterates through all the
board[r][c]
columns below the current
Block
(from r+1 to
BLOCK_ROWS-1). If we find a missing
Block
, we increment the missing variable.
if (tempBlock != null) {
missing=0;
if (r<BLOCK_ROWS) {
for (var m:int = r+1; m < BLOCK_ROWS;m++) {
if (board[m][c]==null) {
missing++;
}
}
}
After we have calculated how many Block objects are missing in the column below the current
Block represented by tempBlock, it is time to move it. First, we change the row and col properties
of the Block to match the new position it will be in when it is finished falling.
if (missing > 0) {
tempBlock.row = r+missing;
tempBlock.col = c;
Then, we update the new position of the
Block
in
board
where the
tempBlock
logically now exists
and set the current position to
null
so the proper
Block
will be replaced.
board[r+missing][c] = tempBlock;
board[r][c] = null;
Finally, we call the startFalling function of tempBlock with the new position on the screen of the
Block, which will, in turn, have it start falling into position.
tempBlock.startFalling(tempBlock.y+
(missing*BLOCK_HEIGHT)+(missing*ROW_SPACING),10);
}
}
}
}
}
}