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

Need help with my JavaScript Guessing Game

I am having trouble with my code. I want to create a guessing game but I don't know where my code is messing up at. Can anyone help me?

<html>

<head>
<title>Guess | JavaScript Game</title>
    <link href="guess.css" rel="stylesheet">
    <link href="normalize.css" rel="stylesheet">
</head>

<body>
<h1>Take A Guess</h1>

<fieldset>
<p>Welcome, Agent 0015. Your mission, if you choose to accept, will be to guessing a number between 1 and 100. You get 10 tries, if you fail to guess correctly your computer will self destruct.</p>
<input type="text" id="guess" onchange="myGuess(this.value, 'guess')" placeholder=" 1 - 100 "><br>
<button type="button">Guess</button>
<button type="button" onclick="ClearFields();">Reset</button>    
</fieldset>

<fieldset><p>Your current status</p>
<output id="number"></output>    
</fieldset>    
<script>

/*Generate a random number between 1 and 100.*/
number = Math.round((Math.random() * 100))%100  + 1;

function myGuess (guess){
  var numberGuess = document.getElementById('number');
  var guess = document.getElementById('guess').value;
}
/* Do this loop for each guess. Leave the loop when the guess is */

counter = 0;
do
    {
    counter++;

    guess = HTMLInputElement("What's your guess?");
    number.innerHTML("Guess #"+counter+" was "+guess+"<BR>");

    if (guess == number) {
        number.innerHTML("You guessed it!<BR>");
        }
    else  {
        if (guess < number)  {
            number.innerHTML("Too small, guess again.<BR>");
            }
        else  {
            number.innerHTML("Too big, guess again.<BR>");
            }
        }       
    } 
    while (counter <10 && guess != number);

if (guess != number) {
        number.innerHTML("I fooled you 10 times - the number was " + number+".<BR>");
        }

function ClearFields() {

     document.getElementById('guess').value = "";
}

</script>
</body>
</html>
I want people to be able to:
* Enter a number
* Display their guess wither its right or wrong
* Then top if they guess correct or after 10 wrong answers

3 Answers

Hi Phillip,

To be honest, there was quite a bit wrong with everything about your code. Not only what was pointed out in the answers already, but logic errors and wrong attributes in elements. But that's why I've come to help. I rewrote your game into a little codepen you can play with below. I wrote lots of comments so check those out to see what I did for ya!

http://codepen.io/anon/pen/YXVZXb

Thank you for all your help! The commenting really helped me.

I am still having trouble with the "reset" button. I want the button to reset the game and generate a new random number.

Here is what I tried to clear the status output.

/* Clear/Reset the text field */    
function clearFields() {
    guessInput.value = "";
    statusOutput.value = "";
    counter;
  //added to put function out of call stack
  return false;
} 

You're very welcome, Phillip!

Here's the code for the clearFields() function that I updated the codepen with, as well.

/* Clear/Reset the text field */    
function clearFields() {
  //reset guess value
  guessInput.value = "";
  //reset counter variable to 0
  counter = 0;
  //reset the text of status output back to the default text in the HTML
  statusOutput.value = "You have yet to guess anything.";
  //set randomNumber to be a new random number
  randomNumber = Math.floor(Math.random() * 100) + 1;
  //added to put function out of call stack
  return false;
}

