2

我是一名学生,正在使用 JavaScript 创建一个 3-guess 游戏。我的游戏无法正常运行,我相信Math.random在游戏的每个阶段都会生成一个新号码。如果有人帮我为变量定义一个数字,我将不胜感激randomNumber

这是JavaScript:

function game() 
{
    var randomNumber = Math.floor(Math.random()*11);
    var userGuess = prompt ("Guess what number I'm thinking of? (It's between 0 & 10)");

    if (userGuess === randomNumber) 
    {
        alert ("Good Guess, you must be psychic!");
    } 
    else 
    {
        var userGuess2 = prompt ("Dohhh! You got it wrong. You have 2 more chances.");
    }

    if (userGuess2 === randomNumber) 
    {
        alert ("Good Guess, you must be psychic!");
    } 
    else 
    {
        var userGuess3 = prompt ("Dohhh! You got it wrong. You have 1 more chance.");
    }

    if (userGuess3 === randomNumber) 
    {
        alert ("Good Guess, you must be psychic!");
    } 
    else 
    {
        alert ("Bad luck. The number was: " + randomNumber);
    }
}
4

2 回答 2

6

prompt返回一个字符串。您正在使用严格相等运算符 ,===将字符串与数字进行比较。他们永远不会平等。

在与严格相等运算符进行比较之前,使用抽象相等运算符,==或将字符串转换为数字。

此外,您的函数可能应该return在正确猜测之后,而不是提示进行更多猜测。

于 2013-04-30T23:08:45.870 回答
2

以下是对代码的清理版本的建议:

function playGame(guesses)
{
    // By default, give the player 3 guesses.
    guesses = guesses || 3;

    var randomNumber = Math.floor(Math.random()*11);
    var userGuess = prompt("Guess what number I'm thinking of? (It's between 0 & 10)");

    // Repeat the following logic whenever the user guesses incorrectly.
    while (userGuess !== randomNumber.toString())
    {
        --guesses;
        if (guesses === 0)
        {
            alert("Bad luck. The number was: " + randomNumber);
            return false;
        }

        userGuess = prompt("Dohhh! You got it wrong. You have " + guesses + " more chance(s).");
    }

    alert("Good Guess, you must be psychic!");
    return true;
}

请注意,它现在更加灵活(您可以为用户提供可配置的猜测次数),同时还减少了代码重复:不是重复相同的逻辑块(差异很小),实际上只有一点逻辑可以重复你喜欢多少次。

于 2013-04-30T23:51:02.703 回答