BACK TO THE LOTTERY ASSISTANT GAME


Now that you have a basic overview of menu systems, it's time to put that knowledge to work creating this chapter's game project. You will create the Lottery Assistant game using the same five steps that you followed in previous chapters. By the time you have finished creating this game, you will have demonstrated your ability to modify your Visual C++ applications by adding fully functional menu systems to your forms.

Designing the Game

The Lottery Assistant game is played on a single window. Therefore, it has only a single form to 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 Label control where the player specifies how many numbers constitute a full set

Label

lblNumPics

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

Label

lblNumRange

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

Label

lblOutput

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

TextBox

txtFullSet

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

TextBox

txtNumPics

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

TextBox

txtNumRange

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

TextBox

txtOutput

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

MenuStrip

mnuStrip I

Identifies the name of the MenuStrip control that is used to create the game's menu system

Step 1: Creating a New Visual C++ Project

The first step in developing the Lottery Assistant game is to start Visual C++ and open a new project, as detailed next:

  1. If you have not already done so, start up Visual C++ 2005 Express and then click on File, New Project. The New Project dialog box appears.

  2. Select Windows Application template.

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

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

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

Step 2: Creating the User Interface

Next, you must add the controls that make up the game's user interface. To begin, let's review the overall layout of the game user interface, as shown in Figure 4.31.

  1. Begin by adding a MenuStrip control to the form. By default, Visual C++ 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 C++ 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 C++ names these controls TextBox1 to TextBox3.

  4. Finally, add a fourth TextBox control to the form just under the Label4 control. Set the control's Multiline property to true and the Wordwrap property to false. Resize it so that it covers most of the bottom half of the form, as shown in Figure 4.31. By default, Visual C++ assigns this control the name TextBox4.

image from book
Figure 4.31: The interface design for the Lottery Assistant game is complete.

The layout of the Visual C++ 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've just added to the form, you need to modify a few properties that belong to the form. 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

ltaForm

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?

Label2

Name

lblNumPics

 

Text

How many sets of lottery numbers do you want?

Label3

Name

lblNumRange

 

Text

What is the highest number that can be picked?

Label4

Name

lblOutput

 

Text

What are your lottery numbers?

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

txtNumPics

TextBox3

Name

txtNumRange

TextBox4

Name

txtOutput

 

Multiline

true

 

ReadOnly

true

 

ScrollBars

Vertical

 

TabStop

false

 

Wordwrap

false

Setting the ReadOnly properly 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 so that the player can 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 in need of modification is the MenuStrip control. First, 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

HelpToolStripMenuItem

Provides access to additional information about the game

After 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

GetNumbersToolStripMenuItem

Retrieves randomly generated lottery numbers

&Clear Numbers

ClearToolStripMenuItem

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

E&xit

ExitToolStripMenuItem1

Terminates game execution

The Clear Numbers menu item is used to execute programming statements that remove text that might currently be stored in the form's TextBox controls. When the form is first displayed, no text is 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 then 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

BackgroundToolStripMenuItem

Provides access to a submenu where you can change the game's background color

&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, in addition to menu items that reside underneath them. However, you are not done yet. You need to set up both the Background and Font Size menu items to provide access to their own submenus. Table 4.9 outlines the contents of the Background submenu. Table 4.10 outlines the contents of the Font Size 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

GrayToolStripMenuItem

Sets the form's background color to gray

Table 4.10: Menu Items Residing on the Font Size Submenu

Text Property

Resulting Menu Name

Description

8

ToolStripMenuItem1

Sets the font size displayed in the txtOutput control to 8

10

ToolStripMenuItem2

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 shortcut key F1 to the Get Numbers menu item located under the File menu by selecting the menu item and setting the ShortcutKeys property to F1. Then add the shortcut 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. 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's 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, no Button controls are available 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 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 C++ automatically opens the Code Editor and creates a couple of lines of initial code for you. So, first double-click on the Get Numbers menu item located under the File menu. The following code is generated automatically and displayed in the Code Editor.

 private: System::Void getNumbersToolStripMenuItem_Click(           System::Object^  sender, System::EventArgs^  e)          {          } 

Type in the source code for the Get Numbers menu item by starting with the following statements. These statements define variables and an array that the application uses to store and manipulate the data it needs to execute. For now, key in these statements exactly as shown. In Chapter 5, "Storing and Retrieving Data in Memory," you will learn all about variables and arrays.

 Double dblInputTest = 0;     //Used to test input const Int16 cMinInSet = 3,   //Set range              cMaxInSet = 10,              cMinNumPics = 1,      //Number of sets              cMaxNumPics = 10,              cMinNumRange = 1,     //Range of picks              cMaxNumRange = 50: 

