BACK TO THE LOTTERY ASSISTANT GAME


Now it is time to turn your attention back to this chapter's game project. You will create the Lottery Assistant game using the five development steps that you have followed in previous chapters. By the time you have finished creating this game, you will have demonstrated your ability to modify your Visual Basic applications by adding fully functional menu systems to your forms.

Designing the Game

The Lottery Assistant game is played on a single form. Therefore, it consists of a single form, upon which you add the nine controls listed in Table 4.1.

Table 4.1: Form Controls for the Lottery Assistant Game

Control Type

Control Name

Description

Label

lblFullSet

Identifies the TextBox control where the player specifies how many numbers constitute a full set of lottery numbers

Label

lblNoPics

Identifies the TextBox control where the player specifies how many sets of lottery numbers the game should generate

Label

lblNoRange

Identifies the TextBox control where the player specifies the range of numbers from which the game should generate lottery numbers

Label

lblOutput

Identifies the TextBox control where the game displays the lottery numbers that it generates

TextBox

txtFullSet

The TextBox control where the player specifies how many numbers constitute a full set of lottery numbers

TextBox

txtNoPics

The TextBox control where the player specifies how many sets of lottery numbers the game should generate

TextBox

txtNoRange

The TextBox control where the player specifies the range of numbers from which the game should generate lottery numbers

TextBox

txtOutput

The TextBox control where the game displays the lottery numbers that it generates

Menustrip

MenuStrip1

The name of the MenuStrip control that will be used to created the game's menu system

Step 1: Creating a New Visual Basic Project

The first step in developing the Lottery Assistant game is to start Visual Basic and open a new project, as outlined below.

  1. If you have not already done so, start up Visual Basic 2005 Express and then click on File and select New Project. The New Project dialog will appear.

  2. Select Windows Application template.

  3. Type Lottery Assistant as the name of your new application in the Name field located at the bottom of the New Project window.

  4. Click on OK to close the New Project dialog.

In response, Visual Basic creates a new project for you and displays a blank form on which you will design the game's user interface.

Step 2: Creating the User Interface

The next step in the creation of the Lottery Assistant game is to assemble the game's interface. To begin, let's review the overall layout of the game user interface, as shown in Figure 4.31.

image from book
Figure 4.31: Completing the interface design for the Lottery Assistant game.

  1. Begin by adding a MenuStrip control to the form. By default, Visual Basic assigns the name MenuStrip1 to the control.

  2. Add four Label controls to the form and line them up as shown in Figure 4.31. By default, Visual Basic names them Label1 to Label4.

  3. Add three TextBox controls to the form and line them up horizontally with the first Label controls. By default, Visual Basic names these controls TextBox1 to TextBox3.

  4. Finally, add a fourth TextBox control to the form just under the Label4 control. Set its Multiline property equal to True and resize it so that it covers most of the bottom half of the form, as shown in Figure 4.31. By default, Visual Basic assigns this control the name TextBox4.

The layout of the Visual Basic form is now complete. All controls should be visible on the form except for the MenuStrip1 control, which is displayed in a Component Tray just below the form.

Step 3: Customizing Form and Control Properties

Before you start customizing the properties associated with the controls that you just added to the form, you need to modify a few properties belonging to the form itself. The properties that need to be changed, along with their new value assignments, are listed in Table 4.2.

Table 4.2: Property Value Assignments for the Lottery Assistant Game's Form

Property

Value

Name

ItaForm

BackColor

White

FormBorderStyle

Fixed3D

StartPosition

CenterScreen

Text

Lottery Assistant

Next, let's set the Name and Text properties for each of the four Label controls as specified in Table 4.3.

Table 4.3: Property Changes for Each of the Label Controls

Control

Property

Value

Label1

Name

lblFullSet

 

Text

How many numbers make up a full set?

Labe12

Name

lblNoPics

 

Text

How many sets of lottery numbers do you want?

Labe13

Name

lblNoRange

 

Text

What is the highest number that can be picked?

Labe14

Name

1bloutput

Readonly

True

Text

Your lottery numbers:

Note that you may need to adjust the location of the first three Textbox controls after you change the text properties associated with the first three label controls. Now let's make modifications belonging to each of the TextBox controls as listed in Table 4.4.

Table 4.4: Property Changes for Each of the Textbox Controls

Control

Property

Value

TextBox1

Name

txtFullSet

TextBox2

Name

txtNoPics

TextBox3

Name

txtNoRange

TextBox4

