我正在尝试制作一个基本的2D Rubik Cube 3x3,但是我遇到了方形颜色的问题,当我开始混合位置导致颜色不相应变化时出现问题,我不知道如何修复它
这是代码。非常感谢您的帮助和时间。
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == upLeft){
Collections.swap(squaresList, 0, 27);
Collections.swap(squaresList, 3, 30);
Collections.swap(squaresList, 6, 33);
Collections.swap(squaresList, 27, 18);
Collections.swap(squaresList, 30, 21);
Collections.swap(squaresList, 33, 24);
Collections.swap(squaresList, 18, 9);
Collections.swap(squaresList, 21, 12);
Collections.swap(squaresList, 24, 15);
// HERE IS WHERE I THINK THE PROBLEM IS...BUT I CANT SEE PAST THE PROBLEM
// I TRIED USING HASHMAP SO EACH SQUARE HAS A UNIQUE CODE FOR ITS COLOR BUT DIDNT WORK OUT...
for(int i = 0; i < squaresList.size(); i++){
if(i <= 8){
squaresList.get(i).setBackground(Color.WHITE);
}else if(i >= 9 && i <= 17){
squaresList.get(i).setBackground(Color.YELLOW);
}else if(i > 17 && i <= 26){
squaresList.get(i).setBackground(Color.BLUE);
}else if(i > 26 && i <= 35){
squaresList.get(i).setBackground(Color.RED);
}else if(i > 35 && i <= 44){
squaresList.get(i).setBackground(Color.GREEN);
}else if(i > 44 && i <= 53){
squaresList.get(i).setBackground(Color.ORANGE);
}
}
}
if(e.getSource() == upLeftRight){
Collections.swap(squaresList, 0, 45);
Collections.swap(squaresList, 1, 46);
Collections.swap(squaresList, 2, 47);
Collections.swap(squaresList, 45, 18);
Collections.swap(squaresList, 46, 19);
Collections.swap(squaresList, 47, 20);
Collections.swap(squaresList, 18, 36);
Collections.swap(squaresList, 19, 37);
Collections.swap(squaresList, 20, 38);
// HERE IS WHERE I THINK THE PROBLEM IS...BUT I CANT SEE PAST THE PROBLEM
// I TRIED USING HASHMAP SO EACH SQUARE HAS A UNIQUE CODE FOR ITS COLOR BUT DIDNT WORK OUT...
for(int i = 0; i < squaresList.size(); i++){
if(i <= 8){
squaresList.get(i).setBackground(Color.WHITE);
}else if(i >= 9 && i <= 17){
squaresList.get(i).setBackground(Color.YELLOW);
}else if(i > 17 && i <= 26){
squaresList.get(i).setBackground(Color.BLUE);
}else if(i > 26 && i <= 35){
squaresList.get(i).setBackground(Color.RED);
}else if(i > 35 && i <= 44){
squaresList.get(i).setBackground(Color.GREEN);
}else if(i > 44 && i <= 53){
squaresList.get(i).setBackground(Color.ORANGE);
}
}
}
}
答案 0 :(得分:1)
根据您提供的代码,我假设squareList包含正方形但不包含颜色值。您的方法的问题是您使用Collection.swap()
移动方块值,但您没有根据原始值分配颜色值,这意味着交换方块时不会交换颜色。
考虑以下示例。假设数字代表你的每个方格。
Original square list: {1(Black), 2(Blue), 3(Green), 4(Red)}
你正在按照Black-Blue-Green-Red的顺序排列这个名单。结果将是颜色按以下顺序:
Original colour list: {Black, Blue, Green, Red}
另一方面,执行交换后:
After swap, the square list: {3, 1, 2, 4}
但是你要按照相同的顺序给出颜色,这将是:
After swap, colour list: {Black, Blue, Green, Red}
所以你的sq 3有黑色,1有蓝色等,看起来颜色不是chaning。我建议用两种方法处理:一种是在数据中保留一个单独的颜色列表,并在交换方块时将它们交换在一起。并使用颜色列表中的顺序指定颜色。
另一个解决方案是为每个Square制作一个数据结构,其中包含颜色值。代码如下所示:
class Square
{
Color myColour;
// ...
}
使用这种结构,当你执行交换时,你正在做:
Original square list: {1(Black), 2(Blue), 3(Green), 4(Red)}
After swap, square list: {3(Green), 2(Blue), 1(Black), 4(Red)}
我希望这会有所帮助。