Next add the following statements, which check to see if the player has supplied valid input into the first TextBox control and display an error message if this is not the case. Take note of the return statement, which immediately forces the function to exit when encountered. This prevents Visual C++ from processing any of the remaining statements associated with the Get Numbers menu item click event.

 //Confirm that full set is a proper entry if( !Double::TryParse( txtFullSet->Text,     dblInputTest ) ||     !(dblInputTest >= cMinInSet &&     dblInputTest <= cMaxInSet) ) {   MessageBox::Show( String::Concat( "You must enter"   " a number between ", cMinInSet.ToString(),   " and ", cMaxInSet.ToString(), " for the full set." ) );   return; } 

Trick 

The Double::TryParse method is one of the most robust means for checking to see if a text string contains a numeric value. Although you can use other means, most require special error handling techniques if they encounter data outside of a certain range. You can use Double::TryParse, however, to examine a string containing any combination of letters and numbers.

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

 //Confirm that number of picks is a proper entry if( !Double::TryParse( txtNumPics->Text, dblInputTest )     || !(dblInputTest >= cMinNumPics &&     dblInputTest <= cMaxNumPics) ) {   MessageBox::Show( String::Concat( "You must enter"   " a number between ", cMinNumPics.ToString(),   " and ", cMaxNumPics.ToString(), " for the "   "number of sets you want." ) );   return; } 

The next set of statements ensures that the third TextBox control has the appropriate values. This includes confirming that the range of numbers is within minimum and maximum bounds and that the range of numbers to generate is greater than the number of picks.

 //Confirm that range is a proper entry if( !Double::TryParse( txtNumRange->Text, dblInputTest )     || !(dblInputTest > cMinNumRange &&     dblInputTest <= cMaxNumRange) ) {   MessageBox::Show( String::Concat( "You must enter"   " a number greater than ", cMinNumRange.ToString(),   " and less than ", cMaxNumRange.ToString(), " for"   " the range of numbers." ) );   return; } 

Trap 

Be certain that any text string you send to the Int32:: Parse method contains an integer value. If not, your program will crash without special error handling techniques.

 //Confirm that range is greater than number within a set if( Int16::Parse( txtNumRange->Text ) <   Int16::Parse( txtFullSet->Text ) ) {   MessageBox::Show( "You must enter a range "   "of numbers that is greater than the number "   "of picks in order to be able to generate "   "one unique number for each pick." );   return; } 

Now add the following statements, which create a series of randomly generated numbers by accessing the computer's current time:

 //Create random numbers based on current time DateTime moment = DateTime::Now; Random^ randNumGen = gcnew Random( moment.Millisecond ); 

Next, add the following statements. These statements include for loops and a do loop, which you will learn more about in Chapter 7, "Processing Lots of Data with Loops."

Although somewhat complicated, you can follow the basic flow of this block of code by reading the comments. First, the code creates a list that holds a set of lottery number picks. This allows for the checking of duplicates. Then the code creates a for loop, which causes the entire process of creating lottery numbers and checking for duplicates to happen again and again until the program has created all the lottery numbers that the user desires.

 //Create a list that will hold the picks //  and allow checks for duplicates Int16 iLotteryArray[cMaxInSet]; //Generate all random numbers Int16 numPics = Int16::Parse(txtNumPics->Text); for( Int16 iNumSetCntr = 0;    iNumSetCntr < numPics;    iNumSetCntr++ ) {    //Clear the list of picks    Int16 iCurPickCntr;    for( iCurPickCntr = 0; iCurPickCntr < cMaxInSet;       iCurPickCntr++ )       iLotteryArray[iCurPickCntr] = 0;    //Generate the list    iCurPickCntr = 0;    Boolean bPickDuplicate;    do    {      bPickDuplicate = false;      //Get a possible lottery value      iLotteryArray[iCurPickCntr] = cMinNumRange +      randNumGen->Next()      % (Int16::Parse( txtNumRange->Text) -      cMinNumRange );      //Check to see if the pick is duplicated      for( Int16 iDupCntr = 0; iDupCntr < iCurPickCntr;         iDupCntr++ )      {        if( iLotteryArray[iDupCntr] ==          iLotteryArray[iCurPickCntr] )        {          bPickDuplicate = true;          break;        }      }      //If the number is a duplicate, try again      if( bPickDuplicate == true )        continue;      //The number is not a duplicate; output      //  and move to next      txtOutput->Text = String::Concat(      txtOutput->Text, Convert::ToString(      iLotteryArrayEiCurPickCntrl ), "t" );      iCurPickCntr++;    } while( iCurPickCntr <            Int16::Parse( txtFullSet->Text) );    txtOutput->Text = String::Concat(    txtOutput->Text, "rrnrrn" ); } 