Name

txtOutput

Readonly

True

ScrollBars

Vertical

TabStop

False

Setting the ReadOnly property to True for the fourth TextBox control prevents the player from attempting to enter text into it. Setting the ScrollBars property to Vertical adds a scrollbar to the text box in order to allow the player to scroll up and down when more sets of lottery numbers are generated than can be displayed at one time. Setting the TabStop property to False takes the fourth TextBox control out of the tab index.

The last control that requires property modification is the MenuStrip control. For starters, click on the control and change its name to mnuStrip. Next, configure the MenuStrip control to create a menu system composed of the menus outlined in Table 4.5.

Table 4.5: Menus for the Lottery Assistant Game

Text Property

Resulting Menu Name

Description

&File

FileToolStripMenuItem

Contains commands that control the game's execution

&Options

OptionsToolStripMenuItem

Contains commands that configure the game's display

&Help

HelpToolStripMenultem

Provides access to additional information about the game

Once you have created each of the menus listed in Table 4.5, it is time to configure each menu by adding menu items. Table 4.6 lists the menu items that you'll need to add to the FileToolStripMenuItem menu.

Table 4.6: Menu Items Residing Under the File Menu

Text Property

Resulting Menu Name

Description

&Get Numbers

GetNumberSTOOlStripMenultem

Retrieves randomly generated lottery numbers

&Clear Numbers

ClearToolStripMenuItem

Clears out any text displayed in the game's TextBox controls

&Exit

ExitToolStripMenuItem1

Terminates game execution

The Clear Number menu item will be used to execute programming statements that remove any text that may currently be stored in the form's TextBox controls. When the form is first displayed, there won't be any text displayed in the TextBox controls. Therefore, it is appropriate to initially disable this Clear Number menu item at design time. Later, when the application is running and the player begins to key in text, you'll add programming logic to enable this menu item. So, to disable the Clear Numbers menu item, select it and set its Enabled property (in the Properties window) to False.

Table 4.7 lists the menu items that you are to add to the OptionsToolStripMenuItem menu.

Table 4.7: Menu Items Residing Under the Options Menu

Text Property

Resulting Menu Name

Description

&Background

BackgroundToolStripMenultem

Provides access to a submenu where the game's background color can be changed

&Font Size

FontSizeToolStripMenUItem

Provides access to a submenu where the font size used to control the display of lottery numbers can be changed

Table 4.8 lists the menu item that you are to add to the HelpToolStripMenuItem menu.

Table 4.8: Menu Items Residing Under the Help Menu

Text Property

Resulting Menu Name

Description

&About

AboutToolStripMenuItem

Executes code that displays information about the game in a pop-up window

At this point, you have defined all three of the game's menus, as well as the menu items that reside underneath them. However, you are not done yet. Both the Background and Font Size menu items need to be set up to provide access to their own submenus. Table 4.9 outlines the contents of the Background submenu.

Table 4.9: Menu Items Residing on the Background Submenu

Text Property

Resulting Menu Name

Description

&White

WhiteToolstripMenuItem

Sets the form's background color to white

&Yellow

YellowToolStripMenuItem

Sets the form's background color to yellow

&Gray

GrayToolStripMenuztem

Sets the form's background color to gray

Table 4.10 outlines the contents of the Font Size submenu.

Table 4.10: Menu Items Residing on the Font Size Submenu

Text Property

Resulting Menu Name

Description

8

ToolStripMenuIteml

Sets the font size displayed in the txtoutput control to 8

10

ToolstripMenultem2

Sets the font size displayed in the txtoutput control to 10

12

ToolStripMenuItem3

Sets the font size displayed in the txtoutput control to 12

Before you call it quits with the Lottery Assistant game's menu system, let's add just a few more bells and whistles. For starters, add the access key F1 to the Get Numbers menu item located under the File menu. Then add the access key F2 to the Clear Numbers menu item, which is also located under the File menu. Then set the Checked property for the White submenu item under the Options menu to True, indicating that it is the default menu item, and then do the same things for the Checked property belonging to the first menu item on the Font Size submenu.

That's all the property modifications that are required for the Lottery Assistant game's controls and menu system. Now it is time to add the program statements required to make the game work.

Step 4: Adding a Little Programming Logic

All of the Lottery Assistant game's program code is controlled by the game's menu system. Unlike the game projects that you worked on in previous chapters, there are no Button controls for the player to click on in this game. To keep things straightforward, let's begin by adding the programming statements for each menu item one by one, starting with the first menu item located on the File menu and finishing up with the last menu item under the Help menu.

