© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 15.1 Test-Driving the Craps Game Application 15.2 Random Number Generation 15.3 Using Constants in the Craps Game Application 15.4 Using Random Numbers in the Craps Game Application 15.5 Wrap-Up Tutorial 15 – Craps Game Application Introducing Random Number Generation and the JPanel
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Objective In this tutorial, you will learn to: –Use simulation techniques that employ random number generation. –Use methods of class Random. –Generate random numbers. –Use constants to enhance code readability. –Use a JPanel and a TitledBorder to add a border around components.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Craps Game Application
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Craps Game Application (Cont.) Figure 15.1 Initial appearance of Craps Game application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Craps Game Application (Cont.) Figure 15.2 Player winning on first roll by rolling 7.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Craps Game Application (Cont.) Figure 15.3 Player losing on first roll by rolling 3.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Craps Game Application (Cont.) Figure 15.4 Player’s first roll setting the point that the player must match to win.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Craps Game Application (Cont.) Figure 15.5 Player winning the game by matching the point before rolling a 7.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Craps Game Application (Cont.) Figure 15.6 Player losing by rolling a 7 before matching the point.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Random Number Generation Class Random Random randomGenerator = new Random(); int randomNumber = randomGenerator.nextInt(); Reference variable –Refers to an object –Contains the location in the computer’s memory of an object Keyword new –Creates an object and assigns it a location in memory Method nextInt –Generates a random int from all possible int values (positive and negative)
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Random Number Generation (Cont.) Method nextDouble –Generates a random double –Returns a positive double value between 0.0 and 1.0 (not including 1.0 )
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application When the player clicks the Play JButton Roll the two dice using random numbers Calculate the sum of the two dice Display images of the rolled dice Switch based on the sum of the two dice: Case where the sum of the two dice is 7 or 11 Display the winning message Case where the sum of the two dice is 2, 3 or 12 Display the losing message Case where none of the preceding cases are true Set the value of the point to the sum of the dice and display the value Disable the Play JButton and enable the Roll JButton
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.) When the player clicks the Roll JButton Roll the two dice using random numbers Calculate the sum of the two dice Display images of the rolled dice If the player rolls the same value as the point Display the winning message Clear the value of the point Enable the Play JButton and disable the Roll JButton If the player rolls a 7 Display the losing message Clear the value of the point Enable the Play JButton and disable the Roll JButton
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.)
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.) Figure 15.9 Importing class Random of the java.util package. Importing the java.util.Random class Packages –Predefined classes are grouped into categories of related classes –Package java.util Provides random number processing capabilities with class Random Keyword import –Imports a class –Allows your application to access that class
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.) Figure Declaring constants in the Craps Game application. Declaring constants
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.) Figure Declaring constants in the Craps Game application. Declaring constants
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.) Figure Adding instance variables to the Craps Game application. Declaring variable for point value Using new to create a Random object
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.) Component JPanel –Container that allows grouping of related components –The content pane covered in Tutorial 2 is a JPanel
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.) layout property –Controls how components are arranged on a JPanel –Setting the value to null allows absolute positioning Component locations are specified exactly by coordinates –Other layouts involve relative positioning Components are placed in relation to other components on a container
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.) Figure Customizing pointDiceJPanel. Customizing the JPanel
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.) Figure Adding components to the JPanel. Adding a JLabel to the JPanel
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.) Figure Setting the border of pointDiceJPanel. Creating a TitledBorder Setting the border property border property –TitledBorder places a line and a title around a GUI component. –Any GUI component attached to the component with the border will appear inside the border –Default borders
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Constants in the Craps Game Application (Cont.) Figure Running Craps Game application. TitledBorder is displayed with Point as the title
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Random Numbers in the Craps Game Application (Cont.) Keyword null –Clears a reference’s value The TitledBorder ’s title property –Controls the text that is displayed in the border The JPanel ’s repaint method –Redraws the JPanel
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Random Numbers in the Craps Game Application (Cont.) Figure Clearing images and rolling the dice. Removing images from JLabel s Setting the title of the border and updating the JPanel “Rolling” the dice
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Random Numbers in the Craps Game Application (Cont.) Figure switch statement in playJButtonActionPerformed. Winning on the first roll Losing on the first roll
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Random Numbers in the Craps Game Application (Cont.) Figure default case in playJButtonActionPerformed. Player must match the point Displaying the die images Displaying the point and updating the application Allowing the player to roll again
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Random Numbers in the Craps Game Application (Cont.) Figure Rolling the dice in rollJButtonActionPerformed. “Rolling” the dice
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Random Numbers in the Craps Game Application (Cont.) Figure Determining the outcome of a roll. Displaying winning message Displaying losing message
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Random Numbers in the Craps Game Application (Cont.) Figure Declaring the rollDice method. Getting two random numbers Displaying the die images Returning the sum of the dice
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Random Numbers in the Craps Game Application (Cont.) Figure Declaring the displayDie method. Displaying a die image Creating a new ImageIcon
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Using Random Numbers in the Craps Game Application (Cont.) Figure Running the completed Craps Game application.
2003 Prentice Hall, Inc. All rights reserved. Outline 34 CrapsGame.java (1 of 12) 1 // Tutorial 15: CrapsGame.java 2 // This application plays a simple craps game 3 import java.awt.*; 4 import java.awt.event.*; 5 import java.util.Random; 6 import javax.swing.*; 7 import javax.swing.border.*; 8 9 public class CrapsGame extends JFrame 10 { 11 // JPanel and TitledBorder to contain dice 12 private JPanel pointDiceJPanel; 13 private TitledBorder pointDiceTitledBorder; // JLabels to display the die images in pointDiceJPanel 16 private JLabel pointDie1JLabel; 17 private JLabel pointDie2JLabel; // JLabels to display the die images from the rolls of the dice 20 private JLabel die1JLabel; 21 private JLabel die2JLabel; // JButtons to allow user to interact with game 24 private JButton playJButton; 25 private JButton rollJButton; Importing the class java.util.Random
2003 Prentice Hall, Inc. All rights reserved. Outline 35 CrapsGame.java (2 of 12) // JLabel and JTextField show results of game 28 private JLabel resultJLabel; 29 private JTextField resultJTextField; // constants representing winning dice rolls 32 private final int LUCKY_SEVEN = 7; 33 private final int YO_LEVEN = 11; // constants representing losing dice rolls 36 private final int SNAKE_EYES = 2; 37 private final int TREY = 3; 38 private final int BOX_CARS = 12; 39 private final int CRAPS = 7; // file name and directory constants 42 private final String FILE_PREFIX = "Images/die"; 43 private final String FILE_SUFFIX = ".png"; // instance variables 46 private int myPoint = 0; 47 private Random randomObject = new Random(); 48 Declaring constants for dice rolls Declaring the constants for the file name Creating a Random object using the new keyword Declaring instance variable myPoint
2003 Prentice Hall, Inc. All rights reserved. Outline 36 CrapsGame.java (3 of 12) 49 // no-argument constructor 50 public CrapsGame() 51 { 52 createUserInterface(); 53 } // create and position GUI components; register event handlers 56 private void createUserInterface() 57 { 58 // get content pane for attaching GUI components 59 Container contentPane = getContentPane(); // enable explicit positioning of GUI components 62 contentPane.setLayout( null ); // set up pointDiceTitledBorder for use with pointDiceJPanel 65 pointDiceTitledBorder = new TitledBorder( "Point" ); // set up pointDiceJPanel 68 pointDiceJPanel = new JPanel(); 69 pointDiceJPanel.setBounds( 16, 16, 200, 116 ); 70 pointDiceJPanel.setLayout( null ); 71 pointDiceJPanel.setBorder( pointDiceTitledBorder ); 72 contentPane.add( pointDiceJPanel ); 73 Adding a border to the JPanel Creating a TitledBorder object
2003 Prentice Hall, Inc. All rights reserved. Outline 37 CrapsGame.java (4 of 12) 74 // set up pointDie1JLabel 75 pointDie1JLabel = new JLabel(); 76 pointDie1JLabel.setBounds( 24, 34, 64, 56 ); 77 pointDiceJPanel.add( pointDie1JLabel ); // set up pointDie2JLabel 80 pointDie2JLabel = new JLabel(); 81 pointDie2JLabel.setBounds( 120, 34, 64, 56 ); 82 pointDiceJPanel.add( pointDie2JLabel ); // set up die1JLabel 85 die1JLabel = new JLabel(); 86 die1JLabel.setBounds( 40, 150, 64, 64 ); 87 contentPane.add( die1JLabel ); // set up die2JLabel 90 die2JLabel = new JLabel(); 91 die2JLabel.setBounds( 136, 150, 64, 56 ); 92 contentPane.add( die2JLabel ); 93 Adding a JLabel to a JPanel using the add method
2003 Prentice Hall, Inc. All rights reserved. Outline 38 CrapsGame.java (5 of 12) 94 // set up playJButton 95 playJButton = new JButton(); 96 playJButton.setBounds( 232, 16, 88, 23 ); 97 playJButton.setText( "Play" ); 98 contentPane.add( playJButton ); 99 playJButton.addActionListener( new ActionListener() // anonymous inner class 102 { 103 // event handler called when playJButton is pressed 104 public void actionPerformed ( ActionEvent event ) 105 { 106 playJButtonActionPerformed( event ); 107 } } // end anonymous inner class ); // end call to addActionListener // set up rollJButton 114 rollJButton = new JButton(); 115 rollJButton.setBounds( 232, 56, 88, 23 ); 116 rollJButton.setText( "Roll" ); 117 rollJButton.setEnabled( false ); 118 contentPane.add( rollJButton );
2003 Prentice Hall, Inc. All rights reserved. Outline 39 CrapsGame.java (6 of 12) 119 rollJButton.addActionListener( new ActionListener() // anonymous inner class 122 { 123 // event handler called when rollJButton is pressed 124 public void actionPerformed ( ActionEvent event ) 125 { 126 rollJButtonActionPerformed( event ); 127 } } // end anonymous inner class ); // end call to addActionListener // set up resultJLabel 134 resultJLabel = new JLabel(); 135 resultJLabel.setBounds( 232, 90, 48, 16 ); 136 resultJLabel.setText( "Result:" ); 137 contentPane.add( resultJLabel ); 138
2003 Prentice Hall, Inc. All rights reserved. Outline 40 CrapsGame.java (7 of 12) 139 // set up resultJTextField 140 resultJTextField = new JTextField(); 141 resultJTextField.setBounds( 232, 106, 88, 24 ); 142 resultJTextField.setHorizontalAlignment( JTextField.CENTER ); 143 resultJTextField.setEditable( false ); 144 contentPane.add( resultJTextField ); // set properties of application’s window 147 setTitle( "Craps Game" ); // set title bar string 148 setSize( 350, 250 ); // set window size 149 setVisible( true ); // display window } // end method createUserInterface // start new game of craps 154 private void playJButtonActionPerformed( ActionEvent event ) 155 { 156 // clear point icons 157 pointDie1JLabel.setIcon( null ); 158 pointDie2JLabel.setIcon( null ); // reset title of border 161 pointDiceTitledBorder.setTitle( "Point" ); 162 pointDiceJPanel.repaint(); 163 Removing images from JLabel s Setting the title of the border and updating the JPanel
2003 Prentice Hall, Inc. All rights reserved. Outline 41 CrapsGame.java (8 of 12) 164 int sumOfDice = rollDice(); // roll dice // check results of the first dice roll 167 switch ( sumOfDice ) 168 { 169 // win on first roll 170 case LUCKY_SEVEN: 171 case YO_LEVEN: 172 resultJTextField.setText( "You win!!!" ); 173 break; // lose on first roll 176 case SNAKE_EYES: 177 case TREY: 178 case BOX_CARS: 179 resultJTextField.setText( "Sorry, you lose." ); 180 break; // remember point in instance variable 183 default: // set the point and output result 186 myPoint = sumOfDice; 187 resultJTextField.setText( "Roll again!" ); 188 Winning on the first roll Losing on the first roll Player must match the point
2003 Prentice Hall, Inc. All rights reserved. Outline 42 CrapsGame.java (9 of 12) 189 // show the dice images 190 pointDie1JLabel.setIcon( die1JLabel.getIcon() ); 191 pointDie2JLabel.setIcon( die2JLabel.getIcon() ); // update the border title 194 pointDiceTitledBorder.setTitle( 195 "Point is " + sumOfDice ); 196 pointDiceJPanel.repaint(); // change the state of the JButtons 199 playJButton.setEnabled( false ); 200 rollJButton.setEnabled( true ); } // end switch statement } // end method playJButtonActionPerformed // continue the game 207 private void rollJButtonActionPerformed( ActionEvent event ) 208 { 209 int sumOfDice = rollDice(); // roll dice 210 Displaying die images Displaying point and updating the JPanel Allowing the player to roll again
2003 Prentice Hall, Inc. All rights reserved. Outline 43 CrapsGame.java (10 of 12) 211 // determine outcome of roll, player matches point 212 if ( sumOfDice == myPoint ) 213 { 214 resultJTextField.setText( "You win!!!" ); 215 rollJButton.setEnabled( false ); 216 playJButton.setEnabled( true ); 217 } 218 // determine outcome of roll, player loses 219 else if ( sumOfDice == CRAPS ) 220 { 221 resultJTextField.setText( "Sorry, you lose" ); 222 rollJButton.setEnabled( false ); 223 playJButton.setEnabled( true ); 224 } } // end method rollJButtonActionPerformed // generate random die rolls 229 private int rollDice() 230 { 231 // generate random die values 232 int die1 = 1 + randomObject.nextInt( 6 ); 233 int die2 = 1 + randomObject.nextInt( 6 ); 234 Generating random numbers
2003 Prentice Hall, Inc. All rights reserved. Outline 44 CrapsGame.java (11 of 12) 235 // display the dice images 236 displayDie( die1JLabel, die1 ); 237 displayDie( die2JLabel, die2 ); return die1 + die2; // return sum of dice values } // end method rollDice // displays the die image 244 private void displayDie( JLabel picDieJLabel, int face ) 245 { 246 ImageIcon image = 247 new ImageIcon( FILE_PREFIX + face + FILE_SUFFIX ); // display die images in picDieJLabel 250 picDieJLabel.setIcon( image ); } // end method displayDie 253 Displaying the image in the JLabel
2003 Prentice Hall, Inc. All rights reserved. Outline 45 CrapsGame.java (12 of 12) 254 // main method 255 public static void main( String args[] ) 256 { 257 CrapsGame application = new CrapsGame(); 258 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // end method main } // end class CrapsGame