Using the Random class to create a simple guessing game

Random number generation is mostly the important factor behind writing many games. Java has a rich toolkit for generating random numbers, in a class java.util.Random. Each instance of this class is a random number generator object generating a stream of pseudorandom numbers.

A Random object can be created by providing a seed, which is used to generate the random numbers. Two Random objects created using a same seed, will produce exactly same results, if same methods are called in same sequence. This can be done using the Random(long seed) constructor. Random object created without the seed using the Random() constructor most likely generates different sequences than any previous invocations.

Once the Random object is created, different types of random numbers can be generated by using the set of methods provided. For example, to generate a random integer, nextInt() method can be used. To generate a random integer between 0 and some upper bound, nextInt(int n) method can be used. Similar methods are provided to generate numbers of different types, like float, long, double and boolean.

This example shows how to use Random object to create a simple Guessing Game, where user is shown 3 doors and has to guess in which door a cub is hiding. The trick is to generate a random integer between 0 to 2, by calling method nextInt(3) . If the random integer generated is 0 means the cub is in Door1, 1 means Door2, and 2 means Door3. This is then compared with the user selection, if user selection is same as the random integer, the guess is correct.

Code

The following applet creates 3 JButtons to indicate the three doors. The icons on these buttons are changed appropriately to display the results.

/*  
* This example is from javareference.com  
* for more information visit,  
* http://www.javareference.com  
*/  

//package 

//import statements 
import java.awt.*;  
import java.awt.event.*; 
import javax.swing.*;  
import java.util.Random; 

/** 
 * This class creates a Guess Game, using Random class 
 * @author Rahul Sapkal(rahul@javareference.com) 
 */ 
public class GuessGame extends JApplet 
       implements ActionListener 
{  
    private JButton m_play; 
    private JButton m_door1; 
    private JButton m_door2; 
    private JButton m_door3; 
     
    private JLabel m_result; 
    private JLabel m_message; 
     
    private ImageIcon m_door, m_cubInTheHouse; 
     
    private Random m_randomGenerator; 
    private int m_randomNumber; 
    private Cursor m_handCursor; 
      
    public void init()  
    {  
        getContentPane().setLayout(new BorderLayout(5, 5)); 
         
        //Get all the images needed 
        getAllImages(); 
                 
        m_play = new JButton("Play"); 
        m_play.addActionListener(this); 
         
        m_handCursor = new Cursor(Cursor.HAND_CURSOR); 
                 
        m_door1 = new JButton(m_cubInTheHouse); 
        m_door1.setBackground(Color.black); 
        m_door1.setBorderPainted(false); 
        m_door1.setFocusable(false); 
        m_door1.setMargin(new Insets(0, 0, 0, 0)); 
        m_door1.addActionListener(this); 
                                 
        m_door2 = new JButton(m_cubInTheHouse); 
        m_door2.setBackground(Color.black); 
        m_door2.setBorderPainted(false); 
        m_door2.setFocusable(false); 
        m_door2.setMargin(new Insets(0, 0, 0, 0)); 
        m_door2.addActionListener(this); 
                 
        m_door3 = new JButton(m_cubInTheHouse); 
        m_door3.setBackground(Color.black); 
        m_door3.setBorderPainted(false); 
        m_door3.setFocusable(false); 
        m_door3.setMargin(new Insets(0, 0, 0, 0)); 
        m_door3.addActionListener(this); 
         
        //message label 
        m_message = new JLabel("Click Play to start the game"); 
         
        //play panel 
        JPanel playPanel = new JPanel(new FlowLayout()); 
        playPanel.add(m_play); 
        playPanel.add(m_message); 
         
        //button panel 
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 50, 50)); 
        buttonPanel.setBackground(Color.black); 
        buttonPanel.add(m_door1);             
        buttonPanel.add(m_door2); 
        buttonPanel.add(m_door3); 

        m_result = new JLabel("All the Best !!!", JLabel.CENTER); 
        m_result.setFont(new Font("Arial", Font.BOLD, 16)); 
                 
        getContentPane().add(BorderLayout.NORTH, playPanel); 
        getContentPane().add(BorderLayout.CENTER, buttonPanel); 
        getContentPane().add(BorderLayout.SOUTH, m_result); 
         
        //create the Random object 
        m_randomGenerator = new Random(); 
    }  
     
    private void changeToHandCursor(boolean handCur) 
    { 
        if(handCur) 
        { 
            m_door1.setCursor(m_handCursor); 
            m_door2.setCursor(m_handCursor); 
            m_door3.setCursor(m_handCursor);                 
        } 
        else 
        { 
            m_door1.setCursor(Cursor.getDefaultCursor()); 
            m_door2.setCursor(Cursor.getDefaultCursor()); 
            m_door3.setCursor(Cursor.getDefaultCursor()); 
        } 
    } 
     
    private void getAllImages() 
    { 
        MediaTracker mt = new MediaTracker(this); 
        Image door = getImage(getCodeBase(), "door.gif"); 
        mt.addImage(door, 1); 
        Image cubInTheHouse = getImage(getCodeBase(), "cubinthehouse.gif"); 
        mt.addImage(cubInTheHouse, 2); 
         
        try  
        {  
            mt.waitForAll(); 
             
            m_door = new ImageIcon(door);  
            m_cubInTheHouse = new ImageIcon(cubInTheHouse); 
        }  
        catch (InterruptedException e)  
        {  
            e.printStackTrace();  
        } 
    } 
     
    private void arrangeToPlay() 
    { 
        m_result.setText("All the Best !!!"); 
         
        m_message.setText("Click any one Door below to Guess where the cub is hiding..."); 
         
        m_door1.setIcon(m_door); 
        m_door2.setIcon(m_door); 
        m_door3.setIcon(m_door); 
         
        changeToHandCursor(true); 
         
        //Generator the next random number, between, 0 to 2 
        m_randomNumber = m_randomGenerator.nextInt(3); 
    } 
     
    private void arrangeForResult(int selection) 
    { 
        //change to default cursor 
        changeToHandCursor(false); 
         
        //set the cub icon on the random number door 
        switch(m_randomNumber) 
        { 
            case 0 : m_door1.setIcon(m_cubInTheHouse); 
                     break; 
            case 1 : m_door2.setIcon(m_cubInTheHouse); 
                     break; 
            case 2 : m_door3.setIcon(m_cubInTheHouse); 
                     break; 
        } 
         
        //set message 
        m_message.setText("Click Play to start the game"); 
         
        //if the random number and the selection is same 
        //the guess is correct 
        if (m_randomNumber == selection) 
        { 
            m_result.setText("Bingo! Good Guess !!!");  
        } 
        else 
        { 
            m_result.setText("Ooops, Try Again !!!"); 
        } 
    } 

    public void actionPerformed(ActionEvent ae) 
    { 
        if(ae.getSource().equals(m_play)) 
        { 
            arrangeToPlay(); 
        } 
        else if(ae.getSource().equals(m_door1)) 
        { 
            //0 means door 1 
            arrangeForResult(0); 
        } 
        else if(ae.getSource().equals(m_door2)) 
        { 
            //1 means door 2 
            arrangeForResult(1); 
        } 
        else if(ae.getSource().equals(m_door3)) 
        { 
            //2 means door 3 
            arrangeForResult(2); 
        }             
    } 
} 

The game in action

Leave a Reply