Adding Code to the Get Numbers Menu Item

The easiest way to associate programming statements with a menu item is to double-click on the menu item. When you do, Visual Basic automatically opens the code editor and creates a couple lines of initial code for you. So, for starters, double-click on the Get Numbers menu item located under the File menu. The following code will be automatically generated and displayed in the code editor.

 Private Sub GetNumbersToolStripMenuItem_Click(ByVal sender _       As System.Object, ByVal  e As System.EventArgs) _       Handles GetNumbersToolStripMenuItem.Click End Sub 

You will key in all the programming statements that are to be executed when the Get Numbers menu item is clicked between these two statements. For starters, add the following statements. These statements define variables and an array used by the application to store and manipulate the data it needs to execute. For now, just key in these statements exactly as shown. In Chapter 5, "Storing and Retrieving Data in Memory," you will learn all about variables and arrays.

 Dim intForLoopCtr As Integer = 0 Dim blnFullSetComplete As Boolean = False Dim intRndNo As Integer = 0 Dim strDisplayString As String = "" Dim intNoOfValidPics As Integer = 0 Dim aintLotteryArray(10) As Array Dim intNumberCount As Integer = 0 Dim strTestString As String = "_" 

Next add the following statements, which check to see if the player has supplied valid input into the first TextBox control and displays an error message if this is not the case. Note the Return statement, which prevents Visual Basic from processing any of the remaining statements associated with the Get Numbers menu item Click event.

 If txtFullSet.Text = "" Then      MessageBox.Show("You must specify how many numbers " & _      "make up a full set.")      Return End If 

The next set of statements checks to ensure that the player entered numeric data into the first TextBox control and displays an error message if this is not the case.

 If IsNumeric(txtFullSet.Text) = False Then      MessageBox.Show("You must specify numeric input when " & _      "specifying how many numbers make up a full set.")      Return End If 

Trick 

You can use Visual Basic's IsNumeric function to test whether a value is numeric or not.

The next set of statements to be added check to see if the player entered a number greater than 10 in the first TextBox control and displays an error message if this is the case.

 If Int32.Parse(txtFullSet.Text) > 10 Then      MessageBox.Show("The maximum number of numbers in a full " & _        "set is 10.  Please enter a number between 3 - 10.")      Return End If 

Trick 

By default, anything the player types into a TextBox control is seen by Visual Basic as a text string. You can use Visual Basic's Int32.Parse method to convert a text string value to an integer.

Now add the following statements, which check to make sure that the user specified a number of no less than 3 in the first TextBox control.

 If Int32.Parse(txtFullSet.Text) < 3 Then      MessageBox.Show("The minimum number of numbers in a full " & _        "set is  3. Please enter a number between 3 - 10.")      Return End If 

Let's add program statements that validate the contents of the second TextBox control. These statements display error messages if the player fails to supply any text, if the player does not supply numeric input, or if the player tries to specify a number less than 1 or greater than 10.

 If txtNoPics.Text = "" Then      MessageBox.Show("You must specify how many sets of " & _        "lottery numbers you want.")      Return End If If IsNumeric(txtNoPics.Text) = False Then      MessageBox.Show("You must specify numeric input when " & _        "specifying how many sets of lottery numbers you want.")      Return End If If Int32.Parse(txtNoPics.Text) > 10 Then      MessageBox.Show("The maximum number of lottery tickets " & _        "that can be generated is 10. Please enter a number " & _        "between 1 - 10.")      Return End If If Int32.Parse(txtNoPics.Text) < 1 Then      MessageBox.Show("The minimum number of lottery tickets " & _        "that can be generated is 1. Please enter a number " & _        "between 1 - 10.")      Return End If 

Now let's add program statements that validate the contents of the third TextBox control. These statements display error messages if the player fails to supply any text, if the player does not supply numeric input, or if the player tries to specify a number that is less than 9 or greater than 50.

 If txtNoRange.Text = "" Then      MessageBox.Show("You must specify the highest number " & _        " that can be picked.")      Return End If If IsNumeric(txtNoRange.Text) = False Then      MessageBox.Show("You must specify numeric input when " &_        "specifying the highest number that can be picked.")      Return End If If Int32.Parse(txtNoRange.Text) > 50 Then      MessageBox.Show("The maximum value for the highest number " & _        "that can be picked is 50. Please enter a number between " & _        "less than or equal to 50.")      Return End If If Int32.Parse(txtNoRange.Text) < 9= False Then      MessageBox.Show("The minimum value for the highest number " & _        "that can be  picked is 9. Please enter  a number greater " & _        "than or equal to 9.")      Return End If 

