Javascript号码猜谜游戏

时间:2015-07-22 21:06:21

标签: javascript numbers

我无法在找到正确答案时让此代码提醒用户,也不能让弹出窗口继续循环再次播放。我将此编码为学习练习。在JS中我非常棒。

有人可以审核我的代码并提出建设性的批评吗?

// noprotect

var targetNumber = Math.floor(Math.random() * 100 + 1);

var userGuess = prompt("Pick a number from 1 to 100 to guess which one I'm  thinking about!" + " (6 guesses left.)");


for (var i=5; i>0; i--) {

if (i === 0) {
    prompt("Out of guesses!" + " (" + i + " guesses left.)" + " My number was: " + targetNumber);

}

if (isNaN(userGuess) === true) {
    userGuess = prompt("That value was not a number! Please pick a number from 1 to 100 to guess which one I'm thinking about!" + " (" + i + " guesses left.)");
}

if (userGuess < 1 || userGuess > 100) {
    userGuess = prompt("That number was not between 1 and 100 inclusive! Please pick a number from 1 to 100 to guess which one I'm thinking about!" + " (" + i + " guesses left.)");
}

if (userGuess === targetNumber) {
    userGuess = alert("You're correct! My number was: " + targetNumber);
}

if (userGuess < targetNumber) {
    userGuess = prompt("You're too low, guess again" + " (" + i + " guesses left.)");
}

if (userGuess > targetNumber) {

    userGuess = prompt("You're too high, guess again!" + " (" + i + " guesses left.)");
}

}

2 个答案:

答案 0 :(得分:4)

您正在使用prompt()将字符串值===返回与数字进行比较。那不行。

相反:

var userGuess = parseInt(prompt(...))

值得注意的是,prompt是一种非常笨重的方法。更好的方法是创建一个表单,其中有一个正确的<input>字段和一个放置响应的位置。

答案 1 :(得分:0)

在我从办公室回家之前添加快速说明。您的for循环永远不会允许i === 0条件通过,因为循环仅在i > 0时继续。您可能希望将其更改为i >= 0或调整循环中的条件。