簡體   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