我正在用Java制作俄罗斯方块并正在努力旋转。
首先,我只是旋转了条形件。
我觉得我现在这样做的方式不仅仅是越野车,而是完全矫枉过正。但我不确定怎么回事。
首先,我有一个keylistener,它将int[] rotatedCoords
设置为calcRotation("right")
...如果向左旋转,rotationsCounter+=1;
将会减少。
if (keycode == KeyEvent.VK_D) {
int[] rotatedCoords = calcRotation("right");
rotationsCounter+=1;
clearCurrPosition();
rotate(rotatedCoords);
System.out.println(rotationsCounter);
if (rotationsCounter == 4) {
rotationsCounter = 0;
}
System.out.println(rotationsCounter);
}
calcRotation(String right or left)获取Piece中所有4个Tiles的当前坐标并将它们发送到int[] getRotation(String shape, String direction, int[] current X coords, int[] current Y Coords)
public int[] calcRotation(String direction) {
for (int i = 0; i < tile.length; i++) {
currPositionX[i] = tile[i].getX();
currPositionY[i] = tile[i].getY();
System.out.println(currPositionX[i] + ", " + currPositionY[i]);
}
return getRotation("Bar", direction, currPositionX, currPositionY);
}
然后getRotation []根据选择的旋转方向(向右或向左)设置新坐标,它是哪个形状,以及它在哪个旋转计数器上(0度,90度,180度或270 ...)< / p>
if (direction == "right") {
if (shape == "Bar") {
if (rotationsCounter == 0) {
currXs[0] += 1;
currYs[0] += -1;
currXs[1] += 0;
currYs[1] += 0;
currXs[2] += -1;
currYs[2] += 1;
currXs[3] += -2;
currYs[3] += 2;
rightRotate1 = new int[] {currXs[0], currYs[0], currXs[1], currYs[1], currXs[2], currYs[2], currXs[3], currYs[3]};
}
if (rotationsCounter == 1) {
... etc
然后适当地设置坐标(pieceRotations
):
//handle on left rotations
if (direction == "right") {
if (shape == "Bar") {
if (rotationsCounter == 0) {
pieceRotations = rightRotate1;
}
if (rotationsCounter == 1) {
pieceRotations = rightRotate2;
}
if (rotationsCounter == 2) {
pieceRotations = rightRotate3;
}
if (rotationsCounter == 3) {
pieceRotations = rightRotate0;
}
}
}
if (direction == "left") {
if (shape == "Bar") {
if (rotationsCounter == 0) {
pieceRotations = rightRotate3;
}
if (rotationsCounter == 1) {
pieceRotations = rightRotate0;
}
if (rotationsCounter == 2) {
pieceRotations = rightRotate1;
}
if (rotationsCounter == 3) {
pieceRotations = rightRotate2;
}
}
}
return pieceRotations;
}
最后,rotate(rotatedCoords)
将使用正确的坐标调用以旋转所有图块...
public void rotate(int[] rotatedCoordinates) {
int counterX = 0, counterY = 1;
if (movePieceValid()) {
for (int i = 0; i < tile.length; i++) {
tile[i].setLocation(rotatedCoordinates[counterX], rotatedCoordinates[counterY]);
counterX+=2;
counterY+=2;
}
} else {
for (int i = 0; i < tile.length; i++) {
tile[i].setLocation(currPositionX[i], currPositionY[i]);
}
}
}
因此,我目前根据left
或right
的每个形状的当前位置计算新坐标的方法显然有点过分。我可以遵循一般指南来大大简化吗?我想不出另一种方法来获得每个形状的位置?
答案 0 :(得分:4)
只有这么多件。试试这个:
public abstract class Piece {
public abstract void rotate(Direction dir);
}
public class BarPiece extends Piece {
public void rotate(Direction dir) {
// implement
}
}
public class TPiece extends Piece {
// ...
}
public class LeftSPiece extends Piece {
// ...
}
特殊似乎有点脏,但是一直做数学会很慢,因为只有很多可能的部分......