c++tetris

How to detect the collision of a tetromino in a tetris game?


I am writing a tetris game with the ncurses library. I am struggling to write the method which detects whether the tetromino can be placed into a new empty space or it is collided with an other tetromino or with the borders.

Every tetromino is derived from an array called shapes, which can be found at: link So every tetromino is a 4x4 array where there can be coloured elements (the value refers to the color itself) and empty spaces as well (denoted as 0).

There is a colobuffer (2d array) in my app, which contains all of the tetrominos as well as the current, falling tetromino. The currentBrick is a type of a Brick class, which contains each cell location building up the tetromino on the game map (colorbuffer).

Here is my method:

bool canPlaceTetromino(int distanceX, int distanceY) {
    for (int y = 0; y < 4; ++y) {
        for (int x = 0; x < 4; ++x) {
            if (shapes[currentBrick.type][currentBrick.rotation][y][x] != 0) {
                int boardX = currentBrick.cellsPos[y][x].x + distanceX;
                int boardY = currentBrick.cellsPos[y][x].y + distanceY;

                if (boardX < 0 || boardX >= MAPWIDTH || boardY >= MAPHEIGHT || gameBoardColours[boardY][boardX] != 0) {
                    return false;
                }
            }
        }
    }
    return true;
}

My problem is, how can I eliminate the option, when the method above also detecting collision with the tetromino itself? I mean, I handle the tetromino as an objects containing cells/pixels, so it is not a point location. I need add the distanceX and distanceY to each cell of the tetromino, but that case I will detect a "self-collision" as well.

Here is the brick class by the way:

class Brick
{
public:
    Brick();

    int type;
    int rotation;
    pos cellsPos[4][4]={};

    void rotate(bool collided);
    void updateCellX(int difference);
    void updateCellY(int difference);
};

Solution

  • Could you just:

    1. Delete the current tetromino from the color buffer (set it to the empty color)
    2. Check the future tetromino for intersections
    3. Put the current tetromino back (which is possible since the class will retain the state of the tetromino)

    I'm assuming that the current tetromino is in a valid position. This solution won't work if that is not the case.