Next add the following statements. These statements include a For loop and a Do loop, which you will learn more about in Chapter 7, "Processing Lots of Data with Loops." The For loop executes once for each set of lottery numbers that the player wants generated. The Do loop executes repeatedly until a complete set of numbers has been generated.

 For intForLoopCtr = 1 To CInt(txtNoPics.Text) :      Do Until blnFullSetComplete = True           Randomize()           intRndNo = _                FormatNumber(Int((txtNoRange.Text * Rnd()) + 1))           If InStr(strTestString, _                Convert.ToString("_" & intRndNo & "_")) = 0 Then                strDisplayString = strDisplayString & " " & _                  intRndNo & ControlChars.Tab                intNoOfValidPics = intNoOfValidPics + 1                strTestString = strTestString & intRndNo & "_"           End If           If intNoOfValidPics = Int32.Parse(txtFullSet.Text). Then                blnFullSetComplete = True                strDisplayString = strDisplayString & _                  ControlChars.NewLine & ControlChars.NewLine                strTestString = "_"            End If      Loop      blnFullSetComplete = False      intNoOfValidPics = 0 Next 

The basic logic used in the statements wrapped inside the Do loop is as follows:

  • Get a randomly generated number.

  • Add that number to a string representing a list of lottery numbers, but don't allow duplicate numbers to be added to the list.

  • Format the display string so that a new line is generated for each set of lottery numbers.

The programming logic used in these statements is more than a little involved. I'll defer further discussion on this group of statements at this point until after you have had the chance to read Chapters 5 through 8.

The last program statements that you will add to the code that executes in response to the Get Numbers menu item's Click event is shown below.

 txtOutput.Text = strDisplayString GetNumbersToolStripMenuItem.Enabled = False C1earToolStripMenuItem.Enabled = True 

The first of these three statements assigns the list of randomly generated lottery numbers created by the two previous loops to the txtOutput control's Text property, thus making the numbers visible to the player. The last two statements disable the Get Numbers menu item and enable the Clear Numbers menu item.

Adding Code to the Clear Numbers Menu Item

Now, switch back to the designer view, drill down into the File menu, and try to double-click on the Clear Numbers menu item. You may be surprised to see that you cannot use this technique to access the menu item's Click event. This is because the menu item has been disabled. However, you can still access this menu item's click event by remaining in the code editor and selecting ClearToolStripMenuItem from the drop-down list located in the upper left-hand side of the code editor. Once selected, all the events associated with this menu item become accessible in the drop-down list located on the upper right-hand side of the code editor. Use this drop-down list to select the Click event. The code editor will respond by generating the following code for you.

 Private Sub C1earToolStripMenuItem_Click(ByVal sender _        As System.Object, ByVal e As System.EventArgs) _        Handles C1earToolStripMenuItem.Click End Sub 

Add the following statement between the two statements shown above. The first four statements clear out any text displayed in the four TextBox controls. The next statement places the cursor in the first TextBox control, and the last statement enables the Get Numbers menu item.

 txtFullSet.Text = "" txtNoPics.Text = "" txtNoRange.Text = "" txtOutput.Text = "" txtFullSet.Focus() GetNumbersToolStripMenuItem.Enabled = True 

Adding Code to the Exit Menu Item

Now return to the designer view and double-click on the Exit menu item located under the File menu. Modify the code that is generated for you by inserting the Application.Exit() statement as shown below.

 Private Sub ExitToolStripMenuIteml Click(ByVal sender _        As System.Object, ByVal e As System.EventArgs) _        Handles ExitToolStripMenuIteml.Click          Application.Exit() End Sub 

Adding Code to the White Menu Item

Now it is time to start adding the program statements required to make the menu items on the Background submenu work. Start by accessing the click event for the White menu item and modify the code that is automatically generated as shown below.

 Private Sub WhiteToolStripMenuItem_Click(ByVal sender _        As System.Object, ByVal e As System.EventArgs) _        Handles WhiteToolStripMenuItem.Click          Me.BackColor = Color.White          WhiteToolStripMenuItem.Checked = True          YellowToolStripMenuItem.Checked = False          GrayToolStripMenuItem.Checked = False End Sub 

