I am programming a Tetris clone and in my game I store my tetromino blocks as 4x4 arrays of blocks. I now need to be able to rotate the integer positions in the arrays so th
In classic tetris there are very few permutations of objects. I would simply have a constant array for each "tetromino," at each of the 4 positions, and simple logic to choose the appropriate one based on input.
Why waste CPU cycles trying to rotate it?
If you want to rotate a 4 x 4 block, you just move the positions:
A B C A
C D D B
B D D C
A C B A
Each A moves to the next A, and the same for B, C and D.
/-----\
| |
| V
A B C A
/->C D>D B--\
| B D D C |
| A C B A |
| | ^ |
| | | |
\----/ \----/
I'd store (x, y) coordinates of the "cells" and use rotation matrix to rotate them. See Drawing a Rotated Rectangle for example. You probably have to round the result to closest 0.5 increment.
int[,] source = { { 1,2,3 }, {4,5,6 }, { 7,8,9} };
int[,] result = new int[3,3];
var rows = source.GetLength(0);
var cols = source.GetLength(1);
for (var r=0; r<rows; r++)
{
for (var c = 0; c < cols; c++)
{
result[r, c] = source[rows - 1 - c, r];
}
}
If they're a 2D array, you can implement rotation by copying with different array access orders.
i.e., for a clockwise rotation, try:
int [,] newArray = new int[4,4];
for (int i=3;i>=0;--i)
{
for (int j=0;j<4;++j)
{
newArray[j,3-i] = array[i,j];
}
}
Counter-clockwise is similar.
Don't rotate the pieces with code. Just store an array of the different piece orientations and cycle through them when the piece is rotated. There's no need to dynamically rotate them in a Tetris game.
As the problem domain is Tetris, you will find that a rotation algorithm causes undesirable effects, such as the long thin Tetronimo not alternating between two positions (as it does in the real thing).