
public class GuessingGame2 {

   static final int MAX = 100;   // The upper limit on the number
                                 //    that the computer chooses.
                                 
   static int gamesWon = 0;      // The number of games won by
                                 //    the user.

   public static void main(String[] args) {
      TextIO.putln("Let's play a game.  I'll pick a number between");
      TextIO.putln("1 and " + MAX + ", and you try to guess it.");
      boolean playAgain;
      do {
         playGame();  // call subroutine to play one game
         TextIO.put("Would you like to play again? ");
         playAgain = TextIO.getlnBoolean();
      } while (playAgain);
      TextIO.putln();
      TextIO.putln("You won " + gamesWon + " games.");
      TextIO.putln("Thanks for playing.  Goodbye.");
   } // end of main()            
   
   static void playGame() {
       int computersNumber = (int)(MAX * Math.random()) + 1;
            // The value assigned to computersNumber is a randomly
            // chosen integer between 1 and MAX, inclusive
       int usersGuess;      // this will be a number entered by user
       int guessCount = 0;  // number of guesses the user has made
       TextIO.putln();
       TextIO.put("What is your first guess? ");
       while (true) {
          usersGuess = TextIO.getInt();  // get the user's guess
          guessCount++;
          if (usersGuess == computersNumber) {
             TextIO.putln("You got it in " + guessCount
                     + " guesses!  My number was " + computersNumber);
             gamesWon++;  // Count this game by incrementing gamesWon.
             break;       // the game is over; the user has won
          }
          if (guessCount == 6) {
             TextIO.putln("Sorry, you didn't get the number in 6 guesses.");
             TextIO.putln("You lose.  My number was " + computersNumber);
             break;  // the game is over; the user has lost
          }
          // If we get to this point, the game continues.
          // Tell the user if the guess was too high or too low.
          if (usersGuess < computersNumber)
             TextIO.put("That's too low.  Try again: ");
          else if (usersGuess > computersNumber)
             TextIO.put("That's too high.  Try again: ");
       }
       TextIO.putln();
   } // end of playGame()
               
} // end of class GuessingGame
