1 / 71

Chapter 6 - Procedures

Chapter 6 - Procedures.

cyrilp
Download Presentation

Chapter 6 - Procedures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 6 - Procedures Outline6.1 Introduction6.2   Modules, Classes and Procedures6.3   Sub Procedures6.4   Function Procedures6.5   Methods6.6   Argument Promotion6.7   Option Strict and Data Type Conversions6.8   Value Types and Reference Types6.9   Passing Arguments: Pass-by-Value vs. Pass-by-Reference6.10   Duration of Identifiers6.11   Scope Rules6.12   Random-Number Generation6.13   Example: Game of Chance6.14   Recursion6.15   Example Using Recursion: The Fibonacci Series6.16   Recursion vs. Iteration

  2. Outline6.17   Procedure Overloading and Optional Arguments 6.17.1  Procedure Overloading 6.17.2  Optional Arguments6.18   Modules

  3. 6.1 Introduction • Divide and Conquer • The best way to develop and maintain a large program is to construct it from small, manageable pieces.

  4. 6.2 Modules, Classes and Procedures • Framework Class Library • Provides a rich collection of “prepackaged” classes and methods for performing many operations • Mathematical calculations • String manipulations • Character manipulations • Input/output operations • Error checking

  5. 6.2 Modules, Classes and Procedures • Programmer-defined procedures • FCL cannot provide every conceivable feature that a programmer could want • Three types of procedures • Sub procedures • Function procedures • Event procedures • A procedure is invoked by a procedure call

  6. 6.2 Modules, Classes and Procedures Boss Worker1 Worker2 Worker3 Worker4 Worker5 Fig. 6.1 Hierarchical boss procedure/worker procedure relationship.

  7. 6.2 Modules, Classes and Procedures • Division of code into procedures • Several motivations to divide code into procedures • Divide-and-conquer approach makes program development more manageable • Software reusability • Avoids the repetition of code in a program

  8. 6.2 Modules, Classes and Procedures • Earlier programs had only one procedure that called FCL methods • Next program contains two customized procedures

  9. PrintPayreceives the values of each argument and stores them in the parameters variables hours and wage PrintPay executes when it is invoked by Main Notice that PrintPay appears within modPayment. All procedures must be defined inside a module or a class 1 ' Fig. 6.2: Payment.vb 2 ' Sub procedure that prints payment information. 3 4 Module modPayment 5 6 Sub Main() 7 8 ' call Sub procedure PrintPay 4 times 9 PrintPay(40, 10.5) 10 PrintPay(38, 21.75) 11 PrintPay(20, 13) 12 PrintPay(50, 14) 13 14 Console.ReadLine() ' prevent window from closing 15 End Sub' Main 16 17 ' print amount of money earned in command window 18 Sub PrintPay(ByVal hours AsDouble, ByVal wage AsDecimal) 19 20 ' pay = hours * wage 21 Console.WriteLine("The payment is {0:C}", hours * wage) 22 EndSub' PrintPay 23 24 EndModule' modPayment Payment.vbProgram Output The payment is $420.00 The payment is $826.50 The payment is $260.00 The payment is $700.00

  10. 6.3 Sub Procedures • Format of a procedure definition Sub procedure-name(parameter-list) declarations and statements EndSub • Procedure header • The first line is known as the procedure header • Procedure-name • Directly follows the Sub keyword • Can be any valid identifier • It is used to call this Sub procedure within the program • Procedure body • The declarations and statements in the procedure definition form the procedure body

  11. 6.4 Function Procedures • Similar to Sub procedures • One important difference • Function procedures return a value to the caller

  12. The For structure displays the results of squaring the Integers from 1-10 Square is invoked with the expression Square(i) The Return statement terminates execution of the procedure and returns the result of y^2 1 ' Fig. 6.3: SquareInteger.vb 2 ' Function procedure to square a number. 3 4 ModulemodSquareInteger 5 6 Sub Main() 7 Dim i As Integer ' counter 8 9 Console.WriteLine("Number" & vbTab & "Square" & vbCrLf) 10 11 ' square numbers from 1 to 10 12 For i = 1To10 13 Console.WriteLine(i & vbTab & Square(i)) 14 Next 15 16 End Sub ' Main 17 18 ' Function Square is executed 19 ' only when the function is explicitly called. 20 Function Square(ByVal y As Integer) As Integer 21 Return y ^ 2 22 End Function' Square 23 24 End Module' modSquareInteger SquareInteger.vb

  13. Number Square 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100 SquareInteger.vbProgram Output

  14. 6.4 Function Procedures • Format of a Function procedure definition Function procedure-name(parameter-list) As return-type declarations and statements EndFunction • Return-type • Indicates the data type of the result returned from the Function to its caller • Return expression • Can occur anywhere in a Function • It returns exactly one value • Control returns immediately to the point at which that procedure was invoked

  15. 6.5 Methods • Definition of method • A method is any procedure that is contained within a class • FCL methods • Custom methods in programmer-defined classes

  16. Remember that all forms inherit from class System.Windows.Forms.Form Event handler cmdMaximum_ClickHandles the event in which ButtoncmdMaximum is clicked These are declarations of all the controls used in the GUI. Create these components visually, using the Toolbox 1 ' Fig. 6.4: Maximum.vb 2 ' Program finds the maximum of three numbers input. 3 4 PublicClass FrmMaximum 5 Inherits System.Windows.Forms.Form 6 7 ' prompts for three inputs 8 FriendWithEvents lblOne As System.Windows.Forms.Label 9 FriendWithEvents lblTwo As System.Windows.Forms.Label 10 FriendWithEvents lblThree As System.Windows.Forms.Label 11 12 ' displays result 13 FriendWithEvents lblMaximum As System.Windows.Forms.Label 14 15 ' read three numbers 16 FriendWithEvents txtFirst As System.Windows.Forms.TextBox 17 FriendWithEvents txtSecond As System.Windows.Forms.TextBox 18 FriendWithEvents txtThird As System.Windows.Forms.TextBox 19 20 ' reads inputs and calculate results 21 Friend WithEvents cmdMaximum As System.Windows.Forms.Button 22 23 ' Visual Studio .NET generated code 24 25 ' obtain values in each text box, call procedure Maximum 26 PrivateSub cmdMaximum_Click(ByVal sender As System.Object, _ 27 ByVal e As System.EventArgs) Handles cmdMaximum.Click 28 Maximum.vb

  17. The values in the three TextBoxes are retrieved using the Text property Call to methods that are defined in a class in the FCL must include the class name and the dot (.) operator Call to methods defined in the class that contains the method call need only specify the method name 29 Dim value1, value2, value3 AsDouble 30 31 value1 = txtFirst.Text 32 value2 = txtSecond.Text 33 value3 = txtThird.Text 34 35 lblMaximum.Text = Maximum(value1, value2, value3) 36 EndSub ' cmdMaximum_Click 37 38 ' find maximum of three parameter values 39 Function Maximum(ByVal valueOne AsDouble, _ 40 ByVal valueTwo AsDouble, ByVal valueThree AsDouble) 41 42 Return Math.Max(Math.Max(valueOne, valueTwo), valueThree) 43 EndFunction ' Maximum 44 45 EndClass ' FrmMaximum Maximum.vbProgram Output

  18. 6.5 Methods Parameter Info window Fig. 6.5 Parameter Info feature of the Visual Studio .NET IDE.

  19. 6.5 Methods Fig. 6.6 IntelliSense feature of the Visual Studio .NET IDE.

  20. 6.5 Methods Fig. 6.7 Math class methods.

  21. 6.5 Methods Fig. 6.7 Math class methods.

  22. 6.6 Argument Promotion • Coercion of arguments • The forcing of arguments to be appropriate data type so that they can be passed to a procedure • Widening conversion • Occurs when a type is converted to another type without losing data • Narrowing conversion • Occurs when there is potential for data loss during the conversion • Ex., double to single, double to integer

  23. 6.6 Argument Promotion Mixed-type expressions: singleNumber1 + integerNumber2 Fig. 6.8 Widening conversions.

  24. 6.7 Option Strict and Data-Type Conversions • Option Explicit • Set to On by default • Forces the programmer to declare explicitly all variables before they are used • Option strict • Set to Off by default • When set to On, it forces the programmer to perform an explicit conversion for all narrowing conversions • Class Convert • The methods in class Convert change data types explicitly • Ex., Convert.ToDouble(“4”)

  25. 6.7 Option Strict and Data-Type Conversions Fig. 6.9 Property Pages dialog with Option Strict set to On.

  26. 6.8 Value Types and Reference Types • Variable of a value type • Contains the actual data • Used for a single piece of data • Integer, Double • Variable of a reference type • Contains a location in memory where data is stored • Known as objects • Literals • Values typed directly in program code • Corresponds to one of the primitive data types • User defined Types: • Value type: Enum, Structure • Reference type: class, interface, delegate

  27. 6.8 Value Types and Reference Types Fig. 6.10 Visual Basic primitive data types.

  28. 6.8 Value Types and Reference Types Fig. 6.11 Literals with type characters.

  29. 6.9 Passing Arguments: Pass-by-Value vs. Pass-by-Reference • Pass-by-value • The program makes a copy of the argument’s value and passes that copy to the called procedure • Pass-by-reference • The caller gives the called procedure the ability to access and modify the caller’s original data directly.

  30. When number1 is passed, a copy of the value is passed to the procedure A reference to the value stored in number2 is being passed 1 ' Fig. 6.12: ByRefTest.vb 2 ' Demonstrates passing by reference. 3 4 Module modByRefTest 5 6 ' squares three values ByVal and ByRef, displays results 7 Sub Main() 8 Dim number1 As Integer = 2 9 10 Console.WriteLine("Passing a value-type argument by value:") 11 Console.WriteLine("Before calling SquareByValue, " & _ 12 "number1 is {0}", number1) 13 SquareByValue(number1) ' passes number1 by value 14 Console.WriteLine("After returning from SquareByValue, " & _ 15 "number1 is {0}" & vbCrLf, number1) 16 17 Dim number2 AsInteger = 2 18 19 Console.WriteLine("Passing a value-type argument"& _ 20 " by reference:") 21 Console.WriteLine("Before calling SquareByReference, " & _ 22 "number2 is {0}", number2) 23 SquareByReference(number2) ' passes number2 by reference 24 Console.WriteLine("After returning from " & _ 25 "SquareByReference, number2 is {0}" & vbCrLf, number2) 26 27 Dim number3 As Integer = 2 28 ByRefTest.vb

  31. ByVal indicates that value-type arguments should be passed by value Enclosing arguments in parenthesis forces pass-by-value ByRef gives direct access to the value stored in the original variable 29 Console.WriteLine("Passing a value-type argument" & _ 30 " by reference, but in parentheses:") 31 Console.WriteLine("Before calling SquareByReference " & _ 32 "using parentheses, number3 is {0}", number3) 33 SquareByReference((number3)) ' passes number3 by value 34 Console.WriteLine("After returning from " & _ 35 "SquareByReference, number3 is {0}", number3) 36 37 End Sub ' Main 38 39 ' squares number by value (note ByVal keyword) 40 Sub SquareByValue(ByVal number As Integer) 41 Console.WriteLine("After entering SquareByValue, " & _ 42 "number is {0}", number) 43 number *= number 44 Console.WriteLine("Before exiting SquareByValue, " & _ 45 "number is {0}", number) 46 End Sub' SquareByValue 47 48 ' squares number by reference (note ByRef keyword) 49 Sub SquareByReference(ByRef number As Integer) 50 Console.WriteLine("After entering SquareByReference" & _ 51 ", number is {0}", number) 52 number *= number 53 Console.WriteLine("Before exiting SquareByReference" & _ 54 ", number is {0}", number) 55 End Sub' SquareByReference 56 57 End Module' modByRefTest ByRefTest.vb

  32. Passing a value-type argument by value: Before calling SquareByValue, number1 is 2 After entering SquareByValue, number is 2 Before exiting SquareByValue, number is 4 After returning from SquareByValue, number1 is 2 Passing a value-type argument by reference: Before calling SquareByReference, number2 is 2 After entering SquareByReference, number is 2 Before exiting SquareByReference, number is 4 After returning from SquareByReference, number2 is 4 Passing a value-type argument by reference, but in parentheses: Before calling SquareByReference using parentheses, number3 is 2 After entering SquareByReference, number is 2 Before exiting SquareByReference, number is 4 After returning from SquareByReference, number3 is 2 Program Output

  33. 6.10 Duration of Identifiers • Identifier’s duration • Period during which the identifier exists in memory • Identifier’s scope • Portion of a program in which the variable’s identifier can be referenced • Automatic duration • Identifiers that represent local variables in a procedure have automatic duration. They are called local variables. • Variables declared in a module exists thru a program’s execution • Instance variable • A variable declared in a class • They exist as long as their containing class is loaded in memory

  34. 6.11 Scope Rules • Possible scopes • Class scope • Begins at the class identifier after keyword Class and terminates at the EndClass statement • Module scope • Variable declared in a module have module scope, which is similar to class scope • Namespace scope • Procedures defined in a module have namespace scope, which generally means that they may be accessed throughout a project, which is done by declaring with Public, instead of Dim • Block scope • Identifiers declared inside a block, such as the body of a procedure definition or the body of an If/Then selection structure, have block scope, which begins at declaration, and ends at END

  35. This variable is hidden in any procedure that declares a variable named value Automatic variable value is destroyed when MethodA terminates None of the method calls modifies this variable – both methods refer to variables in other scopes 1 ' Fig. 6.13: Scoping.vb 2 ' Demonstrates scope rules and instance variables. 3 4 Public Class FrmScoping 5 Inherits System.Windows.Forms.Form 6 7 Friend WithEvents lblOutput As System.Windows.Forms.Label 8 9 ' Windows Form Designer generated code 10 11 ' instance variable can be used anywhere in class 12 Dim value AsInteger = 1 13 14 ' demonstrates class scope and block scope 15 PrivateSub FrmScoping_Load(ByVal sender As System.Object, _ 16 ByVal e As System.EventArgs) HandlesMyBase.Load 17 18 ' variable local to FrmScoping_Load hides instance variable 19 Dim value AsInteger = 5 20 21 lblOutput.Text = "local variable value in" & _ 22 " FrmScoping_Load is " & value 23 24 MethodA() ' MethodA has automatic local value 25 MethodB() ' MethodB uses instance variable value 26 MethodA() ' MethodA creates new automatic local value 27 MethodB() ' instance variable value retains its value 28 29 lblOutput.Text &= vbCrLf & vbCrLf & "local variable " & _ 30 "value in CScoping_Load is " & value 31 EndSub' FrmScoping_Load 32 33 ' automatic local variable value hides instance variable 34 Sub MethodA() 35 Dim value As Integer = 25' initialized after each call Scoping.vb

  36. When MethodB procedure refers to variable value, the instance variable value (line 12) is used. 36 37 lblOutput.Text &= vbCrLf & vbCrLf & "local variable " & _ 38 "value in MethodA is " & value & " after entering MethodA" 39 value += 1 40 lblOutput.Text &= vbCrLf & "local variable " & _ 41 "value in MethodA is " & value & " before exiting MethodA" 42 EndSub' MethodA 43 44 ' uses instance variable value 45 Sub MethodB() 46 lblOutput.Text &= vbCrLf & vbCrLf & "instance variable" & _ 47 " value is " & value & " after entering MethodB" 48 value *= 10 49 lblOutput.Text &= vbCrLf & "instance variable " & _ 50 "value is " & value & " before exiting MethodB" 51 EndSub' MethodB 52 53 End Class ' FrmScoping Scoping.vb

  37. 6.12 Random-Number Generation • Random class • Produces values at random • Keyword New creates an object of a specified type and returns the object’s location in memory • Next Method • Generates a positive Integer value between zero and the constant Int32.MaxValue (2,147,483,647) • The current time of day becomes the seed value for the calculation • When a single argument is passed to Next, the values returned will be in the range from 0 to the value of that argument • Scaling • By passing two arguments, the programmer is allowed to specify the bottom range too

  38. Note that we must use 7 as the second argument to produce integers in the range from 1-6 Go to the next line every time five numbers are generated 1 ' Fig. 6.14: RandomInteger.vb 2 ' Generating random integers. 3 4 Imports System.Windows.Forms 5 6 Module modRandomInteger 7 8 Sub Main() 9 Dim randomObject As Random = New Random() 10 Dim randomNumber AsInteger 11 Dim output AsString = "" 12 Dim i As Integer 13 14 For i = 1To20 15 randomNumber = randomObject.Next(1, 7) 16 output &= randomNumber & " " 17 18 If i Mod5 = 0Then ' is i a multiple of 5? 19 output &= vbCrLf 20 EndIf 21 22 Next 23 24 MessageBox.Show(output, "20 Random Numbers from 1 to 6", _ 25 MessageBoxButtons.OK, MessageBoxIcon.Information) 26 End Sub ' Main 27 28 End Module ' modRandomInteger RandomInteger.vb

  39. Event-handling method cmdRoll_Click, executes whenever the user clicks cmdRoll RandomNumber is an instance variable of FrmRollDice. This allows the same Random object to be used each time DisplayDie executes 1 ' Fig. 6.15: RollDice.vb 2 ' Rolling four dice. 3 4 Imports System.IO 5 6 PublicClass FrmRollDice 7 Inherits System.Windows.Forms.Form 8 9 ' button for rolling dice 10 FriendWithEvents cmdRoll As System.Windows.Forms.Button 11 12 ' labels to display die images 13 FriendWithEvents lblDie1 As System.Windows.Forms.Label 14 FriendWithEvents lblDie2 As System.Windows.Forms.Label 15 FriendWithEvents lblDie3 As System.Windows.Forms.Label 16 FriendWithEvents lblDie4 As System.Windows.Forms.Label 17 18 ' Visual Studio .NET generated code 19 20 ' declare Random object reference 21 Dim randomNumber As Random = New Random() 22 23 ' display results of four rolls 24 PrivateSub cmdRoll_Click(ByVal sender As System.Object, _ 25 ByVal e As System.EventArgs) Handles cmdRoll.Click 26 27 ' method randomly assigns a face to each die 28 DisplayDie(lblDie1) 29 DisplayDie(lblDie2) 30 DisplayDie(lblDie3) 31 DisplayDie(lblDie4) 32 EndSub ' cmdRoll_Click 33 RollDice.vb

  40. Class Image is contained in the System.Drawing namespace, which is imported by default in all Windows Applications Image property displays an image on the label Method Directory.GetCurrentDirectory returns the location of the folder in which the current project is located, including bin 34 ' get a random die image 35 Sub DisplayDie(ByVal dieLabel As Label) 36 37 ' generate random integer in range 1 to 6 38 Dim face As Integer = randomNumber.Next(1, 7) 39 40 ' load corresponding image 41 dieLabel.Image = Image.FromFile( _ 42 Directory.GetCurrentDirectory & "\Images\die" & _ 43 face & ".png") 44 EndSub ' DisplayDie 45 46 EndClass' FrmRollDice RollDice.vb

  41. The TextBox is used to display the cumulative frequencies of each face We declare counters for each of the possible rolls 1 ' Fig. 6.16: RollTwelveDice.vb 2 ' Rolling 12 dice with frequency chart. 3 4 Imports System.IO 5 6 PublicClass FrmRollTwelveDice 7 Inherits System.Windows.Forms.Form 8 9 ' labels to display die images 10 FriendWithEventslblDie1AsSystem.Windows.Forms.Label 11 FriendWithEventslblDie2AsSystem.Windows.Forms.Label 12 FriendWithEventslblDie3AsSystem.Windows.Forms.Label 13 FriendWithEventslblDie4AsSystem.Windows.Forms.Label 14 FriendWithEventslblDie5AsSystem.Windows.Forms.Label 15 FriendWithEventslblDie6AsSystem.Windows.Forms.Label 16 FriendWithEventslblDie7AsSystem.Windows.Forms.Label 17 FriendWithEventslblDie8AsSystem.Windows.Forms.Label 18 FriendWithEventslblDie9AsSystem.Windows.Forms.Label 19 FriendWithEventslblDie10AsSystem.Windows.Forms.Label 20 FriendWithEventslblDie11AsSystem.Windows.Forms.Label 21 FriendWithEventslblDie12AsSystem.Windows.Forms.Label 22 23 ' displays roll frequencies 24 FriendWithEvents displayTextBox As _ 25 System.Windows.Forms.TextBox 26 27 ' Visual Studio .NET generated code 28 29 ' declarations 30 Dim randomObject As Random = New Random() 31 Dim ones, twos, threes, fours, fives, sixes AsInteger 32 RollTwelveDice.vb

  42. The “P” format code is used to display the frequency of each roll as percentages 35 PrivateSub cmdRoll_Click _ 34 (ByVal sender As System.Object, _ 35 ByVal e As System.EventArgs) Handles cmdRoll.Click 36 37 ' assign random faces to 12 dice using DisplayDie 38 DisplayDie(lblDie1) 39 DisplayDie(lblDie2) 40 DisplayDie(lblDie3) 41 DisplayDie(lblDie4) 42 DisplayDie(lblDie5) 43 DisplayDie(lblDie6) 44 DisplayDie(lblDie7) 45 DisplayDie(lblDie8) 46 DisplayDie(lblDie9) 47 DisplayDie(lblDie10) 48 DisplayDie(lblDie11) 49 DisplayDie(lblDie12) 50 51 Dim total AsInteger = ones + twos + threes + fours + _ 52 fives + sixes 53 54 Dim output As String 55 56 ' display frequencies of faces 57 output = "Face" & vbTab & vbTab & _ 58 "Frequency" & vbTab & "Percent" 59 60 output &= vbCrLf & "1" & vbTab & vbTab & ones & _ 61 vbTab & vbTab & String.Format("{0:P}", ones / total) 62 63 output &= vbCrLf & "2" & vbTab & vbTab & twos & vbTab & _ 64 vbTab & String.Format("{0:P}", twos / total) 65 66 output &= vbCrLf & "3" & vbTab & vbTab & threes & vbTab & _ 67 vbTab & String.Format("{0:P}", threes / total) RollTwelveDice.vb

  43. SelectCase is used to calculate the frequency 68 69 output &= vbCrLf & "4" & vbTab & vbTab & fours & vbTab & _ 70 vbTab & String.Format("{0:P}", fours / total) 71 72 output &= vbCrLf & "5" & vbTab & vbTab & fives & vbTab & _ 73 vbTab & String.Format("{0:P}", fives / total) 74 75 output &= vbCrLf & "6" & vbTab & vbTab & sixes & vbTab & _ 76 vbTab & String.Format("{0:P}", sixes / total) & vbCrLf 77 78 displayTextBox.Text = output 79 EndSub ' cmdRoll_Click 80 81 ' display a single die image 82 Sub DisplayDie(ByVal dieLabel As Label) 83 84 Dim face AsInteger = randomObject.Next(1, 7) 85 86 dieLabel.Image = _ 87 Image.FromFile(Directory.GetCurrentDirectory & _ 88 "\Images\die" & face & ".png") 89 90 ' maintain count of die faces 91 SelectCase face 92 93 Case1 94 ones += 1 95 96 Case2 97 twos += 1 98 99 Case3 100 threes += 1 101 RollTwelveDice.vb

  44. 102 Case4 103 fours += 1 104 105 Case5 106 fives += 1 107 108 Case6 109 sixes += 1 110 111 EndSelect 112 113 EndSub ' DisplayDie 114 115 EndClass ' FrmRollTwelveDice RollTwelveDice.vb

  45. 6.13 Example: Game of Chance • Craps • The next application simulates one of the most popular games of chance • The player must roll two dice on the first and all subsequent rolls

  46. A GroupBox is a container used to group related components Enumerations are used to define groups of related constants 1 ' Fig 6.17: CrapsGame.vb 2 ' Playing a craps game. 3 4 Imports System.IO 5 6 PublicClass FrmCrapsGame 7 Inherits System.Windows.Forms.Form 8 9 FriendWithEvents cmdRoll As Button ' rolls dice 10 FriendWithEvents cmdPlay As Button ' starts new game 11 12 ' dice displayed after each roll 13 FriendWithEvents picDie1 As PictureBox 14 FriendWithEvents picDie2 As PictureBox 15 16 ' pointDiceGroup groups dice representing player's point 17 FriendWithEvents pointDiceGroup As GroupBox 18 FriendWithEvents picPointDie1 As PictureBox 19 FriendWithEvents picPointDie2 As PictureBox 20 21 FriendWithEvents lblStatus As Label 22 23 ' Visual Studio .NET generated code 24 25 ' die-roll constants 26 Enum DiceNames 27 SNAKE_EYES = 2 28 TREY = 3 29 CRAPS = 7 30 YO_LEVEN = 11 31 BOX_CARS = 12 32 End Enum 33 CrapsGame.vb

  47. Keyword Const creates a single constant identifier in which values cannot be modified after they are declared Keyword Nothing can be used with reference-type variables to specify that no object is associated with the variable Setting the Image property to Nothing causes the PictureBoxes to appear blank The Select structure analyzes the roll returned by RollDice to determine how play should continue 34 ' file-name and directory constants 35 ConstFILE_PREFIXAsString = "/images/die" 36 ConstFILE_SUFFIXAsString = ".png" 37 38 Dim myPoint AsInteger 39 Dim myDie1 AsInteger 40 Dim myDie2 AsInteger 41 Dim randomObject As Random = New Random() 42 43 ' begins new game and determines point 44 Private Sub cmdPlay_Click(ByVal sender As System.Object, _ 45 ByVal e As System.EventArgs) Handles cmdPlay.Click 46 47 ' initialize variables for new game 48 myPoint = 0 49 pointDiceGroup.Text = "Point" 50 lblStatus.Text = "" 51 52 ' remove point-die images 53 picPointDie1.Image = Nothing 54 picPointDie2.Image = Nothing 55 56 Dim sum AsInteger = RollDice() 57 58 ' check die roll 59 SelectCase sum 60 61 Case DiceNames.CRAPS, DiceNames.YO_LEVEN 62 63 ' disable roll button 64 cmdRoll.Enabled = False 65 lblStatus.Text = "You Win!!!" 66 CrapsGame.vb

  48. Disabling a Button causes no action to be performed when the Button is clicked 67 Case DiceNames.SNAKE_EYES, _ 68 DiceNames.TREY, DiceNames.BOX_CARS 69 70 cmdRoll.Enabled = False 71 lblStatus.Text = "Sorry. You Lose." 72 73 Case Else 74 myPoint = sum 75 pointDiceGroup.Text = "Point is " & sum 76 lblStatus.Text = "Roll Again!" 77 DisplayDie(picPointDie1, myDie1) 78 DisplayDie(picPointDie2, myDie2) 79 cmdPlay.Enabled = False 80 cmdRoll.Enabled = True 81 82 End Select 83 84 End Sub ' cmdPlay_Click 85 86 ' determines outcome of next roll 87 PrivateSub cmdRoll_Click(ByVal sender As System.Object, _ 88 ByVal e As System.EventArgs) Handles cmdRoll.Click 89 90 Dim sum AsInteger = RollDice() 91 92 ' check outcome of roll 93 If sum = myPoint Then 94 lblStatus.Text = "You Win!!!" 95 cmdRoll.Enabled = False 96 cmdPlay.Enabled = True 97 ElseIf sum = DiceNames.CRAPSThen 98 lblStatus.Text = "Sorry. You Lose." 99 cmdRoll.Enabled = False 100 cmdPlay.Enabled = True 101 End If CrapsGame.vb

  49. RollDice generates two random numbers and calls method DisplayDie, which loads an appropriate die image on the PictureBox passed to it. 102 103 End Sub' cmdRoll_Click 104 105 ' display die image 106 Sub DisplayDie(ByVal picDie As PictureBox, _ 107 ByVal face AsInteger) 108 109 ' assign die image to picture box 110 picDie.Image = _ 111 Image.FromFile(Directory.GetCurrentDirectory & _ 112 FILE_PREFIX & face & FILE_SUFFIX) 113 End Sub' DisplayDie 114 115 ' generate random die rolls 116 Function RollDice() As Integer 117 Dim die1, die2 As Integer 118 119 ' determine random integer 120 die1 = randomObject.Next(1, 7) 121 die2 = randomObject.Next(1, 7) 122 123 ' display rolls 124 DisplayDie(picDie1, die1) 125 DisplayDie(picDie2, die2) 126 127 ' set values 128 myDie1 = die1 129 myDie2 = die2 130 131 Return die1 + die2 132 End Function ' RollDice 133 134 End Class' FrmCrapsGame CrapsGame.vb

  50. GroupBox PictureBoxes (displaying images) CrapsGame.vb

More Related