javascript - 如何重启JS游戏?
问题描述
我目前正在编写一个 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/en-US/docs/Web/JavaScript/Reference/Classes
推荐阅读
- python - 未找到名称为“Read Csv File To List”的关键字
- tensorflow - 根据 TENSORFLOW 中的 if 语句使用不同的优化器
- php - 我正在使用带有 WSDL 和 Nusoap 的 Moodle,但我无法连接,因为我的代码中有错误
- wpf - 从 Grid.Row\Column DependencyProperty 中提取索引
- java - 递增变量多线程
- nginx - 如何将多个文件上传到nginx?
- powershell - 如果存在“关键字”,则重新运行批处理文件
- python - 在 python 中使用带有间隔描述的表对 DataFrame 中的值进行编码
- ionic2 - Ionic2:未捕获(承诺):无效链接:日历
- iot - 引导加载程序代码 stm32 控制器