我正在 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