4 Replies Latest reply: Feb 10, 2008 6:25 PM by 807601

# 2d Array Tetris Row Collapsing Problem

Hey guys for class I am building a Tetris game and while I have everything else down im getting stuck on the "row collapsing." I am using a 2 d array to represent the board and switching individual cells on and off to emulate pieces. Ive tried nested for loops with various algorithms but I just cannot figure out how to get this working. Even if i delete a full row, the part of the row above might make another full row and i cant figure out how to detect that. Am i even going in the right direction? just a hint would be nice or a link to a good array manipulation guide thanks :)
• ###### 1. Re: 2d Array Tetris Row Collapsing Problem
javed.b.ahamed wrote:
Even if i delete a full row, the part of the row above might make another full row and i cant figure out how to detect that.
This never happens in Tetris. When an entire row gets filled, it disappears and the rows above it drop, but nothing drops more than 1 row (or the number of rows that disappeared, 1-4).

Just use System.arraycopy when you detect some lines should be cleared to move all rows above the cleared row(s) down. Here's a simplistic way of doing it that could be optimized, but is usually fast enough for a Tetris game:
``````     private void removeEmptyRows() {
int i = 0;
while (i<4 && rowsBeingCleared>-1) {
// NOTE: This could be optimized to only move rows with blocks in
// them (i.e., copy just the "block stack", not the entire board,
// as at least some of the top is empty), but the row count is so
// small this is just as good.
// NOTE 2: This could also be optimized by recognizing when 2 or
// more of the rows being cleared are adjacent. They could be
// removed at the same time.
// "+i" in row calculation to adjust for any lower rows already
// removed. This assumes values in rowsBeingCleared go from
// higher-indexed rows to lower-indexed rows.
int row = rowsBeingCleared[i] + i;
System.arraycopy(data,0, data,1, row);
// Reallocate row 0 so row 0 and 1 don't point to the same array.
//Arrays.fill(data[0], 0);
data[0] = new int[getBoardColumnCount()];
i++;
}

tetris.linesCleared(i);

}
``````
• ###### 2. Re: 2d Array Tetris Row Collapsing Problem
you can't use system.arraycopy with 2d arrays can u...
• ###### 3. Re: 2d Array Tetris Row Collapsing Problem
Sure you can. 2D arrays are just arrays of arrays.
• ###### 4. Re: 2d Array Tetris Row Collapsing Problem
SunFred wrote:
Sure you can. 2D arrays are just arrays of arrays.
Just keep in mind that it'll be copying references to the sub-arrays, and not doing a deep copy. So be sure, when iterating and doing System.arraycopy of 2-D arrays, to do it from the "bottom up".