功能:
用户根据猜谜游戏输入颜色。当答案错误时提示会保持提示,只有当用户设置正确答案时提示才会退出。
我做了什么: 使用 while 循环来检查条件。 while循环中,设置while循环只有等于target时才结束,target是系统随机选取的颜色
问题: 提示最初将颜色设置为答案,但即使用户设置了正确答案,提示仍然循环。
当其中一种颜色设置后如何退出循环?
<html>
<head>
<title>Color Guessing Game</title>
</head>
<body onload="do_game()">
<script>
function do_game() {
var color = ["blue", "cyan", "gray", "green", "magenta", "orange", "red", "white", "yellow"];
var guess_input_text, guess_input, finished = false,
target, guesses = 0;
var target_index = color[0, 8];
target = target_index;
alert(target);
while (!finished) {
guess_input_text = prompt("I am thinking of these colors:" +
"\n\n blue, cyan, gray, green, magenta, orange, red, white, yellow" + "\n\n what color am I thinking of?");
guess_input = parseInt(guess_input_text);
guesses += 1;
finished = target;
}
}
</script>
</body>
</html>
最佳答案
尝试这段代码,如果输入与目标相同,则控制每一轮循环,如果它们相同,则完成为 true:
function do_game() {
var color = ["blue", "cyan", "gray", "green", "magenta", "orange", "red", "white", "yellow"];
var guess_input_text, guess_input, finished = false,
target, guesses = 0;
var rnd = Math.floor((Math.random() * 9) + 0); //Makes a random number between 0 and 8
target = color[rnd]; //sets the target to a random color from the color array
while (!finished) {
guess_input_text = prompt("I am thinking of these colors:" +
"\n\n blue, cyan, gray, green, magenta, orange, red, white, yellow" + "\n\n what color am I thinking of?"); //gets alert-input from user
guesses += 1;
if(guess_input_text == target){//checks if input from user and target are the same
finished = true;
}
}
}
关于javascript - 即使条件满足后,while 循环也不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34172221/