Sunday, March 30, 2025

Part 1: Tetris Game in C programming | Tetriminos (Shapes), Coordinate System, Rotation and Translation of Tetriminos (Shapes)

Previous Page                                                                                                                  Next Page



Tetriminos (Shapes)

In this Tetris game, I use 7 shapes. While some versions only include 5 shapes, I’ve added two extra ones: the J and S shapes, which are mirror opposites of the L and Z shapes, respectively.

Each shape consists of 4 blocks, and each block is called a Mino (short for monomino). A group of 4 Minos forms a Tetrimino (also known as Tetromino or Tetramino). For consistency, I’ll use the term Tetrimino throughout this article.


Coordinate System

To simplify game development, I’ve designed a gotoxy(x, y) function that relocates the coordinate system’s origin (0, 0) from the default top-left corner of the command window to a more convenient central position at (36, 12).

How It Works:
  1. Coordinate Transformation:
    • The function offsets input coordinates:
      • x becomes x + 36
      • y becomes y - 12
    • This allows negative coordinates (e.g., (-36, 12) maps to the original (0, 0)).
  1. Purpose:
    • Centering (0, 0) simplifies calculations for symmetric gameplay elements (e.g., rotating Tetriminos around the origin).
    • Negative coordinates enable intuitive positioning relative to the new origin.
The final coordinate system of the game is represented on below image.


Tetris game board spans 11 units along x-axis (width) and 21 units along the y-axis (height). The center coordinate is (0,0) so the coordinates of four corner of the Tetris board are (5, 10), (5, -10), (-5, -10), and (-5, 10).

Rotation and Translation

To rotate and translate Tetrimino, we must use linear algebra. This is 2D game and we rotate Tetrimino only by 90 degrees clockwise or anticlockwise. So, the final formula of rotation and translation will be simple.

Translation formula is:
v = (x, y) , T = (x', y') then v' = v + T = (x + x', y + y')

so, v = (0,0) T = (0, 12) move to v' = (0+0, 0+12) = (0,12)



Rotation formula by center of axis is:
v = (x, y), R = (cos Φ - sin Φ, sin Φ + cos Φ) then v' = R . v
 v' = (x cos Φ - y sin Φ, x sin Φ + y cos Φ)

we rotate Tetrimino only by 90 degrees so cos Φ = 0, and sin Φ = -1 so final rotation vector is

v' = (y * -1, x * 1), anticlockwise

v' = (y * 1, x * -1), clockwise

so (2,3), clockwise rotation is (3*1, 2*-1) = (3, -2)

 

Let's take a line shape Tetrimino as an example and discuss how we have implemented in game.

We always draw Tetrimino at the center of axis so that while rotating it will rotate by its own center of body. Initial coordinates of line are (0, 2), (0, 1), (0, 0), and (0, -1).


Coordinates after clockwise rotation are (-1,0), (0, 0), (1, 0), and (2, 0).


Coordinates after translating by (-3, 7) are (-4,7), (-3, 7), (-2, 7), and (-1, 7).



No comments:

Post a Comment