Section 7.16. Case Study: A Game of Chance


7.16. Case Study: A Game of Chance

One of the most popular games of chance is a dice game known as "craps." The rules of the game are straightforward:

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 upward faces is calculated. If the sum is 7 or 11 on the first throw, the player wins. If the sum is 2, 3 or 12 on the first throw (called "craps"), the player loses (i.e., the "house" wins). If the sum is 4, 5, 6, 8, 9 or 10 on the first throw, that sum becomes the player's "point." To win, players must continue rolling the dice until they "make their point" (i.e., roll their point value). The player loses by rolling a 7 before making the point.

The application in Fig. 7.17 simulates the game of craps.

Figure 7.17. Craps game using class Random.

  1  ' Fig. 7.17: CrapsGame.vb  2  ' Playing a craps game.  3  Imports System.IO  4  5  Public Class FrmCrapsGame  6     ' die-roll constants  7     Enum DiceNames        8        SNAKE_EYES = 2     9        TREY = 3          10        LUCKY_SEVEN = 7   11        CRAPS = 7         12        YO_LEVEN = 11     13        BOX_CARS = 12     14     End Enum             15 16     ' file-name and directory constants         17     Const FILE_PREFIX As String = "/images/die" 18     Const FILE_SUFFIX As String = ".png"        19 20     Dim myPoint As Integer ' total point 21     Dim myDie1 As Integer ' die1 face 22     Dim myDie2 As Integer ' die2 face 23     Dim randomObject As New Random() ' generate random number 24 25     ' begins new game and determines point 26     Private Sub btnPlay_Click(ByVal sender As System.Object, _ 27        ByVal e As System.EventArgs) Handles btnPlay.Click 28 29        ' initialize variables for new game 30        myPoint = 0 31        grpPoint.Text = "Point" 32        lblStatus.Text = "" 33 34        ' remove point-die images 35        picPointDie1.Image = Nothing 36        picPointDie2.Image = Nothing 37 38        Dim sum As Integer = RollDice()  ' roll dice and calculate sum 39 40        ' check die roll 41        Select Case sum 42           Case DiceNames.LUCKY_SEVEN, DiceNames.YO_LEVEN 43              btnRoll.Enabled = False ' disable Roll button 44              lblStatus.Text = "You Win!!!" 45           Case DiceNames.SNAKE_EYES, DiceNames.TREY, DiceNames.BOX_CARS 46              btnRoll.Enabled = False ' disable Roll button 47              lblStatus.Text = "Sorry. You Lose." 48           Case Else 49              myPoint = sum 50              grpPoint.Text = "Point is " & sum 51              lblStatus.Text = "Roll Again!" 52              DisplayDie(picPointDie1, myDie1) 53              DisplayDie(picPointDie2, myDie2) 54              btnPlay.Enabled = False ' disable Play button 55              btnRoll.Enabled = True ' enable Roll button 56        End Select 57     End Sub ' btnPlay_Click 58 59     ' determines outcome of next roll 60     Private Sub btnRoll_Click(ByVal sender As System.Object, _ 61        ByVal e As System.EventArgs) Handles btnRoll.Click 62 63        Dim sum As Integer = RollDice()  ' roll dice and calculate sum 64 65        ' check outcome of roll 66        If sum = myPoint Then ' win 67           lblStatus.Text = "You Win!!!" 68           btnRoll.Enabled = False ' disable Roll button 69           btnPlay.Enabled = True ' enable Play button 70        ElseIf sum = DiceNames.CRAPS Then ' lose 71           lblStatus.Text = "Sorry. You Lose." 72           btnRoll.Enabled = False ' disable Roll button 73           btnPlay.Enabled = True ' enable Play button 74        End If 75     End Sub ' btnRoll_Click 76 77     ' display die image 78     Sub DisplayDie(ByVal picDie As PictureBox, _ 79        ByVal face As Integer) 80        ' assign die image to picture box                       81        picDie.Image = Image.FromFile(Directory.GetCurrentDirectory & _ 82           FILE_PREFIX & face & FILE_SUFFIX)                   83     End Sub ' DisplayDie 84 85     ' generate random die rolls 86     Function RollDice() As Integer 87        ' determine random integer 88        myDie1 = randomObject.Next(1, 7) 89        myDie2 = randomObject.Next(1, 7) 90 91        ' display rolls 92        DisplayDie(picDie1, myDie1) 93        DisplayDie(picDie2, myDie2) 94 95        Return myDie1 + myDie2 ' return sum 96     End Function ' RollDice 97  End Class  ' FrmCrapsGame 

