我正在用 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...)设置新坐标
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
是矫枉过正。有没有我可以遵循的一般指南来大大简化它?我想不出另一种方法来获得每个形状的位置?