As you can see, you are adding four statements. The first statement changes the background color of the parent object (the form) to white. The next statement places a check mark to the right of the White menu item. The last two statements make sure that the Yellow and Gray menu items do not display a check mark.

Adding Code to the Yellow Menu Item

Next access the click event for the yellow submenu item and modify the code that is automatically generated as shown below.

 Private Sub YellowToolStripMenuItem_Click(ByVal sender _        As System.Object, ByVal e As System.EventArgs) _        Handles YellowToolStripMenuItem.Click          Me.BackColor = Color.LightYellow          WhiteToolStripMenuItem.Checked = False          YellowToolStripMenuItem.Checked = True          GrayToolStripMenuItem.Checked = False End Sub 

As you can see, the only difference between this and the code that you added to the White menu item is that this code changes the background color to yellow and sets the check mark for the Yellow menu item.

Adding Code to the Gray Menu Item

Now access the click event for the Gray menu item and modify the code that is automatically generated as shown below.

 Private Sub GrayToolStripMenuItem_Click(ByVal sender _        As System.Object, ByVal e As System.EventArgs) _        Handles GrayToolStripMenuItem.Click          Me.BackColor = Color.LightGray          WhiteToolStripMenuItem.Checked = False          YellowToolStripMenuItem.Checked = False          GrayToolStripMenuItem.Checked = True End Sub 

Adding Code to the First Font Size Submenu Item

Let's add the code that will execute when the menu items on the Font Size submenu are clicked. For starters, access the click event for the first menu item in the Font Sizes submenu (the menu item that sets the font size to 8) and modify the code that is automatically generated as shown below.

 Private Sub ToolStripMenuItem1_Click(ByVal sender _        As System.Object, ByVal e As System.EventArgs) _        Handles ToolStripMenuItem1.Click          txtOutput.Font = New Font("Microsoft Sans Serif", 8)          ToolStripMenuItem1.Checked = True          ToolStripMenuItem2.Checked = False          ToolStripMenuItem3.Checked = False End Sub 

As you can see, the first statement that you added sets the Font property or the txtOutput control to Microsoft Sans Serif and specifies a font size of 8. The next three statements control the placement of the check mark.

Adding Code to the Second Font Size Submenu Item

Now access the click event for the second menu item in the Font Size submenu (the menu item that sets the font size to 10) and modify the code that is automatically generated as shown below.

 Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, _        ByVal e As System.EventArgs)  Handles ToolStripMenuItem2.Click          txtOutput.Font = New Font("Microsoft Sans Serif", 10)          ToolStripMenuIteml.Checked = False          ToolStripMenuItem2.Checked = True          ToolStripMenuItem3.Checked = False End Sub 

Adding Code to the Third Font Size Submenu Item

Finally, access the click event for the third menu item in the Font Size submenu (the menu item that sets the font size to 12) and modify the code that is automatically generated as shown below.

 Private Sub ToolStripMenuItem3_Click(ByVal sender As System.Object, _        ByVal e As System.EventArgs)  Handles ToolStripMenuItem3.Click          txtOutput.Font = New Font("Microsoft Sans Serif", 12)          ToolStripMenuIteml.Checked = False          ToolStripMenuItem2.Checked = False          ToolStripMenuItem3.Checked = True End Sub 

Adding Code to the about Menu Item

Now let's add the program statements for the last remaining menu item by accessing the click event for the About menu item located under the Help menu. Modify the code that is automatically generated as shown below.

 Private Sub AboutToolStripMenuItem_Click(ByVal sender _        As System.Object, ByVal e As System.EventArgs) _        Handles AboutToolStripMenuItem.Click          MessageBox.Show("This Visual Basic application was created " & _          "by Jerry Lee Ford, Jr.") End Sub 

As you can see, the MessageBox.Show method is executed whenever the player clicks on the About menu item, displaying information about the application and its author.

That's the last of this application's program statements. In the next four chapters, you will learn about the programming statements that make up the Visual Basic programming language. So if there is anything in this project that you had trouble understanding, bookmark it and then come back and look over the example again once you have gotten through Chapters 5 through 8.

Step 5: Testing the Execution of the Lottery Assistant Game

OK. That's it. It's time to test your newest creation. Press F5 and see how it runs. If you run into any errors, go back and check your typing and fix any typos that you may have made. Once you think you have the game running smoothly, share it with friends and ask them to test it out as well.




Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
ISBN: 1592008143
EAN: 2147483647
Year: 2006
Pages: 126

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