私はJavaでテトリスを作っていて、作品を回転させることに取り組んでいます。
まず、棒状のピースを回転させただけです。
今のやり方はバグがあるだけでなく、完全にやり過ぎだと感じています。しかし、他にどうすればいいのかわかりません。
まず、次のように設定するキーリスナーがあります...左に回転すると、代わりにデクリメントされます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) は、ピース内の 4 つのタイルすべての現在の座標を取得し、それらを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
明らかにやり過ぎです。それを大幅に簡素化するために従うことができる一般的なガイドはありますか? 各形状の位置を取得する別の方法が思いつきませんか?