2

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);
    }
}
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;
}

コードの重複を減らしながら、より柔軟になったことに注意してください (ユーザーに設定可能な数の推測を与えることができます): ロジックの同じブロックを (わずかな違いで) 繰り返すのではなく、実際には繰り返すことができるロジックは 1 ビットだけです。何度でも。

于 2013-04-30T23:51:02.703 に答える