Tetris Rotation

I am currently at the last stage of the Tetris Clone using SDL library, the only thing left is rotation. For each piece I have a separate class, and in order to move the pieces down I use a method:

1
2
3
4
5
6
7
void PieceZ::movePieceDown()
    {
      drawBlock(x1,y1++);
      drawBlock(x2,y3++);
      drawBlock(x3,y3++);
      drawBlock(x4,y4++);
    }

This method is called like that: current->movePieceDown(); where current represents a pointer to the current piece. Now to rotate the piece I have another method:

1
2
3
4
5
6
7
void PieceZ::rotatePiece()
    {
      drawBlock(newX1,newY2++);
      drawBlock(x2,y2);
      drawBlock(newX3,newY3++);
      drawBlock(newX4,newY4++);
    }


New X and Y coordinates are calculated elsewhere, with x2 and y2 taken as the origin.
My question is how do I swap current->movePieceDown() with current->rotatePiece() while the piece is moving? Taking into acount that I am handling keyboard events in another method.
Last edited on
I would have 3 threads. One thread (call it the display thread) listens for events. When a downEvent event comes, it calls movePieceDown. When a rotateEvent event comes, it calls rotatePiece

The second thread would run a repeating timer. Every time the timer expires it sends a downEvent to the display thread. You can shorten the timer duration to speed up the pieces if you want.

The third thread would be your keyboard handler. When the rotate key is pressed, the handler will send a rotateEvent to the display thread.

Edit: I guess you don't really need a separate thread for a timer and a callback function, but you can see that the functionality is separate from the display thread.
Last edited on
Hey, thank you for the answer, my program almost corresponds to your idea. I found the solution, and wanted to post it just in case:

Basically I removed the method rotatePiece(), instead of that I have a method that calculates the rotation independently of drawing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void PieceZ::getRotation()
    {
      newX1 = (y1-y2) + x2;
      newY1 = (x2-x1) + y2;

      newX3 = (y3-y2) + x2;
      newY3 = (x2-x3) + y2;

      newX4 = (y4-y2) + x2;
      newY4 = (x2-x4) + y2;

      x1 = newX1;
      x3 = newX3;
      x4 = newX4;

      y1 = newY1;
      y3 = newY3;
      y4 = newY4;
    }


new values are set to 0 initially, and every time a user presses a button on the keyboard this method gets called, it calculates the new rotation in new and assigns it to x and y values. Which gives you a 90 degree counter clockwise rotation.
Topic archived. No new replies allowed.