// Exercise 12.21 Solution

// GuessGame.java

// Guess the number

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;



public class GuessGame extends JFrame {

   private int number, guess;

   private int highest, lowest;

   private JTextField guessInput;

   private JTextField message;

   private JLabel text1, text2;

   private JButton newGame;



   public GuessGame()

   {

      super( "Guess Game" );

      text1 = new JLabel( "I have a number between 1 and 1000." );

      text2 = new JLabel( "Can you guess my" +

                         " number? Enter your Guess:" );



      highest = 0;

      lowest = 1000;

      guessInput = new JTextField( 5 );

      guessInput.addActionListener( new GuessHandler( ) );

      message = new JTextField( "<------------------", 15 );

      message.setEditable( false );



      newGame = new JButton( "New Game" );

      newGame.addActionListener(

         new ActionListener() {

            public void actionPerformed( ActionEvent e ) {

               message.setText( "<------------------" );

               guessInput.setText( "" );

               guessInput.setEditable( true );

               theGame();

            }

         }

      );



      Container c = getContentPane();

      c.setLayout( new FlowLayout() );

      c.add( text1 );

      c.add( text2 );

      c.add( guessInput );

      c.add( message );

      c.add( newGame );

      setSize( 300, 200 );

      show();

      theGame();

   }



   public void theGame()

   {  number = ( int ) ( Math.random() * 1000 + 1 );  }



   public static void main( String args[] )

   {

      GuessGame app = new GuessGame();



      app.addWindowListener(

         new WindowAdapter() {

            public void windowClosing( WindowEvent e )

            {

               System.exit( 0 );

            }

         }

      );

   }



   class GuessHandler implements ActionListener

   {

      public void actionPerformed( ActionEvent e )

      {

         guess = Integer.parseInt( guessInput.getText() );



         if ( guess > number ) {

            message.setText( "Too High" );



            if ( guess < lowest ) {

               lowest = guess;

               setBackground( Color.red );   // warmer

            }

            else

               setBackground( Color.blue );  // colder

         }

         else if ( guess < number ) {

            message.setText( "Too Low" );



            if ( guess > highest ) {

               highest = guess;

               setBackground( Color.red );   // warmer

            }

            else

               setBackground( Color.blue );  // colder

         }

         else {

            message.setText( "Correct!" );

            setBackground( Color.white );

            guessInput.setEditable( false );

            lowest = 1000;

            highest = 0;

         }


         repaint();

      }

   }

}
