BACK TO THE CLICK RACE GAME


In the Click Race game, the player is required to click as quickly as possible on two buttons to score points. The game creates pressure by limiting the amount of time the player can click to a 30-second period. And because clicking a single button would be too easy, the game requires the player to alternate between the left and right button when clicking. As a result, the player not only must be quick with the mouse, but accurate with his aim when it conies to clicking on a button.

Designing the Game

The game is composed of a single window, given by the form, and six controls added to the form. The form controls are summarized in Table 2.2.

Table 2.2: Form Controls for the Click Race Game

Control

Description

TextBox1

Text box that displays the number of valid mouse clicks

Label1

Descriptive label for the text box

Button1

One of two game buttons

Button2

One of two game buttons

Button3

Button used to start game play

Button4

Button used to close the game

Timer1

Timer control used to control the length of a game

Step 1: Creating a New Visual C++ Project

To create the Click Race game, you must first create a new project. The steps for doing so are short and easy.

  1. If you have not already done so, launch Visual C++ 2005 Express Edition.

  2. When the IDE appears displaying the Start page, select File and then New Project. The New Project dialog box appears.

  3. In the Project Types section, make sure that CLR is highlighted. (It should be by default.)

  4. Under Templates, select Windows Forms Application. This instructs the IDE to provide your project with the access to the forms and controls you need to create a Windows application.

  5. Type The Click Race Game as the name of your new application in the Name field located near the bottom of the New Project window.

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

When you complete these steps, the Visual C++ IDE places you in the Design view of your new project. You should see a blank form ready for controls to be added to it.

Step 2: Creating the User Interface

Now let's add the necessary controls that make up the Click Race game's interface. Figure 2.21 shows all the controls you will be using.

  1. Start by adding a text box to the upper middle of the form, as shown in Figure 2.21.

  2. Next, add a label and position it above the text box. Visual C++ automatically names the label Label1.

  3. Add the first button to the left side of the form. Visual C++ assigns it the name Button1.

  4. Add the second button to the right side of the form, as shown in Figure 2.21. It has the default name of Button2.

    Trap 

    Be careful not to mix the buttons up. When you begin adding code to control the behavior of the application based on button clicks, you will need to add it to the right button. If you get confused about the name of any control, select it and look under Properties for the (Name) field. The value to its right will be the name used to refer to the component in code.

  5. Add the third button centered near the bottom form. Visual C++ assigns it the name Button3.

  6. Add a fourth button just beneath the third button. This button appears with the label Button4.

  7. Add a Timer control to your form. This control does not appear on your form, but rather in the Component Tray. By default, it is named timer1.

image from book
Figure 2.21: The design view of the Click Race game's interface.

