编程语言
首页 > 编程语言> > Java Tetris旋转

Java Tetris旋转

作者:互联网

我知道有人问过很多,但我想知道如何旋转俄罗斯方块?
我已经做了一个漫长而糟糕的解决方案(约170行代码),但是应该有更简单的方法可以做到这一点.

我的俄罗斯方块碎片由4个块组成,这些块都知道它们在矩阵中的位置(行和列).矩阵本身是char类型的,因此4个块都是字母.例如:

......
..T...
.TTT..
......

我试图通过计数中间的行和列并将其用作origo来将矩阵模拟为坐标系,然后尝试应用这个发现的简单算法:
90度旋转(x,y)=(-y,x)

看来,只有当我的作品在矩阵的中心时,它才起作用.我不知道该怎么办,我整天都在想.这是我的方法:

public void rotatePiece(ArrayList<Block> random) {
        int distance = 0; // how far is the origo

        for (int i=0; i < 4; ++i)
            board[random.get(i).getRow()][random.get(i).getColumn()] = '.';  // erases the current location of the piece

        for (int i=0; i < 4; ++i) {
            distance = Math.abs(random.get(i).getColumn()-middleColumn);

            if (random.get(i).getColumn() < middleColumn)
                random.get(i).setColumn(random.get(i).getColumn()+(distance*2)); // "throws" the location of the block to the other side of the origo
            else
                random.get(i).setColumn(random.get(i).getColumn()-(distance*2));

            int help = random.get(i).getColumn();
            random.get(i).setColumn(random.get(i).getRow());  // (x, y) = (-y, x)
            random.get(i).setRow(help);
        }

         for (int i=0; i < 4; ++i)
            board[random.get(i).getRow()][random.get(i).getColumn()] = random.get(0).getStyle(); // saves the new location of the piece in the matrix

解决方法:

我建议为每个块组定义四个状态.

enum ROTATION {
    UP, DOWN, LEFT, RIGHT;

    ROTATION rotateLeft() {
        switch(this) {
             case UP: return LEFT;
             case LEFT: return DOWN;
             case DOWN: return RIGHT;
             case RIGHT: return UP;
        }
        return null; // wont happen;
    }

    ROTATION rotateRight() {
        ROTATION r = this;
         // wow I'm lazy, but I've actually seen this in production code!
        return r.rotateLeft().rotateLeft().rotateLeft();
    }
}

abstract class Brick {
    Point centerPos;
    ROTATION rot;
    abstract List<Point> pointsOccupied();
}

class TBrick extends Brick {

    List<Point> pointsOccupied() {
        int x = centerPos.x();
        int y = centerPos.y();
        List<Point> points = new LinkedList<Point>();
        switch(rot) {
            case UP: points.add(new Point(x-1,y);
                     points.add(new Point(x,y);
                     points.add(new Point(x+1,y);
                     points.add(new Point(x, y+1);
                break;
            case Down: points.add(new Point(x-1,y);
                       points.add(new Point(x,y);
                       points.add(new Point(x+1,y);
                       points.add(new Point(x, y-1);
                break;
            // finish the cases
        }

   }

}

标签:matrix,rotation,tetris,java
来源: https://codeday.me/bug/20191102/1993955.html