我知道这个问题已经被问了很多次,但我想知道如何旋转俄罗斯方块?我已经写了一个冗长且糟糕的解决方案(约170行代码),但应该有更简单的方法。
我的俄罗斯方块由4个方块组成,它们都知道它们在矩阵中的位置(行和列)。矩阵本身是char类型的,所以4个方块都是字母。例如,它看起来像这样:
......
..T...
.TTT..
......
我尝试将我的矩阵模拟成坐标系,通过计算中间行和列并将其用作原点,然后尝试应用我找到的这个简单算法:
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