430 likes | 651 Views
16. Craps Game Application Introducing Random-Number Generation and Enum. Outline. 16.1 Test-Driving the Craps Game Application 16.2 Random-Number Generation 16.3 Constructing the Craps Game Application 16.4 Using Random Numbers in the Craps Game Application.
E N D
16 • Craps GameApplication • Introducing Random-NumberGeneration and Enum
Outline • 16.1 Test-Driving the CrapsGame Application • 16.2 Random-Number Generation • 16.3 Constructing theCrapsGame Application • 16.4 Using Random Numbers in the CrapsGame Application
In this tutorial you will learn: Code simulation techniques that employrandom-number generation. Use class Random methods to generate random numbers. Use enumerations to enhance code readability. Read images from files. Objectives
16.1 Test-Driving the CrapsGame Application • Create an application that simulates playing the game of craps. In this game, a player rolls two dice. Each die has six faces. 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 throw, the player wins. If the sum is 2, 3 or 12 on the first throw (called “craps”), the player loses. If the sum is 4, 5, 6, 8, 9 or 10 on the first throw, that sum becomes the player’s “point.” To win, a player must continue rolling the dice until the point value is rolled. The player loses by rolling a 7 before rolling the point.
Test-Driving the CrapsGame Application • Run the completed application (Fig. 16.1). Figure 16.1|CrapsGame application’s initial appearance.
Test-Driving the CrapsGame Application (Cont.) • There are three possible outcomes for clicking the PlayButton. • The player wins by rolling 7 or 11 (Fig.16.2). Figure 16.2| Player wins on first roll by rolling 7 or 11.
Test-Driving the CrapsGame Application (Cont.) • The player loses by rolling 2, 3 or 12 (Fig. 16.3). Figure 16.3| Player loses on first roll by rolling 2, 3 or 12.
Test-Driving the CrapsGame Application (Cont.) • Otherwise, the roll becomes the player’s point (4, 5, 6, 8, 9 or 10), which is then displayed (Fig. 16.4). Figure 16.4| First roll sets the point that the player must match to win.
Test-Driving the CrapsGame Application • Click the RollButton repeatedly until either you win by matching your point value (Fig. 16.5) or you lose by rolling a 7 (Fig. 16.6). Figure 16.5| Winning the game by matching your point. Figure 16.6|Losing by rolling a 7 before matching your point.
16.2 Random-Number Generation • An object of class Random introduces chance into your applications. • Consider the following statements: Dim randomObject AsNew Random() Dim randomNumber AsInteger = randomObject.Next() • The first statement declares randomObject as a reference of type Random and assigns it a NewRandom object. • The second statement declares Integer variable randomNumber and assigns it the value returned by calling Random’s Next method on randomObject.
16.2 Random-Number Generation (Cont.) • The Next method generates a positive Integer value between zero and the largest possible Integer. • You can also use NextDouble method to generate random values of type Double. The NextDouble method returns a positive Double value from 0.0 up to, but not including, 1.0. • The values returned by Next are actually pseudorandomnumbers produced by acomplex mathematical calculation.
16.2 Random-Number Generation (Cont.) • The range of values produced by Next often is different from the range needed in a particular application. • An application that simulates coin tossing might require only 0 for heads and 1 for tails. • An application that simulates the rolling of a six-sided die would require random Integers from 1 to 6. • By passing an argument to the Next method you can produce integers in the range from 1 to 6. value = 1 + randomObject.Next(6)
16.2 Random-Number Generation (Cont.) • You may also pass two arguments to Next to produce a range of numbers. value = randomObject.Next(1, 7) ' from 1 up to, but not including, 7 • As with method Next, the range of values produced by method NextDouble is also usually different from the range needed in a particular application. • By multiplying the value returned from method NextDouble you can produce Double values in the range from 0.0 to 6.0 (not including 6.0) value = 6 * randomObject.NextDouble()
16.2 Random-Number Generation (Cont.) • Figure 16.7 shows examples of the ranges returnedby calls to methods Next and NextDouble. Figure 16.7|Next and NextDouble method calls with corresponding ranges.
16.3 Constructing the CrapsGame Application When the player clicks the Play Button: Roll the dice using random numbers Display images corresponding to the numbers on the rolled dice Calculate the sum of both dice Select correct case based on the sum of the two dice: Case where first roll is 7 or 11 Display the winning message Case where first roll is 2, 3 or 12 Display the losing message
16.3 Constructing the CrapsGame Application (Cont.) Case where none of the preceding Cases are true Set the value of the point to the sum of the dice Display point value Display message to roll again Display images for user’s point Disable the Play Button Enable the Roll Button When the player clicks the Roll Button: Roll the dice using random numbers Display images corresponding to the numbers on the rolled dice Calculate the sum of both dice
16.3 Constructing the CrapsGame Application (Cont.) If the player rolls the same value as the point Display the winning message Disable the Roll Button Enable the Play Button Else If the player rolls a 7 Display the losing message Disable the Roll Button Enable the Play Button
Action/Control/Event (ACE) Table forthe CrapsGame Application • Use an ACE table to convert pseudocode into Visual Basic (Fig. 16.8). Figure 16.8| ACE table for the CrapsGame application. (Part 1 of 3.)
Action/Control/Event (ACE) Table forthe CrapsGame Application (Cont.) Figure 16.8| ACE table for the CrapsGame application. (Part 2 of 3.)
Action/Control/Event (ACE) Table forthe CrapsGame Application (Cont.) Figure 16.8| ACE table for the CrapsGame application. (Part 3 of 3.)
16.3 Constructing the CrapsGame Application (Cont.) • With enumerations, you can create constant identifiers. • In this application, enumerations are used to describe significant dice combinations. • Enumerations: • describe their values • enhance program readability • ensure that numbers are consistent
Introducing Enumerations andDeclaring Instance Variables • Open the template application (Fig. 16.9). Figure 16.9|Template CrapsGameForm in Design view.
Introducing Enumerations andDeclaring Instance Variables (Cont.) • Enumerations begin with the keyword Enum(line 3), and end with the keywords EndEnum(line 10) (Fig. 16.10). Defining an enumeration Figure 16.10| Enumeration DiceNames in the CrapsGame application.
Good Programming Practice • Use enumerations to group related constants and enhance code readability.
Introducing Enumerations andDeclaring Instance Variables (Cont.) • You can refer to the numbers using the enumeration name and the member-access operator. • For instance, use DiceNames.SNAKE_EYES forthe number 2. • Note that you can assign the same value to multiple enumeration constants. • If no values are specified, the constants are automatically assigned consecutive values starting from 0.
Common Programming Error • You can specify an enumeration’s type after its name by using the keyword As followed by Byte, SByte, Short, UShort, Integer, UInteger, Long, or ULong. If no type is specified, enumeration constants are of type Integer by default. Attempting to create enumerations of other types results in compilation errors.
Introducing Enumerations andDeclaring Instance Variables (Cont.) • Add constants representing the file names (Fig. 16.11). Declaring constants Declaring a variableto store point value Creating a Random object Figure 16.11| Instance variables added to the CrapsGame application.
Introducing Enumerations andDeclaring Instance Variables (Cont.) • The game of craps requires that you store the user’s point, once established on the first roll,for the game’s duration. • Variable myPoint stores the value of the dice on thefirst roll. • You use randomObject to “roll” the dice and generate those values.
Coding the PlayButton’s Click Event Handler • Double click the PlayButton to generate the PlayButton’s Click event handler (Fig. 16.12). Initializing valuesfor a new game Removing images from PictureBoxes “Rolling” the dice Figure 16.12|playButton_Click event handler definition.
Coding the PlayButton’s ClickEvent Handler (Cont.) • Lines 30–31 remove any images from the PictureBoxes used to display the point die. • Though there are no images when the application is first run, if the user chooses to continue playing after completing a game, the images from the previous game must be cleared. • Setting the Image property to keyword Nothing indicates that there is no image to display.
Coding the PlayButton’s ClickEvent Handler (Cont.) • Add a SelectCase statement to respond to various die rolls (Fig. 16.13). Winning on the first roll Losing on the first roll Figure 16.13|SelectCase statement in playButton_Click.
Coding the PlayButton’s ClickEvent Handler (Cont.) • If the player did not roll a 2, 3, 7, 11 or 12 (Case Else), then the value of the dice becomes the point and the player must roll again (Fig. 16.14). Player must match the point Display die images Allow player to roll again Figure 16.14|CaseElse statement in playButton_Click.
Coding the RollButton’s Click Event Handler • Generate the RollButton’s Click event handler (Fig. 16.15). Rolling the dice Figure 16.15| Rolling the dice in rollButton_Click.
Coding the RollButton’s ClickEvent Handler (Cont.) • The If...Then statement (Fig.16.16) determines whether the current roll matches the point. • If so, the program displays a winning message. Display winning message Display losing message Figure 16.16| Determining the outcome of a roll.
Coding the RollButton’s ClickEvent Handler (Cont.) • The ElseIf statement determines whetherthe sum of the dice in the current roll is 7. • If so, the application displays a message that the userhas lost. • It then ends the game by disabling the RollButtonand enabling the PlayButton.
Using Random Numbers to Simulate Rolling Dice • This application will roll and display dice many times as it executes. • Therefore, it is a good idea to create procedures to roll the dice and to display a die (Fig.16.17). Getting two random numbers Displaying die images Returning sum of dice Figure 16.17|RollDice procedure definition.
Using Random Numbers to SimulateRolling Dice (Cont.) • Now define procedure DisplayDie to displaythe die images corresponding to the random numbers generated in procedure RollDice (Fig. 16.18). Displaying a die image Figure 16.18|DisplayDie procedure definition.
Using Random Numbers to SimulateRolling Dice (Cont.) • Image.FromFile returns an Image object containing the image located at the path you specify. • To specify the location, pass a String representing the path to the FromFile method. • If the value of face is 1, the expression would represent the string images\ die1.png • The application searches for the specified file in the directory in which its executable file (.exe) is located.
Outline • Figure 16.19 presents the source codefor the Craps Game application. (1 of 5 ) Defining an enumeration
Outline (2 of 5 ) Creating a Random object Removing the images from both point PictureBoxes
Outline (3 of 5 ) Using Enum constants Using Enum constants
Outline (4 of 5 )
Outline (5 of 5 ) Generating random numbers Using code to display an image