Search code examples
javarotationcoordinate-systems

Rotating blocks in 2D-array


I am making a program similar to the famous game Tetris and I've run into some problems when it comes to rotating a block.

I know you are able to rotate figures in a coordinate system by using "x = -y" and "y = x" but the problem is that because I am using an array of integers to represent the block it makes things so much more difficult.

My array looks like:

int[][] space = new int[20][10];

And if a coordinate contains a block the value is 1 else it's 0.

So how can I rotate a block in that space without getting trouble with negative numbers?


Solution

  • Here's a sample piece (reusing your int[][] using 0's and 1's, which might as well be done using a boolean array):

    private static final int[][] piece = new int[][] {
            { 0, 1, 0, },
            { 1, 1, 1, },
    };
    

    You can rotate a piece doing this:

    private static int[][] rotate( final int[][] piece ) {
        final int[][] res = new int[piece[0].length][piece.length];
        for (int x = 0; x < piece.length; x++) {
            for (int y = 0; y < piece[0].length; y++) {
                res[(res.length-1)-y][x] = piece[x][y];
            }
        }
        return res;
    }
    

    The starting piece:

    010
    111
    

    Here's rotate(piece):

    01
    11
    01
    

    Here's rotate(rotate(piece)):

    111
    010
    

    And here's rotate(rotate(rotate(piece))):

    10
    11
    10