方块从 rubiks 立方体中消失并旋转

tile disappearing from rubiks cube with rotation

我正在处理 2x2 rubik 立方体,但在使用我的程序旋转一侧时遇到了问题。立方体是一个二维正方形数组。我只是想逆时针转 90 度。

事情是这样的 https://imgur.com/a/tlskNKY

我改变了颜色,这样我就可以看到具体的方块以及它们是如何变化的。我试着改变顺序,一次移动特定的部分,看看问题是否只是重叠的部分(没有这样的运气)。

//square class

public class square implements Comparable {
    int c;
    private Rectangle r;
    int xpos, ypos, width, height;

    public square(int a, int x, int y) {
        c = a;
        xpos = x;
        ypos = y;

        r = new Rectangle(xpos, ypos, 50, 50);

    }
    //some unused methods
}

//inside the cube class
public class cube{

square[] temp = new square[4]

square[][] sq= new square[6][4]
//two for loops make squares and fills the sq 2d array
//the result is in the imgur link

public void turnVc(){

    temp= sq[2];

    sq[2][0]=temp[1];

    sq[2][1]=temp[3];

    sq[2][2]=temp[2];

    sq[2][3]=temp[0];

}
}

我希望输出是逆时针旋转的原始图像。

tmp 是指向与 sq[2] 指针相同的对象的指针。这就是为什么当您更改 sq[2] 内容时,您也会更改 tmp。 我认为您应该执行以下操作而不是分配 "temp= sq[2];":

temp = new square[4];
for (int i = 0; i < 4; i++) {
    temp[i] = sq[2][i];
}

编辑: 我认为你可以做的一点改进是你不需要保存所有的 sq[2] 数组,你只能保存第一个项目。我会这样做(tmp 现在是一个正方形,而不是一个数组):

tmp = sq[2][0];
sq[2][0] = sq[2][1];
sq[2][1] = sq[2][3];
sq[2][3] = sq[2][2];
sq[2][2] = tmp;

如果你的方块class实现了Cloneable,你应该尽可能使用clone()方法,它也类似于@Nguyen Tan Bao的回答,但更短 我猜你是 C++ 开发人员,Java 中的引用就像 C++ 中的指针,你可以研究更多玩得开心!