Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Rotate a 2D Array of Integers

Tags:

c++

arrays

c#

math

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 that I get a rotated tetris block. I cannot simply rotate the texture because all my collision detection, etc has been designed to work with the 2D array. The game is written in C# using XNA.

How can i possibly rotate my 2D array of ints by 90 degrees clockwise/counter clockwise.

Here is how my 'L' block is stored as an example.

0 1 0 0
0 1 0 0
0 1 1 0 
0 0 0 0

Thanks for your help.

like image 424
Brock Woolf Avatar asked Mar 14 '09 18:03

Brock Woolf


People also ask

How do you rotate an array 90 degrees?

Rotate Matrix 90 Degree Clockwise or Right Rotation The rotation of a matrix involves two steps: First, find the transpose of the given matrix. Swap the elements of the first column with the last column (if the matrix is of 3*3). The second column remains the same.

How do you rotate an array 90 degrees in Python?

The rot90() function is used to rotate an array by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis. Array of two or more dimensions. Number of times the array is rotated by 90 degrees.


2 Answers

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.

like image 192
Reed Copsey Avatar answered Sep 19 '22 22:09

Reed Copsey


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).

like image 39
Jon Avatar answered Sep 19 '22 22:09

Jon