Bird Lives
Bird Lives

Reputation: 35

Use only the first number generated with Math.random

I'm a student creating a 3-guess game with JavaScript. My game doesn't work properly, I believe Math.random is generating a new number at every stage of the game. I would be most grateful if somebody helps me define a single number for the variable randomNumber.

Here's the 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);
    }
}

Upvotes: 2

Views: 193

Answers (2)

Dan Tao
Dan Tao

Reputation: 128317

Here's a suggestion for a cleaned-up version of your code:

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

Notice that it's now more flexible (you can give the user a configurable number of guesses) while also reducing code duplication: instead of repeating the same block of logic (with small differences), there is really just one bit of logic that can be repeated as many times as you like.

Upvotes: 2

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

prompt returns a string. You are using the strict equality operator, ===, to compare strings with numbers. They will never be equal.

Use the abstract equality operator, ==, or convert the strings to numbers before comparing with the strict equality operator.

Also, your function should probably return after a correct guess, rather than prompting for more guesses.

Upvotes: 6

Related Questions