javarotationrubiks-cube

tile disappearing from rubiks cube with rotation


I'm working on a 2x2 rubik cube, and was having trouble getting one side rotate with my program. The cube is a 2d array of squares. I'm just triying to do a 90 degree counter clockwise turn.

This is what happens https://i.sstatic.net/78Xqg.jpg

I changed the colour so I could see the specific squares and how they changed. I tried changing the order, moving specific pieces at a time to see if the problem was just overlapping pieces (no such luck).

//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];

}
}

I expect the output to be the original image turned counter clockwise.


Solution

  • tmp is a pointer that points to the same object that sq[2] pointers. That's why when you change sq[2] content, you change tmp's as well. i think instead of assign "temp= sq[2];" you should do the following:

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

    Edit: i think a little improvement you could do is that you don;t need to save all the sq[2] array, you could only save the fist item. i would do like this (tmp is now a square, not an array):

    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;