gpt4 book ai didi

java - 为什么每次循环后我的数组都会重置为 0?

转载 作者:行者123 更新时间:2023-12-02 05:05:25 24 4
gpt4 key购买 nike

我正在尝试制作贪吃蛇游戏,但遇到了一些问题。我有这个包含游戏循环的线程,但它似乎不起作用。这是我的循环的简单形式,我简化了它,因为它一开始不起作用,但现在仍然不起作用。发生的情况是,我的 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;
}

}

最佳答案

因为循环的第一部分显式地将数组设置为零。注释掉它就像

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);

关于java - 为什么每次循环后我的数组都会重置为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27838792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com