在JavaScript中创建一个随机数生成器游戏,无法使While循环保持循环



我正在尝试创建一个数字生成器游戏,其中用户有5个猜测来猜测正确的数字(在1到10之间)。我的代码是:

/* Random number generator that compares itself with the user input */
var randomGenerator = Math.floor(Math.random() * 10) + 1;
var turns = 5;
while (turns > 0); {
  var user = prompt("Pick a number between one through ten");
  var userInput = parseInt(user);
  if(userInput === randomGenerator) {
    alert("You got it!");
    turns = 0;
  } else if (userInput > randomGenerator) {
    alert("Guess lower!");
    --turns;
  } else if (userInput < randomGenerator) {
    alert("Guess higher!");
    --turns;
  }
}
alert("The number was " + randomGenerator);

代码运行一次并停止。我希望它一遍又一遍地运行,直到他们猜不到或猜到正确的数字。

while后面有分号删除它,它将工作得很好

我会为浏览器做这样的事情。。。。

// browser with jquery
(function() {
     var guesses = 5;
     var myRandomNumber = random; // Get random number however you choose
     $('#guessInput').on('submit', function (e) {
           var guess = $(this).val(); 
           if( guess == myRandomNumber ) {
                 // show user congratulations
           } else {
                 guesses -= 1;
           }
           if (guesses === 0) {
                 // say sorry you are out of guesses
                 $(this).prop("disabled", true);
           }
     });
}());

你必须将其链接到一个实际提交的按钮,然后测试输入,而不是我给你的。

最新更新