You have now successfully built the interface for the Click Race game. Your result should look something like that shown in Figure 2.21. (Don't worry if your elements are not lined up exactly right.)

Step 3: Customizing Form and Control Properties

The first step in customizing the Click Race game is to get the game to display its title when you run it. This involves changing a single value, but you must bring up the Properties window for the form. To do this, click anywhere on the form except where you have placed the controls. When the Properties window appears, locate the Text field that appears under the Appearance category (or under T if you are viewing the list alphabetically, as was mentioned earlier in this chapter in the section "Understanding How to Use the Properties Window"). The default value is Form1. Replace this with The Click Race Game.

Trap 

Make certain that you edit the Text property and not the (Name) property beneath the Design category, which also displays the value Form1. The Name property is associated with code (and won't accept spaces anyway).

Now let's move on to modifying the individual controls you've added. The first control that you must modify is the TextBox1 control. Table 2.3 shows the properties that need to be modified and their corresponding value.

Table 2.3: Property Changes for the TextBox1 Control

Property

Value

BackColor

Info

ForeColor

HotTrack (on the System tab)

ReadOnly

True

Font

Arial

Font

Regular

Font

Size 14

Size

132,29

Next, bring up the Properties window for the Label1 control by clicking on it. Table 2.4 shows the changes you need to make.

Table 2.4: Property Changes for the Label1 Control

Property

Value

Font

Arial

Font

Bold

Font

Size 12

Text

Number of Clicks

You're almost done. For Button1, Button2, Button3, and Button4, consult Table 2.5 to see what values to set the button properties to.

Table 2.5: Property Changes for the Button Controls

Button Name

Property

Value

Button1

Text

Click Me!

Font

Arial

Font

Regular

Font

Size 9

Button2

Text

Click Me!

Font

Arial

Font

Regular

Font

Size 9

Button3

Text

Start Game

Font

Arial

Font

Regular

Font

Size 9

Button4

Text

Exit

Font

Arial

Font

Regular

Font

Size 9

You need to modify one more control. timer1, which appears in the Component Tray, must have its Interval property changed. By default, Interval is 100. This value represents the delay, in milliseconds, before the Timer control registers that a single interval has passed. Intervals are simply a means of grouping milliseconds into blocks of time so that you can count them easily. You can set the interval to 1, in which case the timer's interval would represent a single millisecond. Or you can group them by thousands, in which case each interval represents a single second. Because we want the player to be able to play for only 30 seconds, it would be more convenient if each timer interval were the equivalent of a single second. So let's change the value to 1000, as illustrated in Table 2.6.

Table 2.6: Property Changs for the Timer1 Control

Property

Value

Interval

1000

You've now made all the property modifications required for the Click Race game.

Step 4: Adding a Little Programming Logic

Now you are ready to move on to controlling the application's behavior by adding code. Start by double-clicking anywhere on the game's form (but not on the controls you've added). Visual C++ automatically places you in a section of code that it generates, as shown in the next listing. Actually, you will see a slight difference between the listing here and what is displayed in the IDE. At the end of the first line is a backslash character. In the C++ language, this is the way you indicate that two lines of code belong together. Here the backslash is used to make the code a bit easier to read. Beyond that minor change, however, the code should be the same.

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

If you scroll above this block of code, you will see that Visual C++ generates a lot of code to drive your application. Unfortunately, much of it will likely not make sense at this stage. Rest assured, though, that you don't need to understand everything that's happening to write a working program.

What is important to understand is that the code you see manages the way your application behaves when it runs. Much of the code handles initializing your application and configuring the resources it needs. For instance, you will see references to the values you've entered in the Properties window, such as the names of the buttons or the font they use. In later chapters, you will come to have a better grasp of why Visual C++ creates what you see, but for now, try to focus on adding the code for the Click Race game where it is needed.

Trap 

The code that Visual C++ generated is grouped into labeled blocks. It is important not to delete or change the values of what you see in these blocks. If you do so, your application might stop working.

The code that you will be adding allows for three things. First, it allows the player to start and end the game. You will also add statements that keep track of the number of clicks and display them to the player. Finally, you will add code that manages the timer.

The majority of what you will be doing is adding C++ statements to create regions of code known as functions. These functions are created automatically when you double-click on the form or one of its controls. There is a wide variety of functions and many details associated with them, which we'll cover in Chapter 8, but you only need to concentrate on adding the statements to each function, as specified.

Hint 

Functions are regions of code that are designed to perform a specific task, such as responding to events generated when a user clicks on one of an application's form controls.

Let's get started. The first step is to add the statements that will keep track of the number of times the two buttons have been clicked and the length of time the player has been playing the game. Locate the section of code displayed in the next listing. This section is reserved for form variables, which are C++ statements that store information. (You'll learn more about form variables in the coming chapters.) Add the lines in bold to your code.

 private:   /// <summary>   /// Required designer variable.   /// </summary>   Int16 intClickCounter;  // Stores number of clicks   Int16 intTimerCounter;  // Stores timer value 

Trick 

The text that appears after two slashes is called a comment. Comments are text descriptions of how certain program statements function in your application. Visual C++ ignores everything after the two slashes, so you can type whatever you want. Comments are not required, but they're one of the marks of a professional programmer, and you should get used to adding them. The details on good commenting are covered in later chapters.

Next, you want to guarantee that the values that control the behavior of the Click Race game are set a certain way as soon as the player launches the application. When the player first plays, both of the buttons on the left and right sides of the form should be disabled (grayed out). The timer should be set to 0, as should the number of clicks. To do this, add the following code to the Form1_Load function:

 private: System::Void Form1_Load(System::Object^ sender,           System::EventArgs^  e) {         // Initialize game's starting values         intClickCounter = 0;         intTimerCounter = 0;         button1->Enabled = false;         button2->Enabled = false; 

Now click on the Form1.h [Design] tab to return to the Design view. Double-click on Button1. Just as when you double-clicked on the form, this action causes Visual C++ to generate a function associated with handling Button1, called button1_Click. Here your application defines what happens when the player clicks on the game's left button. Type the statements shown in bold in the next listing. This code performs four steps. First, the statement right beneath the comments describing this block of code increases the counter holding the number of clicks by one. Next, it copies the value of the counter to the Text property of textBox1, which in turn causes it to be displayed to the player. The next statement disables the game's left button. The final statement enables the right button.

 private: System::Void button1 Click(System::Object^ sender,           System::EventArgs^  e) {         // Increment the number of clicks, display them, and         // then disable the left button and enable the right one         intClickCounter++;         textBox1->Text = intClickCounter.ToString();         button1->Enabled = false;         button2->Enabled = true;       } 

The game's right button must perform almost the same steps. Switch back to the Design view by clicking the Form1.h [Design] tab. Double-click on Button2. This action, in turn, switches you back to the Code Editor. Visual C++ has added a function that corresponds to Button2, called button2_Click. Add the statements in bold to control the game's behavior when the player clicks the right game button. As you can see, the first two lines below the comment are identical to what you added under button1_Click. The difference is that this time the left button is enabled and the right button is disabled.

 private: System::Void button2_Click(System::0bject^ sender,           System::EventArgs^  e) {         // Increment the number of clicks, display them, and         // then disable the right button and enable the left one         intClickCounter++;         textBox1->Text = intClickCounter.ToString();         button1->Enabled = true;         button2->Enabled = false;       } 

Next, it is time to control what happens when the player clicks the game's Start button, which is button3 in the code. Switch back to Design view by clicking the Form1.h [Design] tab. Double-click on Button3. Once again, Visual C++ generates code and returns you to the Code Editor. Now you will notice that the cursor has been placed at a new function named button3_Click. You are going to add functionality that is similar to the code you added to the Form1_Load function. The code sets the game's counter and timer values to 0. Although you already did this in the Form1_Load function, doing it here ensures that the timer count and number of clicks are not carried over from a previous game, but are fresh for each new game. The code also enables the left mouse button and disables the right. Finally, it starts the timer and ensures that textBox1 is cleared for a new game. To give Button3 this functionality, add the code in bold in the next program listing.

 private: System::Void button3_Click(System::0bject^ sender,           System::EventArgs^  e) {         // Start the game by making sure the timer and counters         // are at 0, the left button is enabled, and the         // right button is disabled         intClickCounter = 0;         intTimerCounter = 0;         button1->Enabled = true;         button2->Enabled = false;         timer1->Enabled = true; // Begin timer         textBox1->Text = "";    // Clear text box       } 

Now let's control the behavior of the program when the player clicks the Exit button. As before, click on the Form1.h [Design] tab to return to the Design view, and then double-click Button3. You will be switched back to the Code Editor and placed at a new function named button4_Click. You need to add only one statement, which closes the entire application. To do this, add the code in bold, exactly as shown in the next listing.

 private: System::Void button4_Click(System::Object^ sender,           System::EventArgs^ e)  {         // End the application when the user clicks the         // exit button         Close();       } 

The final step to complete the game is to add code that controls the behavior of the timer. Click on the Form1.h [Design] tab to return to the Design view, and then double-click on the timer1 control. You are taken back to the Code Editor, where Visual C++ has added the timer1_Tick function to your application. You want the code associated with the timer to increment its counter each interval, which is also known as a timer tick. Recall that you earlier defined a tick as 1 second in the Properties window of the timer1 control. Now you will add code that is activated once per second. The code adds 1 to the timer's count and tests the final result to see if it equals 30. If the timer counter reaches 30, both game buttons are disabled, thus ending the game. To make this happen, add the bold statements in the next listing.

 private: System::Void timer1_Tick(System::Object^ sender,           System::EventArgs^  e) {         // Update the timer         intTimerCounter++;         if( intTimerCounter == 30 )         {           // If the timer reaches 30, disable           // the buttons           button1->Enabled = false;           button2->Enabled = false;         }       } 

Step 5: Testing the Execution of the Click Race Game

Congratulations! You've just finished building your first complete game! But before you can see the results of all your hard work in action, you need to compile and run the program. To do this, select Build Solution from the Build menu or simply press the F7 key.

In the Output window are the results of your program being compiled. When you're finished, Visual C++ displays the following:

 ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ========== 

If the result instead claims 0 succeeded and 1 or more failed, your program has an error. Any error is probably the result of a typo, so carefully check the code you typed if this occurs. The details of several of the most common errors you might see are covered in Chapter 11, "Debugging Visual C++ Applications."

When you're ready to run the program, select Start Debugging from the Debug menu. Visual C++ launches the program for you automatically. You can then begin testing, which is the final phase to developing any application. In this phase, programmers make sure the program works as intended.




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