zfollette
zfollette

Reputation: 487

Tetris: Turning the pieces?

So I am making a tetris game and one of the problems I am running into is piece rotation. I know I can just hard code it but thats not the right way to do it. The way the system works is I have a 2d array of an object 'Tile' the 'Tile' object has x, y coords, boolean isActive, and color. The boolean isActive basically tells the computer which tiles are actually being used (Since tetris shapes are not perfect quadrilaterals).

Here is how I would make a shape in my system:

public static Tile[][] shapeJ() {
    Tile[][] tile = new Tile[3][2];

    for (int x = 0; x < 3; x++) {
        for (int y = 0; y < 2; y++) {
            tile[x][y] = new Tile(false, Color.blue);
        }
    }

    tile[0][0].setActive(true);
    tile[0][0].setX(0);
    tile[0][0].setY(0);

    tile[1][0].setActive(true);
    tile[1][0].setX(50);
    tile[1][0].setY(0);

    tile[2][0].setActive(true);
    tile[2][0].setX(100);
    tile[2][0].setY(0);

    tile[2][1].setActive(true);
    tile[2][1].setX(100);
    tile[2][1].setY(50);

    return tile;
}

Now I need to rotate this object, I do not know how to do that without hard coding the positions. There has to be an algorithm for it. Can anyone offer some help?

Upvotes: 1

Views: 448

Answers (1)

RedCoast
RedCoast

Reputation: 336

A good way that I used when writing a tetris clone is to use rotational matrices:

http://en.wikipedia.org/wiki/Rotation_matrix

So the coordinates (x',y') of the point (x,y) after rotation are:

x' = x*cos(theta) - y*sin(theta);

y' = x*sin(theta) + y*cos(theta);

Where theta is the angle of rotation(+-90 degrees or +-PI/2 radians for the java functions that I know) In this case the blocks are rotated around the origin (0, 0) so you either have to have the coordinates of the block in special "block space" that then gets transposed onto "field space" or you take away the offset of the block so that it is centered at the origin every iteration.

I hope that helps, I am happy to answer specific questions in the comments.

Upvotes: 3

Related Questions