Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Making Decisions with Conditional Statements Improving the Random Number Guessing Game

Jacques Retief
Jacques Retief
954 Points

Just a post to brag

var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6 ) + 1;

var guess = prompt('I\'m thinking of a number between 1 and 6. What is it?');

if (parseInt(guess) === randomNumber ) {
  correctGuess = true;
} else if ( randomNumber > 3 ) {
  var guessTopRange = prompt('Try again. The number I am thinking of is more than 3');
  if (parseInt(guessTopRange) === randomNumber) {
      correctGuess = true;
  }
} else if ( randomNumber < 4 ) {
  var guessBottomRange = prompt('Try again. The number I am thinking of is less than 4');
  if (parseInt(guessBottomRange) === randomNumber) {
      correctGuess = true;
  }
}

if ( correctGuess ) {
    document.write('<p>You guessed the number!</p>');
} else {
    document.write('<p>Sorry. The number is ' + randomNumber + '.</p>');
}

Very happy with my 'mod' :D

2 Answers

Steven Parker
Steven Parker
231,271 Points

It seems to work well.

But it's curious that you wouldn't give a hint based on the first guess. If I guess 3 it may say "The number I am thinking of is less than 4". But I might expect it to say "The number I am thinking of is less than 3."

Jacques Retief
Jacques Retief
954 Points

Your answer makes me think of

String.prototype.replace()

and

String.prototype.split()

I chose to split down the middle between 1 and 6 :)

Jacques Retief
Jacques Retief
954 Points

So many variables to choose from!

What if your guess was 2, and the answer was 1?

The hint would have to be reframed.

Steven Parker
Steven Parker
231,271 Points

In that case, you would say "The number I am thinking of is less than 2." The number would always be the guess, only the "less" or "more" would change.

Jacques Retief
Jacques Retief
954 Points

Steven Parker, your enthusiasm keeps the light shining and that's what I like about you! Even if the hint points you to the obvious answer, I still feel the Joy in searching for the answer, and that is what makes you a great teacher. Thanks!