LoveHate2Code
LoveHate2Code

Reputation: 1

guessing game in javascript using while loop and unlimited guesses

var x = Math.floor(Math.random() * 100) + 1;
var hint = 'Guess my number, 1-100!';
var userIsGuessing = true;

while (userIsGuessing) {
    var guess = prompt(hint + ' Keep guessing!');
    userIsGuessing++;
    if (guess < x && (x - guess) < 15) hint += ' A little too small!';
    else if (guess < x && (x - guess) >= 15) hint += ' Way too small!';
    else if (guess > x && (x - guess) < 15) hint += ' A little too big!';
    else if (guess > x && (x - guess) >= 15) hint += ' Way too big!';
    else(guess === x); {
        document.writeln("You win! It took you" + userIsGuessing + " times to
            guess the number.
            ");
        }
    }

I am trying to get this code to ask the user to guess a number between 1 and 100. Each time the user guesses, they get one of four hints. Then at the end, when they guess correctly, they will be told how many guesses it took them. I'm really stuck, please help.

Upvotes: 0

Views: 1470

Answers (1)

Aks
Aks

Reputation: 395

How to begin..

  • userIsGuessing is a boolean, you should never use ++ on it.
  • You are writing in the document that the user win, you should alert it, like the prompt but ok.
  • Do not increment your hint, the ergonomics is terrible.

Check the comment

var x = Math.floor(Math.random() * 100) + 1;
var hint = 'Guess my number, 1-100!';
var userIsGuessing = false; // Boolean, begin at false
var count = 0; // Will count the try of the users

while (!userIsGuessing) {
    var guess = prompt(hint + ' Keep guessing!'); count++; // We increment count
    if(guess == x) { // CHECK IF RIGHT FIRST. EVER FOR THIS KIND OF STUFF.
        userIsGuessing = true; // If right, then the Boolean come true and our loop will end.
        alert("You win! It took you" + count + " times to guess the number.");

    }
    if (guess < x && (x - guess) < 15) hint = ' A little too small!';
    else if (guess < x && (x - guess) >= 15) hint = ' Way too small!';
    else if (guess > x && (x - guess) < 15) hint = ' A little too big!';
    else if (guess > x && (x - guess) >= 15) hint = ' Way too big!';
}

Upvotes: 2

Related Questions