Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
1
Tutorial 15 – Craps Game Application
Introducing Random Number Generation and the
JPanel
Outline
15.1
15.2
15.3
15.4
15.5
Test-Driving the Craps Game Application
Random Number Generation
Using Constants in the Craps Game Application
Using Random Numbers in the Craps Game Application
Wrap-Up
© Copyright 1992-2004 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 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
3
15.1
Test-Driving the Craps Game Application
Application Requirements
Create an application that simulates playing the world-famous dice game
“Craps.” In this game, a player rolls two dice. Each die has six faces. Each
face contains 1, 2, 3, 4, 5 or 6 spots. After the dice have come to rest, the sum
of the spots on the two top faces is calculated. If the sum is 7 or 11 on the first
roll, the player wins. If the sum is 2, 3 or 12 on the first roll (called “craps”),
the player loses (the “house” wins). If the sum is 4, 5, 6, 8, 9 or 10 on the first
roll, that sum becomes the player’s “point.” To win, a player must continue
rolling the dice until the player rolls the point value. The player loses by
rolling a 7 before rolling the point.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
4
15.1
Test-Driving the Craps Game Application
(Cont.)
Figure 15.1
Initial appearance of Craps Game application.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
5
15.1
Test-Driving the Craps Game Application
(Cont.)
Figure 15.2
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Player winning on first roll by rolling 7.
6
15.1
Test-Driving the Craps Game Application
(Cont.)
Figure 15.3
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Player losing on first roll by rolling 3.
7
15.1
Figure 15.4
Test-Driving the Craps Game Application
(Cont.)
Player’s first roll setting the point that the player must match to win.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
8
15.1
Figure 15.5
Test-Driving the Craps Game Application
(Cont.)
Player winning the game by matching the point before rolling a 7.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
9
15.1
Test-Driving the Craps Game Application
(Cont.)
Figure 15.6
Player losing by rolling a 7 before matching the point.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
10
15.2
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 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
11
15.2
Random Number Generation (Cont.)
Expression
Resulting range
randomGenerator.nextInt()
(-232) to (232 - 1) [all possible values of int]
randomGenerator.nextInt( 30 )
0
10 + randomGenerator.nextInt( 10 )
10
randomGenerator.nextDouble()
8 * randomGenerator.nextDouble()
to 29
to 19
0.0 to less than 1.0
0.0 to less than 8.0
Figure 15.7 The nextInt and nextDouble methods produce
expressions with random ranges.
• Method nextDouble
– Generates a random double
– Returns a positive double value between 0.0 and 1.0 (not
including 1.0)
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
12
15.3
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 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
13
15.3
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 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
14
15.3
Using Constants in the Craps Game
Application (Cont.)
Action
Component
Label the application’s components
resultJLabel
Roll the two dice
randomObject
Display images of the rolled dice
die1JLabel,
die2JLabel
resultJTextField
Case where the sum is 7 or 11
Display the winning message
Case where the sum is 2, 3 or 12
Display the losing message
Case where none of the preceding
cases are true
Display the value of the point
Disable the Play JButton and
enable the Roll JButton
Roll the two dice
Display images of the rolled dice
User clicks the Play
JButton
resultJTextField
pointDie1JLabel,
pointDie2JLabel
playJButton,
rollJButton
rollJButton
die1JLabel,
die2JLabel
resultJTextField
If the player rolls the point
Display the winning message
playJButton,
Enable the Play JButton and
rollJButton
disable the Roll JButton
resultJTextField
If the player rolls a 7
Display the losing message
playJButton,
Enable the Play JButton and
rollJButton
disable the Roll JButton
Figure 15.8 ACE table for the Craps Game application.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Event
User clicks the Roll
JButton
15
15.3
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 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
16
15.3
Using Constants in the Craps Game
Application (Cont.)
Figure 15.10
Declaring constants in the Craps Game application.
Declaring constants
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
17
15.3
Using Constants in the Craps Game
Application (Cont.)
Figure 15.11
Declaring constants in the Craps Game application.
Declaring constants
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
18
15.3
Using Constants in the Craps Game
Application (Cont.)
Figure 15.12
Adding instance variables to the Craps Game application.
Declaring variable
for point value
Using new to create
a Random object
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
19
15.3
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 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
20
15.3
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 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
21
15.3
Using Constants in the Craps Game
Application (Cont.)
Figure 15.13
Customizing
the JPanel
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Customizing pointDiceJPanel.
22
15.3
Using Constants in the Craps Game
Application (Cont.)
Figure 15.14
Adding a JLabel
to the JPanel
Adding a JLabel
to the JPanel
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Adding components to the JPanel.
23
15.3
Using Constants in the Craps Game
Application (Cont.)
Figure 15.15
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 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
24
15.3
Using Constants in the Craps Game
Application (Cont.)
Figure 15.16
Running Craps Game application.
TitledBorder is displayed
with Point as the title
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
25
15.4
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 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
26
15.4
Using Random Numbers in the Craps
Game Application (Cont.)
Figure 15.17
Removing images
from JLabels
Setting the title of the border
and updating the JPanel
“Rolling” the dice
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Clearing images and rolling the dice.
27
15.4
Using Random Numbers in the Craps
Game Application (Cont.)
Figure 15.18
switch statement in playJButtonActionPerformed.
Winning on
the first roll
Losing on
the first roll
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
28
15.4
Using Random Numbers in the Craps
Game Application (Cont.)
Figure 15.19
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 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
29
15.4
Using Random Numbers in the Craps
Game Application (Cont.)
Figure 15.20 Rolling the dice in rollJButtonActionPerformed.
“Rolling” the dice
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
30
15.4
Using Random Numbers in the Craps
Game Application (Cont.)
Figure 15.21
Displaying
winning message
Displaying losing
message
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Determining the outcome of a roll.
31
15.4
Using Random Numbers in the Craps
Game Application (Cont.)
Figure 15.22
Getting two
random numbers
Displaying the
die images
Returning the
sum of the dice
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
Declaring the rollDice method.
32
15.4
Using Random Numbers in the Craps
Game Application (Cont.)
Figure 15.23
Declaring the displayDie method.
Creating a new
ImageIcon
Displaying a
die image
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
33
15.4
Using Random Numbers in the Craps
Game Application (Cont.)
Figure 15.24
Running the completed Craps Game application.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson
Education Inc. All Rights Reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Tutorial 15: CrapsGame.java
// This application plays a simple craps game
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.*;
34
Outline
CrapsGame.java
(1 of 12)
Importing the class
public class CrapsGame extends JFrame
{
// JPanel and TitledBorder to contain dice
private JPanel pointDiceJPanel;
private TitledBorder pointDiceTitledBorder;
java.util.Random
// JLabels to display the die images in pointDiceJPanel
private JLabel pointDie1JLabel;
private JLabel pointDie2JLabel;
// JLabels to display the die images from the rolls of the dice
private JLabel die1JLabel;
private JLabel die2JLabel;
// JButtons to allow user to interact with game
private JButton playJButton;
private JButton rollJButton;
2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
35
// JLabel and JTextField show results of game
private JLabel resultJLabel;
private JTextField resultJTextField;
// constants representing winning dice rolls
private final int LUCKY_SEVEN = 7;
private final int YO_LEVEN = 11;
// constants representing losing dice rolls
private final int SNAKE_EYES = 2;
private final int TREY = 3;
private final int BOX_CARS = 12;
private final int CRAPS = 7;
// file name and directory constants
private final String FILE_PREFIX = "Images/die";
private final String FILE_SUFFIX = ".png";
// instance variables
private int myPoint = 0;
private Random randomObject = new Random();
Outline
CrapsGame.java
(2 of 12)
Declaring constants
for dice rolls
Declaring the constants
for the file name
Declaring instance
variable myPoint
Creating a Random
object using the
new keyword
2003 Prentice Hall, Inc.
All rights reserved.
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// no-argument constructor
public CrapsGame()
{
createUserInterface();
}
36
Outline
CrapsGame.java
(3 of 12)
// create and position GUI components; register event handlers
private void createUserInterface()
{
// get content pane for attaching GUI components
Container contentPane = getContentPane();
// enable explicit positioning of GUI components
contentPane.setLayout( null );
// set up pointDiceTitledBorder for use with pointDiceJPanel
pointDiceTitledBorder = new TitledBorder( "Point" );
// set up pointDiceJPanel
pointDiceJPanel = new JPanel();
pointDiceJPanel.setBounds( 16, 16, 200, 116 );
pointDiceJPanel.setLayout( null );
pointDiceJPanel.setBorder( pointDiceTitledBorder );
contentPane.add( pointDiceJPanel );
Creating a
TitledBorder
object
Adding a border to
the JPanel
2003 Prentice Hall, Inc.
All rights reserved.
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// set up pointDie1JLabel
pointDie1JLabel = new JLabel();
pointDie1JLabel.setBounds( 24, 34, 64, 56 );
pointDiceJPanel.add( pointDie1JLabel );
// set up pointDie2JLabel
pointDie2JLabel = new JLabel();
pointDie2JLabel.setBounds( 120, 34, 64, 56 );
pointDiceJPanel.add( pointDie2JLabel );
// set up die1JLabel
die1JLabel = new JLabel();
die1JLabel.setBounds( 40, 150, 64, 64 );
contentPane.add( die1JLabel );
// set up die2JLabel
die2JLabel = new JLabel();
die2JLabel.setBounds( 136, 150, 64, 56 );
contentPane.add( die2JLabel );
37
Outline
CrapsGame.java
(4 of 12)
Adding a JLabel
to a JPanel using
the add method
Adding a JLabel
to a JPanel using
the add method
2003 Prentice Hall, Inc.
All rights reserved.
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// set up playJButton
playJButton = new JButton();
playJButton.setBounds( 232, 16, 88, 23 );
playJButton.setText( "Play" );
contentPane.add( playJButton );
playJButton.addActionListener(
38
Outline
CrapsGame.java
(5 of 12)
new ActionListener() // anonymous inner class
{
// event handler called when playJButton is pressed
public void actionPerformed ( ActionEvent event )
{
playJButtonActionPerformed( event );
}
} // end anonymous inner class
); // end call to addActionListener
// set up rollJButton
rollJButton = new JButton();
rollJButton.setBounds( 232, 56, 88, 23 );
rollJButton.setText( "Roll" );
rollJButton.setEnabled( false );
contentPane.add( rollJButton );
2003 Prentice Hall, Inc.
All rights reserved.
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
rollJButton.addActionListener(
new ActionListener() // anonymous inner class
{
// event handler called when rollJButton is pressed
public void actionPerformed ( ActionEvent event )
{
rollJButtonActionPerformed( event );
}
39
Outline
CrapsGame.java
(6 of 12)
} // end anonymous inner class
); // end call to addActionListener
// set up resultJLabel
resultJLabel = new JLabel();
resultJLabel.setBounds( 232, 90, 48, 16 );
resultJLabel.setText( "Result:" );
contentPane.add( resultJLabel );
2003 Prentice Hall, Inc.
All rights reserved.
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// set up resultJTextField
resultJTextField = new JTextField();
resultJTextField.setBounds( 232, 106, 88, 24 );
resultJTextField.setHorizontalAlignment( JTextField.CENTER );
resultJTextField.setEditable( false );
contentPane.add( resultJTextField );
40
Outline
CrapsGame.java
(7 of 12)
// set properties of application’s window
setTitle( "Craps Game" ); // set title bar string
setSize( 350, 250 );
// set window size
setVisible( true );
// display window
} // end method createUserInterface
// start new game of craps
private void playJButtonActionPerformed( ActionEvent event )
{
// clear point icons
pointDie1JLabel.setIcon( null );
pointDie2JLabel.setIcon( null );
// reset title of border
pointDiceTitledBorder.setTitle( "Point" );
pointDiceJPanel.repaint();
Removing images
from JLabels
Setting the title of the
border and updating
the JPanel
2003 Prentice Hall, Inc.
All rights reserved.
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
int sumOfDice = rollDice(); // roll dice
// check results of the first dice roll
switch ( sumOfDice )
{
// win on first roll
case LUCKY_SEVEN:
case YO_LEVEN:
resultJTextField.setText( "You win!!!" );
break;
// lose on first roll
case SNAKE_EYES:
case TREY:
case BOX_CARS:
resultJTextField.setText( "Sorry, you lose." );
break;
41
Outline
CrapsGame.java
(8 of 12)
Winning on
the first roll
Losing on
the first roll
// remember point in instance variable
default:
// set the point and output result
myPoint = sumOfDice;
resultJTextField.setText( "Roll again!" );
Player must
match the point
2003 Prentice Hall, Inc.
All rights reserved.
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// show the dice images
pointDie1JLabel.setIcon( die1JLabel.getIcon() );
pointDie2JLabel.setIcon( die2JLabel.getIcon() );
// update the border title
pointDiceTitledBorder.setTitle(
"Point is " + sumOfDice );
pointDiceJPanel.repaint();
// change the state of the JButtons
playJButton.setEnabled( false );
rollJButton.setEnabled( true );
} // end switch statement
42
Outline
CrapsGame.java
(9 of 12)
Displaying die images
Displaying point and
updating the JPanel
Allowing the player
to roll again
} // end method playJButtonActionPerformed
// continue the game
private void rollJButtonActionPerformed( ActionEvent event )
{
int sumOfDice = rollDice(); // roll dice
2003 Prentice Hall, Inc.
All rights reserved.
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// determine outcome of roll, player matches point
if ( sumOfDice == myPoint )
{
resultJTextField.setText( "You win!!!" );
rollJButton.setEnabled( false );
playJButton.setEnabled( true );
}
// determine outcome of roll, player loses
else if ( sumOfDice == CRAPS )
{
resultJTextField.setText( "Sorry, you lose" );
rollJButton.setEnabled( false );
playJButton.setEnabled( true );
}
43
Outline
CrapsGame.java
(10 of 12)
} // end method rollJButtonActionPerformed
// generate random die rolls
private int rollDice()
{
// generate random die values
int die1 = 1 + randomObject.nextInt( 6 );
int die2 = 1 + randomObject.nextInt( 6 );
Generating
random numbers
2003 Prentice Hall, Inc.
All rights reserved.
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// display the dice images
displayDie( die1JLabel, die1 );
displayDie( die2JLabel, die2 );
return die1 + die2; // return sum of dice values
44
Outline
CrapsGame.java
(11 of 12)
} // end method rollDice
// displays the die image
private void displayDie( JLabel picDieJLabel, int face )
{
ImageIcon image =
new ImageIcon( FILE_PREFIX + face + FILE_SUFFIX );
// display die images in picDieJLabel
picDieJLabel.setIcon( image );
Displaying the image
in the JLabel
} // end method displayDie
2003 Prentice Hall, Inc.
All rights reserved.
254
// main method
255
public static void main( String args[] )
256
{
257
CrapsGame application = new CrapsGame();
258
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
259
260
} // end method main
261
262 } // end class CrapsGame
45
Outline
CrapsGame.java
(12 of 12)
2003 Prentice Hall, Inc.
All rights reserved.