You are Here!
HOME | Topics | References | Contact Us

JAVA

Java is an object oriented language developed by SUN computer. Here is a sample JAVA program which plays a number guessing game. The program picks a number and allows you several tries to guess it. If you are too high or too low, the program will let you know and you can guess again. If you guess the number before you run out of tries, you win.

Right click here to download a copy of the program. If you don't know how to complile a Java program, go to the Sun Java Site for instructions on obtaining and using a Java compiler.

One small technical note, the program running on this page has been converted to an applet which allows it to run on a web page. The version below is the stand alone version.
/*
 * Guessing Game 
 */

   import javax.swing.JButton;
   import javax.swing.JFrame;
   import javax.swing.JTextField;
   import javax.swing.JPanel;
   import javax.swing.border.*;
   import java.awt.*;
   import java.awt.event.*;
 
 
    public class GuessingGame extends JFrame implements ActionListener {
    
    /*
     * Note: MAX_NUMBER should be equal to ROWS * COLS  You can change these values to
     * create a larger game board.  For example, try using the following assignments:
     * ROWS = 16, COLS = 16, MAX_NUMBER = 256, NUM_TRIES = 7
     */
      
    //constants
      private static final boolean WIN=true, LOSS=false;
      private static final int ROWS = 5, COLS = 5, MAX_NUMBER = 25, NUM_TRIES = 4;
     
    //fields  
      private Container content;
      private JPanel northPanel,centerPanel,southPanel;
      private JTextField banner,score;
      private int secretNumber,wins,losses,tries;
      private JButton jbArray[],resetButton;
      private boolean waitingForReset=false; 
   	
       public GuessingGame() //constructor
      {  
         wins=0;
         losses=0;
         resetButton = createResetButton();
         banner = createJTextField(" You have "+NUM_TRIES+" tries to guess the hidden number ");
         banner.setHorizontalAlignment(JTextField.CENTER);
         score = createJTextField("   Wins: "+wins+"  Losses: "+losses+"  ");
         score.setHorizontalAlignment(JTextField.CENTER);
         content = getContentPane();
         content.setLayout(new BorderLayout());
         northPanel = new JPanel();
         centerPanel = new JPanel();
         southPanel = new JPanel();
         content.add(northPanel,BorderLayout.NORTH); 
         northPanel.add(banner);
         content.add(southPanel,BorderLayout.SOUTH);
         southPanel.setLayout(new FlowLayout());
         southPanel.add(resetButton);	
         southPanel.add(score);
         content.add(centerPanel,BorderLayout.CENTER);
         centerPanel.setLayout(new GridLayout(ROWS,COLS));
         jbArray = new JButton[MAX_NUMBER+1];
         for (int i=1;  i<=MAX_NUMBER; i++)
         {
            jbArray[i]=(JButton)createGameButton(i);
            centerPanel.add(jbArray[i]);
         }      	
         resetGame();  
      }
         
   	/*
   	 * resetGame
   	 *
   	 * Resets the game board for the next game.
   	 *
   	 */
   	    		
       private void resetGame()
      {
         resetButton.removeActionListener(this);
         waitingForReset=false;
         tries=NUM_TRIES;
         tryMessage(tries);
         secretNumber= (int) (Math.random()*MAX_NUMBER+1); //Picks the Number to be Guessed
         activateAllGameButtons();
       // For Testing: System.out.println("The secret number is "+secretNumber);
      }
   
       private JTextField createJTextField (String s)
      {
         JTextField temp = new JTextField(s);
         temp.setFont(new Font("Helvetica",Font.PLAIN,14));
         temp.setBorder(new EmptyBorder(10,10,10,10));
         temp.setEditable(false);
         return(temp);
      }
   	
       private JButton createResetButton()
      { 
         JButton temp = new JButton("Reset");
         temp.setFont(new Font("Helvetica",Font.PLAIN,12));
         temp.removeActionListener(this);
         return(temp);
      }
      
       private JButton createGameButton (int i)
      {
         String s=Integer.toString(i);
         JButton temp = new JButton(s);
         temp.setFont(new Font("Helvetica",Font.PLAIN,12)); 
         temp.setForeground(Color.black);			//set color of the game button text
         temp.setBackground(Color.yellow);			//set the game button background color
         return(temp);
      }
   
       public void actionPerformed(ActionEvent e)	//Returns the pushed button #
      {
         if (waitingForReset==true) resetGame();
         else
         {
            String textInButton = ((JButton)e.getSource()).getText();
            int numberOfButton=Integer.parseInt(textInButton);
            processNumberSelect(numberOfButton);
         }
      }
   	
       private void processNumberSelect (int guess)
      {
         if (guess==secretNumber) gameWon(); 
         else
            if (--tries <= 0 ) gameLost(); 
            else {
               tryMessage(tries);
               if (guess<secretNumber){
                  for (int i=1;i<=guess;i++) deactivateGameButton(i) ;
               }
               else
                  for (int i=guess;i<=MAX_NUMBER;i++) deactivateGameButton(i) ;
            }	
      			
      }
   	
       private void gameWon()
      {	         
         for (int i=1;i<=MAX_NUMBER;i++)
         {
            jbArray[i].removeActionListener(this); 
            if (i==secretNumber) jbArray[i].setBackground(Color.green);
            else
            {
               jbArray[i].setForeground(Color.red);
               jbArray[i].setBackground(Color.red);
            }
         } 
         banner.setText("Winner, Winner, Chicken Dinner!");
         updateScoreboard(WIN);
         waitingForReset=true;
         resetButton.addActionListener(this);
      } 
      
       private void gameLost()
      {
         updateScoreboard(LOSS);
         banner.setText("Sorry, you lose!");
         for (int i=1;i<=MAX_NUMBER;i++)
         {
            jbArray[i].removeActionListener(this); 
            if (i==secretNumber)
            {
               jbArray[i].setBackground(Color.black);
               jbArray[i].setForeground(Color.white);
            }
            else
            {
               jbArray[i].setForeground(Color.red);
               jbArray[i].setBackground(Color.red);
            }
         } 
      
         waitingForReset=true;
         resetButton.addActionListener(this);
      }  
   	
       private void deactivateGameButton(int i)
      {	
         jbArray[i].setForeground(Color.red);		// hides text by making the text
         jbArray[i].setBackground(Color.red);		// color the same as the background
         jbArray[i].removeActionListener(this);
      }
   	
       private void activateAllGameButtons()
      {	int i;
         for (i=1;i<=MAX_NUMBER;i++) 
         {
            jbArray[i].setForeground(Color.black);
            jbArray[i].setBackground(Color.yellow);
            jbArray[i].addActionListener(this);
         }
      }
   	
       private void tryMessage(int i)
      {  
         if (i==1)banner.setText("You have 1 try to guess the hidden number");
         else
            banner.setText("You have "+i+" tries to guess the hidden number");
      }
   	
       private void updateScoreboard(boolean b)
      {
         if (b==WIN) ++wins;
         if (b==LOSS) ++losses;
         score.setText("  Wins: "+wins+"  Losses: "+losses);
      }
   	
       public static void main(String[] args) {
         GuessingGame window = new GuessingGame();
         window.setTitle("Number Guessing Game");
         window.pack();
         window.setVisible(true);
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }
   }


Home | Topics | Book Reviews | Contact Us

Please send comments about this site or its contents to the webmaster.
© 2001-2003 Steve Bunning. All rights reserved.