Don't worry if this example is difficult to follow. The specifics of the programming logic are covered in upcoming chapters. The last program statements to add to the code that executes in response to the Get Numbers menu item's click event are shown next:

 getNumbersToolStripMenuItem->Enabled = false; clearNumberToolStripMenuItem->Enabled = true; 

These 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 Design view and double-click on the Clear Numbers menu item. Visual C++ generates the following code:

 private: System::Void clearNumberToolStripMenuItem_Click(           System::Object^  sender, System::EventArgs^  e)       {       } 

Add these statements to the Clear Numbers menu click event. 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 = ""; txtNumPics->Text = ""; txtNumRange->Text = ""; txtOutput->Text = ""; txtFullSet->Focus(); getNumbersToolStripMenuItem->Enabled = true; 

Adding Code to the Exit Menu Item

Now return to the Design view and double-click on the Exit menu item located under the File menu. The code to add to this function is straightforward. Simply add the programming statement this->C1ose(), which tells the application to shut down all windows and quit.

 private: System::Void exitToolStripMenuItem_Click(System::Object^           sender, System::EventArgs^ e)       {         this->Close();       } 

Adding Code to the White Menu Item

Now it's 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 modifying the code that is generated automatically, as shown here:

 private: System::Void whiteToolStripMenuItem_C1ick(System::Object^           sender, System::EventArgs^  e)       {         this->BackColor = Color::White;         whiteToolStripMenuItem->Checked = true;         yellowToolStripMenuItem->Checked = false;         grayToolStripMenuItem->Checked = false;       } 

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 ensure 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 generated automatically, as shown here:

 private: System::Void yellowToolStripMenuItem_Click(System::Object^           sender, System::EventArgs"  e)       {         this->BackColor = Color::Yellow;         whiteToolStripMenuItem->Checked = false;         yellowToolStripMenuItem->Checked = true;         grayToolStripMenuItem->Checked = false;       } 

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 Cray Menu Item

Now access the click event for the Gray menu item and modify the code that is generated automatically, as shown here:

 private: System::Void grayToolStripMenuItem_Click(System::Object^           sender, System::EventArgs^  e)       {         this->BackColor = Color::Gray;         whiteToolStripMenuItem->Checked = false;         yellowToolStripMenuItem->Checked = false;         grayToolStripMenuItem->Checked = true;       } 

Adding Code to the First Font Size Submenu Item

Now let's add the code that executes 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 Size submenu (the menu item that sets the font size to 8) and modify the code that is generated automatically, as shown here:

 private: System::Void toolStripMenuItem2_Click(System::Object^           sender, System::EventArgs^  e)       {         this->txtOutput->Font = gcnew Drawing::Font(L"Arial", 8.25F );         toolStripMenuItem2->Checked = true;         toolStripMenuItem3->Checked = false;         toolStripMenuItem4->Checked = false;       } 

As you can see, the first statement that you added sets the Font property of the txtOutput control to Arial and specifies a font size of 8.25. 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 generated automatically, as shown here:

 private: System::Void toolStripMenuItern3_Click(System::Object^           sender, System::EventArgs^  e)       {         this->txtOutput->Font = gcnew Drawing::Font(L"Arial", 10.OF );         toolStripMenuItem2->Checked = false;         toolStripMenuItem3->Checked = true;         toolStripMenuItem4->Checked = false;       } 

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 generated automatically, as shown here:

 private: System::Void toolStripMenuItem4_Click(System::Object^           sender, System::EventArgs^ e)       {         this->txtOutput->Font = gcnew Drawing::Font(L"Arial", 12.OF );         toolStripMenuItem2->Checked = false;         toolStripMenuItem3->Checked = false;         toolStripMenuItem4->Checked = true;       } 

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 generated automatically, as shown here:

 private: System::Void aboutToolStripMenuItem_Click(System::Object^           sender, System::EventArgs^ e)       {         MessageBox::Show( "This Visual C++ application was"         "created by Aaron Miller" );       } 

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. (However, you can feel free to change the name.)

That's it. In the next four chapters, you will gain a better understanding of the programming statements that make up the Visual C++ programming language. If there is anything in this project that you had trouble understanding, bookmark it and then come back and look over the example again after you have gotten through Chapters 5 through 8.

Step 5: Testing the Execution of the Lottery Assistant Game

Okay. Now it's time to see if your application works. 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 might have made. When you think you have the game running smoothly, share it with friends and ask them to test it.




Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
ISBN: 735615381
EAN: N/A
Year: 2005
Pages: 131

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