Also, I'm sure you noticed that I greatly changed the code for your random number generation. I wrote up an article on that and posted it here on Treehouse as an answer, but I couldn't find it :( If you have any questions about how that piece of code operates, I'll explain the math and logic behind it. Also, if you have any other questions, feel free to ask.

I did a major update to the checkGuess() function so that blank guesses don't get counted. I updated the comments, too!

I don't know what happened to your article, but I would love to take a look at it. Try posting it again.

I would also love to know about the math a logic behind the code, every little thing helps.

I uploaded the final game >> Game

Thanks for all your help. JavaScript has defiantly been a challenge for me.

It looks awesome, Phillip! I just used that codepen link I gave you in the original answer, but I updated one if statement inside the checkGuess() function so that there has to be a value inside the guess input in order for the number of tries to increment.

And here is the codepen link again: http://codepen.io/anon/pen/YXVZXb

function checkGuess() {
  //cache guess value temporarily for function and store as integer
  var guessVal = parseInt(guessInput.value);
  //check to see if counter is less than 10 and that guessVal is not empty
  //by just putting "guessVal" the compiler makes sure that "guessVal" is a truthy value
  //there is a video here on Treehouse about truthy and falsey values: https://teamtreehouse.com/library/javascript-booleans
  //here is a great article about truthy/falsey values: http://www.sitepoint.com/javascript-truthy-falsy/
  if (counter < 10 && guessVal) {
    //add 1 to counter variable
    counter++;
    if (guessVal < randomNumber) {
      //change the status text
      statusOutput.value = "Too small! Guess again.";
    }
    if (guessVal > randomNumber) {
      //change the status text
      statusOutput.value = "Too large! Guess again.";
    }
    if (guessVal === randomNumber) {
      //change the status text
      statusOutput.value = "You guessed the correct number! It was " + randomNumber + "."
      +  " It only took you " + counter + " tries to get right.";
    }
  }
  //if counter has reached 10
  //10 tries have occurred and user couldn't guess correctly
  else if (counter === 10) {
    //update the status
    statusOutput.value = "You weren't able to guess the correct number, and your computer is going to self destruct! The number was " + randomNumber;
  }
    //puts function out of call stack
    return false;
}

You'll want to add the extra statement I put in that counter < 10 if statement to your code so that people can't accidentally use up tries without putting in some kind of value.

And so the logic behind using all of those functions and mathematics in that way starts like this: Math.floor() is used as the outer function to give a consistent minimum value for the range we want. Inside the Math.floor() function, we multiply a base number (let's call it N) times the Math.random() function to get a range of [0,N-1] (brackets means inclusive of the values). We get 0 as the minimum value because Math.random() will get very close to 0 (technically it can reach 0 although it is rare) and then Math.floor() will take the number down to 0. The maximum is "N-1" because Math.random() can reach to around 0.9999.... (never 1) and so if you take any number and multiply it by 0.999... and then round down, you will get the number right below it. In other words, the number minus 1.

By adding 1 to the multiplication done on the outside, you add 1 to both the minimum and maximum values. So, the range becomes [1, N] (remember it was [0, N-1]).

Keep in mind that this formula only works for the number 1 as the minimum value. If you want a range that has a minimum of any other number than 1, you'll have to use a bit more complex of a formula to achieve that range.

This is the standard formula for creating a range of random numbers from a given minimum value to a given maximum value:

//generates numbers from a given minimum to a given maximum, inclusive of both numbers
Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;

Hey Phillip,

Cool project!

First things I notice:

  • innerHTML is a property, not a method, so you have to do something like number.innerHTML="text here"
  • You're trying to set the innerHTML for number, but number is just an int in your script, not an html element. I assume you mean numberGuess, which isn't a great name - I would probably give it a more intuitive name like status.
  • I'm not sure what this line of code is for, and it's probably causing trouble: guess = HTMLInputElement("What's your guess?");

Fix these and maybe do some other trouble shooting. Let me know if you get it to work!

So, I made some changes but I still can't figure out what else is wrong. I want the game to make people input numbers in the text field and then get their results but I can't get the text field to work and not its automatically running the results on its own.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Guess | JavaScript Game</title>
    <meta charset="utf-8">
    <link href="guess.css" rel="stylesheet">
    <link href="normalize.css" rel="stylesheet">
</head>

<body>
<h1>Take A Guess</h1>

<fieldset>
<p>Welcome, Agent 0015. Your mission, if you choose to accept, will be to guessing a number between 1 and 100. You get 10 tries, if you fail to guess correctly your computer will self destruct.</p>
<input type="text" id="guess" onchange="status(this.value, 'guess')" placeholder=" Guess 1 thru 100 "><br>
<button type="button">Guess</button>
<button type="button" onclick="ClearFields();">Reset</button>    
</fieldset>

<fieldset><p>Your current status</p>
<output id="status_output"></output>    
</fieldset>    

<script>

/*Generate a random number between 1 and 100.*/
number = Math.round((Math.random() * 100))%100  + 1;

function status (guess){
  var status = document.getElementById('status_output');
  var guess = document.getElementById('guess').value;
}

/* Do this loop for each guess. Leave the loop when the guess is */    

counter = 0;
do
    {
    counter++;

    guess = status("What's your guess?");
    document.write("Guess #"+counter+" was "+guess+"<BR>");

/* If guess is correct is blank or doesn't have a number value "Congratulations Agent 0015" */

    if (guess == number) {
        document.write("Congratulations Agent 0015, you guessed correctly!<BR>");
        }    
    else  {
        if (guess < number)  {
            document.write("Too small, guess again.<BR>");
            }
        else  {
            document.write("Too big, guess again.<BR>");
            }
        }       
    } 
    while (counter <10 && guess != number);

if (guess != number) {
        document.write("I fooled you 10 times - the number was " + number+".<BR>");
        }

/* Clear/Reset the text field */    
function ClearFields() {

     document.getElementById('guess').value = "";
}

</script>
</body>
</html>

The main problem is attempt to access this method of a number (?) inside if statement:

   number.innerHTML("I fooled you 10 times - the number was " + number+".<BR>");

Because you "number" is Number()

number = Math.round((Math.random() * 100)) % 100 + 1;

It seems you need numberGuess variable instead.

Also, have no idea what this line of code meaning is:

    guess = HTMLInputElement("What's your guess?");

BTW, my Chrome also have no idea what is the meaning of this code lines. Could you explain what you've tried to do?

I was originally going to do

guess = prompt("What's your guess?");

but I want the guess to come from the input field in the html document