Search code examples
javaarraysenumstetris

Storing Piece objects on array - java Tetris Tutorial


Im just new to Java and i found this good tutorial for creating a Java Tetris Game.

I dont have a mentor or a tutor to help me with this - Ive been looking for one for ages :( so currently im self learning java and PHP :)

Anyways heres the website i found http://zetcode.com/tutorials/javagamestutorial/tetris/

can someone explain how this method works from the tutorial?

Tetrominoes shapeAt(int x, int y) { return board[(y * BoardWidth) + x]; }

I know it gets called form the Paint() Method

for (int i = 0; i < BoardHeight; ++i) {
 for (int j = 0; j < BoardWidth; ++j) {
     Tetrominoes shape = shapeAt(j, BoardHeight - i - 1);
     if (shape != Tetrominoes.NoShape)
         drawSquare(g, 0 + j * squareWidth(),
                    boardTop + i * squareHeight(), shape);
 }
}

From what i understand - it loops at each square of the board and determines if there is a shape (Enum) stored on the board[] array.

I just need someone to explain to me how this portion paints all shapes, or remains of the shapes, that have been dropped to the bottom of the board?

And how All the squares are rememberd in the board[] array?

Thank you


Solution

  • Put simply, the board array is a single-dimensional array which remembers what sort of shape is on each square. Although it's single-dimensional, it's arranged so that the first row comes first, then the second row, etc. So on a 3x5 board like this:

    A B C
    D E F
    G H I
    J K L
    M N O
    

    The array would be such that board[0] would contain the shape at A, board[3] would contain D, etc.

    It's important to note that it's not actually remembering a whole shape for each square - just what kind of shape was there. So as shapes drop to the bottom, each individual square stays in the board array even if part of the shape it represented is wiped out by a line being removed. Removing a line really just involves shifting the first part of the array "down" to overwrite the row being removed, and clearing out the top row's-worth of elements (to Tetrominoes.NoShape).