如何阻止随机数重新生成?

时间:2014-02-18 06:04:39

标签: javascript

我正在创建一个孩子的数字猜谜游戏,其中生成一个随机数(1到50之间),你必须继续猜测数字,直到找到生成的数字。您会收到有关您的猜测是太高还是太低的反馈,以便更好地告知您的猜测。下面是我提出的代码,但问题是,我似乎无法确定随机数。似乎每次猜测都会重新生成数字。我怎样才能使每个猜测都使用相同的数字,直到猜到正确为止?

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro' rel='stylesheet' type='text/css'>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <form id ="game" action="javascript:void(checkGuess())">
        <p class="owlOne">I'm thinking of a number between 1 and 50.</p>
        <br class="clear" />
        <p class="owlTwo"><input id="guess" type="text"><input id="button" type="submit" value="Guess!"></p>
        <br class="clear" />
        <p class="owlOne"><span id="response">Can you guess what it is?</span></p>
    </form>

<script>
function checkGuess() {
    var guess = Number(document.getElementById('guess').value); // Assigns guessed number to variable.
    var number = Math.floor(Math.random() * 49 + 1); // Generates a random number between 1 and 50.

    // Guessed number is correct.
    if (guess == number) {
        document.getElementById("response").innerHTML= "Congratulations, you guessed correctly!";
    }

    // Guessed number is within 5 above.
    else if (guess > number && guess <= number+5) {
        document.getElementById("response").innerHTML= "You're so close! Just a little bit lower.";
    }

    // Guessed number is within 5 below.
    else if (guess < number && guess >= number-5) {
        document.getElementById("response").innerHTML= "You're so close! Just a little bit higher.";
    }

    // Guessed number is at least 1, but more than 5 below.
    else if (guess < number-5 && guess >= 1) {
        document.getElementById("response").innerHTML= "Too low! Guess again.";
    }

    // Guessed number is no more than 50, but less than 5 above.
    else if (guess > number+5 && guess <= 50) {
        document.getElementById("response").innerHTML= "Too high! Guess again.";
    }

    // Guessed number is not within the 1 - 50 range.
    else {
        document.getElementById("response").innerHTML= "Remember, the number I'm thinking of is between 1 and 50.";
    }
}
</script>

</body>
</html>

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

移动

var number = Math.floor(Math.random() * 49 + 1);

外部该功能。然后,只会在页面加载时生成数字,而不是每次调用函数时都会生成。

number将成为一个全局变量,也可以在函数内部访问。

答案 1 :(得分:0)

每次调用该函数时,它都会将数字重新定义为新的随机数。如果您在函数外部移动声明,则每次调用checkGuess时都不会重新定义声明;

您的代码应该类似于

 var number = Math.floor(Math.random() * 49 + 1); 

   function checkGuess() {
      // code
   }

但是您应该注意,这会将数字放在全局范围内,您也可以执行类似

的操作
var checkGuess = (function(number) {
   return function(){
      // code that was in checkGuess(){

   } 
})(Math.floor(Math.random() * 49 + 1));

这样做是否会将checkGuess函数返回给变量,但现在该代码可以访问数字变量,因为它位于closure内。