As in most HTML games, the real action happens when the user clicks a button. This form has two buttons, but one of them is hidden most of the time. For now, concentrate on the code that happens when the user clicks on the Check Your Guess button.

 function checkGuess(){
 //from numGuess.js
 //increment turns
 response = turns + ") ";
 //get guess from user
 guess = parseInt(txtGuess.value);
 if (guess < correct){
  response += "Too low";
 } else if (guess > correct){
  response += "Too high";
 } else if (guess == correct){
  response += "Correct!";
  //show again button = "block";
 } else {
  response += "Please enter a number between 1 and 100";
 } // end if
 output.innerHTML = response;
 } // end checkGuess

This function is a real powerhouse, but it isn't much of a mystery. Everything this function does was predicted by the design document. Here are the details:

  1. Increment the turn counter.

    Every time the user clicks the button, she’s taken a turn, so begin by adding one to the turn counter.

  2. Begin building the response.

    The main purpose of the checkGuess() function is to get input from the user and return some sort of output. That output will be stored in a string variable called response. Response begins with the turn number and a parenthesis.

  3. Get the guess from the text field.

    The user should have entered some value in the text box. Grab that value, convert it to an integer, and store it in the guess variable.

  4. Check to see if the guess is too low.

    Use an if statement to determine if the guess is less than the correct answer. Note how careful variable names make this a very easy line of code to understand. Just tell the user that the guess is too low by adding the message to response.

  5. Check to see if the guess is too high.

    If the guess is too high, all that's necessary is to inform the user.

  6. Check for a correct guess.

    If the user guesses correctly, there's a little more work to do, but none of it is very difficult.

  7. Tell the user she is correct.

    Add a congratulation message to the response variable.

  8. Show the Play Again button.

    If the game is over, you need a way to reset it so the user can play again. Simply show the Play Again button. When this button is clicked, it calls init(), which restarts the entire game (and rehides the Play Again button).

  9. Check for errors.

    You might think the user's guess would be too high, too low, or correct, but those aren't the only options. If the user does something crazy, the program should do something. The else clause catches any condition that wasn't caught by the previous tests. Just gently remind the user what input is required, and count it as a turn.