仅使用Math.random生成的第一个数字

时间:2013-04-30 23:05:00

标签: javascript

我是一名学生用JavaScript创建一个3猜猜游戏。我的游戏无法正常运行,我相信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);
    }
}

2 个答案:

答案 0 :(得分:6)

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

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

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

答案 1 :(得分: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;
}

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