如何重启JS游戏?

How to restart JS game?

我目前正在编写 JS 游戏。游戏结束后,我希望玩家能够单击 "go back to menu" 按钮,被定向到主页,然后能够单击播放并开始新游戏。我遇到的问题是我不确定点击播放后如何重新加载游戏。当我再次点击播放时,它会带我回到游戏结束屏幕,显示上一局的最终比分。

var keys = [];
var health = 100;
var score = 0;
var scene = "menu";
var clicked = false;
keyPressed = function() {
  keys[keyCode] = true;
};
keyReleased = function() {
  keys[keyCode] = false;
};

textFont(createFont("calibri", 35));

//Buttons
var button = function(cJ) {
  this.x = cJ.x;
  this.y = cJ.y;
  this.w = cJ.w;
  this.h = cJ.h;
};
button.prototype.mouseIsOver = function() {
  return (
    mouseX > this.x &&
    mouseX < this.x + this.w &&
    mouseY > this.y &&
    mouseY < this.y + this.h
  );
};
button.prototype.draw = function() {
  noStroke();
  textAlign(CENTER);
  if (this.mouseIsOver() === true) {
    fill(232, 232, 232);
    rect(this.x + 3, this.y - 3, this.w, this.h);
  } else if (this.mouseIsOver() === false) {
    fill(255, 255, 255);
    rect(this.x + 3, this.y - 5, this.w, this.h);
  }
};
var playButton = new button({
  x: width / 2 - 60,
  y: height / 2 + 21,
  w: 120,
  h: 45
});
var howButton = new button({
  x: width / 2 - 60,
  y: 284,
  w: 120,
  h: 45
});
var backButton = new button({
  x: width / 2 - 197,
  y: 365,
  w: 70,
  h: 30
});
var restartButton = new button({
  x: width / 2 - 102,
  y: 250,
  w: 200,
  h: 36
});

var menuC = function() {
  if (howButton.mouseIsOver()) {
    how();
  } else if (playButton.mouseIsOver()) {
    game();
  }
};
var howC = function() {
  if (backButton.mouseIsOver()) {
    menu();
  }
};
var loseC = function() {
  if (restartButton.mouseIsOver()) {
    Program.restart();
  }
};
mouseClicked = function() {
  if (scene === "menu") {
    menuC();
  } else if (scene === "how") {
    howC();
  } else if (scene === "lose") {
    loseC();
  }
};

//TEXT mic.
draw = function() {
  if (scene === "menu") {
    menu();
    //TITLE
    textSize(47);
    fill(41, 207, 182);
    text("ACIDIC RAIN", 207, 147);

    //Buttons
    playButton.draw();
    howButton.draw();

    textSize(30);
    fill(41, 207, 182);
    text("PLAY", 202, 248);
    text("HOW", 202, 311);
  }
  if (scene === "game") {
    game();
  }
  if (scene === "how") {
    how();
    backButton.draw();
    fill(41, 207, 182);
    textSize(17);
    text("BACK", 40, 380);
  }
  if (scene === "lose") {
    lose();
    restartButton.draw();
    fill(0);
    textSize(20);
    text("GO BACK TO MENU", 201, 270);
  }
};

那是因为你所有的变量都是在 "global" 范围内声明的(在 JS 的开头),所以调用任何像 game()menu() 这样的方法只会使这些方法重用来自这些变量的旧值。

我建议您将作为示例提供的整个代码包装在 "class" 中(制作变量和方法 - class 的属性)。这样,当单击按钮时,您可以轻松地销毁 class 的实例并在其位置重新创建一个新的 class (重置 class 实例中的所有局部变量,导致之前的所有进度都将被删除)。

参见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes