我正在制作一个2048克隆,但它拒绝合并不在第一行/列交互的块,经过进一步调查后我发现for循环不是正确地完成工作
用于演示目的的示例代码:
import java.util.Arrays;
public class teste{
public static void main(String[] args){
int[] gameBoard = new int[] {4,2,2,0} ;
gameBoard = pushLeft(gameBoard);
System.out.println(Arrays.toString(gameBoard));
}
public static int[] pushLeft(int[] gameBoard) {
System.out.println("Pushing left...");
// This one is the troublemaker
for (int y = 1; y < 4; y++) {
System.out.println("Y = " + y);
boolean[] alreadyCombined = { false, false, false, false };
if(gameBoard[y] != 0) {
int value = gameBoard[y];
int aux = y-1;
while ( (aux >= 0) && (gameBoard[aux] == 0)) {
aux--;
}
if (aux == -1) {
gameBoard[y] = 0;
gameBoard[0] = value;
}
else if (gameBoard[aux] != value && y-aux != 1) {
gameBoard[y] = 0;
gameBoard[aux+1] = value;
}
else if(gameBoard[aux] != value) {
break;
}
else {
if(alreadyCombined[aux]) {
gameBoard[y] = 0;
gameBoard[aux+1] = value;
}
else {
gameBoard[y] = 0;
gameBoard[aux] *= 2;
alreadyCombined[aux] = true;
}
}
}
}
return gameBoard;
}
此代码返回此输出:
Pushing left...
Y = 1
[4, 2, 2, 0]
正如你所看到的那样,它缺少Y = 2和Y = 3,这使得2个内部的两个人不能合并。有什么想法吗?
答案 0 :(得分:2)
您的代码通过
else if(gameBoard[aux] != value) {
break;
}
因此,因为value = 2
et和gameBoard[aux] = 4
所以中断会阻止您停止循环
您应该尝试打印这些值以查看问题所在
答案 1 :(得分:1)
代码
else if(gameBoard[aux] != value) {
break;
}
在第一次迭代gabeBoard[aux] (4)
中,而不是value (2)
。所以它正在经历休息。
答案 2 :(得分:0)
这个怎么样?它不是你要求的,而是你想要的更多: - )
public static void main(String[] args) {
int[] g = new int[] {4,2,2,0} ;
pushLeft(g);
System.out.println(Arrays.toString(g));
g = new int[] {0,0,2,2} ;
pushLeft(g);
System.out.println(Arrays.toString(g));
g = new int[] {4,2,0,0} ;
pushLeft(g);
System.out.println(Arrays.toString(g));
g = new int[] {0,0,0,0} ;
pushLeft(g);
System.out.println(Arrays.toString(g));
g = new int[] {0,0,0,2} ;
pushLeft(g);
System.out.println(Arrays.toString(g));
}
private static void pushLeft(int[] g) {
for (int i = 0; i < g.length; i++) {
// shift left
for (int j = i+1; j < g.length; j++) {
if (g[i] == 0 && g[j] > 0) {
g[i] = g[j];
g[j] = 0;
break;
}
}
// combine left
for (int j = i+1; j < g.length; j++) {
if (g[i] > 0 && g[i] == g[j]) {
g[i] *= 2;
g[j] = 0;
break;
}
}
}
}
打印:
[4, 4, 0, 0]
[4, 0, 0, 0]
[4, 2, 0, 0]
[0, 0, 0, 0]
[2, 0, 0, 0]