(a)

(b)

(c)

(d)

The player must roll two dice on the first and all subsequent rolls. When executing the application, click the Play Button to play the game. The form displays the results of each roll. The screen captures depict the execution of two games. Fig. 7.17(a) displays the Form before the game has begun, while Fig. 7.17(b) shows the application after the Play Button has been clicked. In this example, a 6 is rolled, which is made the point. We click Roll again and a 7 is rolled, causing us to lose the game (Fig. 7.17(c)). Fig. 7.17(d) shows another example game, where the user wins by rolling a 7 on the first roll.

This program introduces the GroupBox control, used to display the user's point. A GroupBox is a container used to group related controls. Within the GroupBox pointDiceGroup, we add two PictureBoxes, which are controls that display images. A GroupBox can be dragged and dropped onto the Form the same way you would any other control. When adding other controls to a GroupBox (such as the two PictureBoxes in this example), drag and drop the controls within the bounds of the GroupBox on the Form. The GroupBox is named grpPoint. We use the prefix grp for GroupBoxes. We set the font size of the GroupBox to 9.75 and the Text property of the GroupBox to Point. This is the text that displays in the upper-left corner of the GroupBox. Note in the output of Fig. 7.17 that we will be modifying this text to display the user's point value. If you leave the Text property blank, the GroupBox will display as a simple border without any text.

Enumerations and Constants

Before introducing any method declarations, the program includes several declarations, including our first enumeration in lines 714 and our first constant identifiers in lines 1718. Constant identifiers and Enumerations enhance program readability by providing descriptive identifiers for constant numbers or Strings. Constant identifiers and Enumerations help you ensure that values are consistent throughout a program. Recall that keyword Const creates a single constant identifier; Enumerations are used to define groups of related constants. In this case, we create Constant identifiers for the file names that are used throughout the program and create an Enumeration of descriptive names for the various dice combinations in craps (i.e., SNAKE_EYES, trEY, LUCKY_SEVEN, CRAPS, YO_LEVEN and BOX_CARS). Note that multiple enumeration members can have the same valuein this example, LUCKY_SEVEN and CRAPS both have the value 7. We use two identifiers for program clarity; on the first roll, a seven causes the player to win (LUCKY_SEVEN), and on subsequent rolls, a seven causes the player to lose (CRAPS). Constant identifiers must be assigned constant values and cannot be modified after they are declared.

After the constant-identifier declarations and the declarations for several instance variables (lines 2023), method btnPlay_Click is declared (lines 2657). It is the event handler for btnPlay's Click event. When the user clicks the Play button, method btnPlay_Click sets up a new game by initializing several values (lines 3032). Note that line 32 sets our status Label's Text property to "". This is known as the empty string (i.e., a string that does not contain any characters). Nothing appears on the screen when an empty string is displayed. Setting the Image property of picPointDie1 and picPointDie2 to Nothing (lines 3536) causes the PictureBoxes to appear blank. Method btnPlay_Click executes the game's opening roll by calling RollDice (line 38). Internally, RollDice (lines 8696) generates two random numbers and calls method DisplayDie (lines 7883), which loads an appropriate die image in the PictureBox passed to it.

The Select...Case statement (lines 4156) analyzes the roll returned by RollDice to determine how play should continue (i.e., by terminating the game with a win or loss, or by enabling subsequent rolls). If the user does not win or lose on the first roll, the GroupBox's text is set to display the point value (line 50) and the property images are displayed in the GroupBox's PictureBoxes (lines 5253). Depending on the value of the roll, Buttons Roll and Play become either enabled or disabled (lines 43, 46 and 5455). Disabling a Button means that no action will be performed when the Button is clicked. Buttons can be enabled and disabled by setting the Button's Enabled property to true or False, respectively.

If button Roll is enabled, clicking it invokes method btnRoll_Click (lines 6075), which executes an additional roll of the dice. Method btnRoll_Click then analyzes the roll, letting users know whether they have won or lost.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net