繁体   English   中英

如何重启JS游戏?

[英]How to restart JS game?

我目前正在编写JS游戏。 游戏结束后,我希望玩家能够单击“返回菜单”按钮,定向到主页,然后能够单击“玩”并开始新游戏。 我的问题是我不确定如何在单击播放后重新加载游戏。 当我再次单击“播放”时,它将带我回到屏幕上,并具有上一播放的最终得分。

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

那是因为所有变量都在“全局”范围内(在JS的开头)声明,因此调用game()menu()类的任何方法只会使这些方法重用这些变量中的旧值。

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

请参阅: https//developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM