-1

我正在 javafx 中创建一个蛇游戏,但遇到了问题。我的游戏运行良好,但我不知道如何重置我的游戏(不关闭程序并重新运行它)。我创建了一个重置​​方法,它将所有变量重置回它们的初始值,并且它们除了蛇本身之外都可以工作。当我单击 ENTER 键(我的重置按钮)时,我的蛇会在其初始位置重生,但是旧的蛇身仍然存在,而我的新蛇无法生长。我相信这是因为我正在重置存储构成蛇的矩形的数组列表。

这是影响重置的我的代码片段:

public void reset() {
    SnakeBody.setX(150); //Reset the snake to its starting position
    SnakeBody.setY(150);

    Food.setX(600); //Reset the food to the starting position
    Food.setY(600);

    rightSpeed = 0;//Reset all speeds, making the snake still when the game resets
    upSpeed = 0;
    leftSpeed = 0;
    downSpeed = 0;
    SnakeSpeed = 4;

    if (canvas.getChildren().contains(SpeedBoost)) { //Removing the speedboost if it is in the canvas at the time of resetting.
        canvas.getChildren().remove(SpeedBoost);
    }

    if (canvas.getChildren().contains(ScoreMultiplier)) {
        canvas.getChildren().remove(ScoreMultiplier);
    }

    score = 0; //Resetting score.
    Score.setText("Score: " + score);

    Snakes.clear(); //Clearing the snake arraylist

    Snakes = new ArrayList<Rectangle>(); //Re initializing the same arraylit
    for (int i = Snakes.size() - 1; i > 0; i--) {

                Snakes.get(i).setX(Snakes.get(i - 1).getX());
                Snakes.get(i).setY(Snakes.get(i - 1).getY());

            }

    Objects(); //The method that creates the food, speed boost and multiplier.


}

此外,这是制作蛇的数组列表:

public ArrayList<Rectangle> makeSnakeBodies() {

    ArrayList<Rectangle> joints = new ArrayList<>();

    int x = 150;
    int y = 150;

    SnakeBody = new Rectangle(x, y, 30, 30);
    SnakeBody.setFill(Color.GOLD);
    SnakeBody.setStroke(Color.WHITE);
    joints.add(SnakeBody);

    return joints;

}

我是Java新手,所以任何帮助表示赞赏!谢谢!

编辑:完整代码:https ://pastebin.com/jpFf4wuq

4

1 回答 1

1

您可以使用

joints.clear():

方法见官方文档

但是,请确保您正在重置一个列表,该列表存储为对象的内部状态(它应该在某处声明为数据字段)

我无法从代码中看到您究竟在哪里执行此操作,但clear列表的所有方法都删除了所有元素。

还有一个建议,您可能必须重新渲染 UI,以便您能够看到不再绘制旧列表

于 2020-01-26T05:53:21.287 回答