我遇到的当前问题对于大多数人来说可能是一个简单的问题,但在使用函数时我似乎遇到了问题。我的目标是让游戏提示一个1到100之间的数字,如果这个人输入的数字无效,它会提醒他们并要求一个新号码。如果这个人在随机数上加了一个数字,它会告诉他们他们是高,并允许他们再次尝试,如果数字是低的话,也一样。
<!doctype html>
<html lang="en">
<head>
<title>Guess game</title>
<meta charset="utf-8">
</head>
<body>
<script>
var guess;
var randomNum = Math.floor(Math.random() * (100 - 1 + 1)) + 1;
var answer = false;
while(answer == false){
guess = prompt("Take a stab in the dark(1 to 100)");
wrongGuess(guess);
checkGuess(guess);
function wrongGuess(guess){
if(guess == null){
alert("Bye");
prompt.close;
}
else if(guess < 0 || guess > 100 || guess == "" || guess == " "){
alert("Write a valid number");
}
}
function checkGuess(guess){
if (guess > randomNum){
alert("Number is to High");
if (guess == randomNum){
answer = true;
alert("Grats Mate you hit the nail on the head");
}
else{
alert("That number is to low");
}
}
}
}
</script>
</head>
</html>
我知道它会询问这些数字,但它没有遵循功能规则来检查数字是否超过随机数,如果数字超出范围,它会提醒你。
答案 0 :(得分:0)
我修复了你的游戏:
var GUESSING_GAME = function () {
var guess = null, // don't leave your variables undefined
randomNum = Math.floor(Math.random() * 100) + 1, // -1 +1 did nothing
answer = false;
var checkGuess = function (guess) { // you can declare functions as variables
if (guess > randomNum) { // no need to nest conditionals here
alert("The number is too high.");
} else if (guess == randomNum) {
answer = true;
alert("Grats mate, you hit the nail on the head!");
} else if (guess < randomNum) { // let's add an explicit condition here
alert("The number is too low.");
} else {
answer = true; // see an explanation below
}
};
while (answer == false) {
guess = prompt("take a stab in the dark(1 to 100)"); // no need to guard against bad input here
checkGuess(guess);
}
}
之前,玩家实际上被迫猜测一个数字以便从while循环中断开。这就是为什么我添加了设置回答为true的else条件,从而终止了循环。当玩家输入任何数字时,游戏将停止。
如果您想通过点击某种按钮来运行游戏,请务必添加onclick属性:
<a href="#" onclick="GUESSING_GAME()">Start the game</a>
如果您的按钮已分配了ID,例如gamestart ...
<a href="#" id="gamestart">Start the game</a>
...您可以通过这种方式附加onclick事件:
document.getElementById("gamestart").addEventListener("click", function () {
GUESSING_GAME();
});
希望它有所帮助!