[英]How to stop execution of a JavaScript program
因此,作为练习,我在 JavaScript 中做了一个猜谜游戏,你必须在 3 次尝试中猜测 1 到 10 之间随机生成的数字。 它工作得很好,但是当三个尝试完成时(或者用户猜到了数字),它又重新开始了。 我希望它在满足上述给定情况时停止。
这是代码:
function runGame() {
var isPlaying = true;
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying = true) {
runGame();
}
一些东西:
将 isPlaying 变量放在全局变量中。 尽管您也可以将其完全删除。 您已经有一个执行相同操作的 while 循环条件。 将您的尝试与零进行比较时删除等号。 否则,当尝试次数为零时,它将继续运行。 当用户猜对时使用break语句,否则猜中后仍会运行。
除了那些你的代码很好。 这是最终的代码:
function runGame() { var num = Math.floor(Math.random() * 10); var guess; var tries = 3; alert("You have 3 chances to guess a mindset between 1 and 10;"): while (tries > 0) { guess = prompt("Enter a guess;"); if (guess > num) { alert("Too high;"); } else if (guess < num) { alert("Too low;"); } else { alert("Exactly; " + num + " it is! You've won!"); break; } tries--; } } runGame();
= 在 JavaScript 中用于为变量赋值。 == 在 JavaScript 中用于比较两个变量。
所以将isPlaying = true
更改为isPlaying == true
就可以了。
while (tries >= 0)
在这里你可以使用 just while (tries > 0)
您也可以在 function 之外声明这些变量,但这不是必需的。
var isPlaying = true;
var tries = 3;
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
删除 isPlaying 并直接调用 runGame(),而不是在 while 循环中,如果机会完成,您可以中断执行,如果用户获胜,rest 会尝试
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
if (tries == 0) {
alert("You have finished your chances");
break;
}
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
} else if (guess < num) {
alert("Too low!");
} else {
alert("Exactly! " + num + " it is! You've won!");
// reset tries back to three
tries = 3;
}
tries--;
}
}
runGame();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.