我正在尝试制作一个蛇游戏,但我遇到了一些问题。我有这个包含游戏循环的线程,但它似乎没有用。这是我循环的一个简单形式,我简化了它,因为它最初没有工作,但它仍然没有。发生的事情是我的state
变量在第一个循环后重置为0,我真的不知道为什么。我尝试了很多方法来修复它,但我似乎无法找到问题。
哦,是的,也不要看看我的run方法的草率开始,我正在尝试解决问题并且它变得相当难看。
public void run() {
alive = true;
keyPressed = 2; // Right
keyPressedBefore = 2;
field = Gui.getPanelArray();
state = new int[20][20];
newstate = new int[20][20];
previous = new int[20][20];
coordw = new int[20*20];
coordh = new int[20*20];
length = 2;
width = height = 20;
for (int w = 0; w < 20; w++) {
for (int h = 0; h < 20; h++) {
state[w][h] = 0;
}
}
state[0][0] = 1;
render(state,field);
previous = state;
newstate = state;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
loop();
}
private void loop() {
while (alive) {
for (int w = 0; w < 20; w++) {
for (int h = 0; h < 20; h++) {
newstate[w][h] = 0;
}
}
if (keyPressed == 0) {
for (int w = 0; w < 20; w++) {
for (int h = 0; h < 20; h++) {
if (state[w][h] == 1) {
newstate[w][h-1] = 1;
}
}
}
} else if (keyPressed == 1) {
for (int w = 0; w < 20; w++) {
for (int h = 0; h < 20; h++) {
if (state[w][h] == 1) {
newstate[w-1][h] = 1;
}
}
}
} else if (keyPressed == 2) {
for (int w = 0; w < 20; w++) {
for (int h = 0; h < 20; h++) {
if (state[w][h] == 1) {
newstate[w][h+1] = 1;
}
}
}
} else if (keyPressed == 3) {
for (int w = 0; w < 20; w++) {
for (int h = 0; h < 20; h++) {
if (state[w][h] == 1) {
newstate[w+1][h] = 1;
}
}
}
}
render(newstate, field);
state = newstate;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//keyPressedBefore = keyPressed;
}
}
答案 0 :(得分:2)
因为循环的第一部分显式地将数组设置为零。像
一样评论它while (alive) {
// for (int w = 0; w < 20; w++) {
// for (int h = 0; h < 20; h++) {
// newstate[w][h] = 0;
// }
// }
另外,不要只在这里指定引用
// state = newstate;
state = Arrays.copyOf(newstate, newstate.length);