为什么我的数组在每次循环后都被重置为 0?

Why is my array being reset to 0 after each loop?

我正在尝试制作贪吃蛇游戏,但遇到了一些问题。我有这个包含游戏循环的线程,但它似乎不起作用。这是我的循环的一种简单形式,我对其进行了简化,因为它一开始不起作用,但现在仍然不起作用。发生的事情是我的 state 变量在第一个循环后重置为 0,我真的不知道为什么。我尝试了很多方法来修复它,但我似乎无法找到问题所在。

哦,是的,也不要看我的运行方法草率的开始,我正在尝试修复问题,但它变得相当丑陋。

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