Now, let's return our attention to this chapter's game project. You will create the Speed Typing game by following the same five steps that you have used to complete previous chapter projects. By the time you are done creating the Speed Typing game, you will have demonstrated your ability to implement many of the advanced design techniques that you learned about in this chapter.
The Speed Typing game is played on a single window, comprised of one form and the 11 controls listed in Table 3.10.
Control Type | Control Name | Description |
---|---|---|
Label | lblInstructions | Displays the game's instructions |
Label | lblSourceText | Identifies the Textbox field that displays the source text that the player is to copy |
Label | lblEntryText | Identifies the Textbox field where the player is to type game input |
Textbox | txtDisplay | Name of the Textbox control where the game's source text string will be displayed |
Textbox | txtEntry | Name of the Textbox control where the player will type game input |
Button | btnGo | Name of the Button control that the player will click on to start the game |
Button | btnDone | Name of the Button control that the player will click on to tell the game to check the player's game input |
Button | btnExit | Name of the Button control that the player will click on to end the game |
Timer | tmrControl | Name of the Timer control that controls the length of game play |
ToolTip | tipControl | Name of the ToolTip control that allows the game to display ToolTip messages |
StatusBar | stbControl | Name of the StatusBar control used to display informational messages as the game runs |
The first step in developing the Speed Typing game is to start Visual Basic and open a new project using the following procedure:
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.
Select Windows Application template.
Type Speed Typing as the name of your new application in the Name field located at the bottom of the New Project window.
Click on OK to close the New Project dialog.
Now, let's begin by adding all the controls required to put together the game's interface. Figure 3.27 shows the overall layout of the game's interface.
Figure 3.27: Completing the interface design for the Speed Typing game.
The following procedure outlines the steps involved in setting up the application's graphical user interface.
Add the ToolTip control to your form. By default, Visual Basic assigns the control a default name of ToolTip1. It will be displayed at the bottom of the form designer windows in a component tray.
Add the Timer control to your form. By default it is assigned a name of Timer1 and will also be displayed in the component tray.
Add a TextBox to the form. Its default name is TextBox1. Set its Multiline property equal to True and expand and reposition it right in the middle of the form, as shown in Figure 3.27.
Add a second TextBox to the form. Its default name is TextBox2. Set its Multiline property equal to True and expand and reposition it under the previous TextBox control, as shown in Figure 3.27.
Add a Label control to the upper left-hand corner of the form. Its default name is Label1.
Add a second Label control to the form just above the first TextBox control. Its default name is Label2.
Add a third Label control to the form just above the second TextBox. Its default name is Label3.
Add a Button control to the lower left-hand corner of the form. Its default name is Button1.
Add a second Button control to the lower right-hand side of the form. Its default name is Button2.
Add a third Button control to the upper right-hand corner of the form. Its default name is Button3.
Add a StatusBar control to your form. Its default name is StatusBar1.
The next step in completing the Speed Typing game is to customize properties associated with the form and the controls that you have added to it. Once this is done, you'll be ready to begin adding the program statements that will make the controls perform their required tasks.
Up to this point In the book, I have used the default names that Visual Basic has been assigning to controls. However, going forward, I am going to start implementing a naming convention to the controls and other programming elements within the chapter game projects. Naming conventions help to make program code easier to read and understand.
Before I explain the naming convention that I plan to follow going forward, you need to know about a few rules that Visual Basic strictly enforces regarding object names and programming elements. These rules include:
Names must begin with either an alphabetic character or the underscore character (_).
Names can only consist of alphabetic characters, numbers, and the underscore character (_).
Names cannot match Visual Basic keywords.
When coming up with names to assign to controls, variables, and other objects in your applications, use a consistent naming scheme. For example, from this point forward, I'LL try to use words that are descriptive and that help to identify what an element is. Also, I'LL follow a consistent approach when creating names. For starters, I'LL employ camelCase spelling. Using camelCase, you use one or more words or abbreviations to generate element names. The first word or abbreviation begins with a Lowercase character, and the first Letter of all remaining words or abbreviations is spelled with an uppercase character.
Working with the default names that Visual Basic assigned to form controls can be difficult, especially if you add a Lot of controls to a form. Instead, I'LL assign a descriptive name to form elements that describes their function. For example, I might assign a name of btnExit to a button that is responsible for exiting an application when clicked. Similarly, I might assign a name of txtInputName to a Textbox control intended to collect a user's name or txtInputAge to a Textbox intended to collect a user's age.
Let's begin customizing the form and the controls that you have added to it. Let's begin by modifying the Form1, changing the properties listed in Table 3.11.
Property | Value |
---|---|
FormBorderStyle | FixedSingle |
StartPosition | CenterScreen |
Text | Speed Typing |
Next, change the name property of the ToolTip control to tipControl. Then change the Name property of the Timer control to tmrControl and set its Interval property to 1000.
Now, modify the properties belonging to the two TextBox controls as shown in Table 3.12.
Control | Property | Value |
---|---|---|
TextBox1 | Name | txtDisplay |
ReadOnly | True | |
ToolTip | Displays source text String | |
TextBox2 | Name | txtEntry |
ReadOnly | True | |
ToolTip | Type your text here |
Modify the properties belonging to the three Label controls as shown in Table 3.13.
Control | Property | Value |
---|---|---|
Label1 | Name | lblInstructions |
Text | Instructions: Click on Go to begin. you will have 15 seconds to type the text displayed in the Source Text field into the Enter Text Here field exactly as shown. | |
Label2 | Name | lblSourceText |
Text | Source Text: | |
Label3 | Name | lblEntryText |
Text | Enter Text Here: |
Modify the properties belonging to the three Button controls as shown in Table 3.14.
Control | Property | Value |
---|---|---|
Button1 | Name | btnGo |
Text | Go | |
ToolTip | Display new text string | |
Button2 | Name | btnDone |
Text | Done | |
ToolTip | Check typing | |
Button3 | Name | btnExit |
Text | Exit | |
ToolTip | Exit game |
Finally, add a StatusBar control to your form, change its Name property to stbControl and clear out the default text stored in its Text property. These are all the control property modifications that are required for the Speed Typing game.
Now it is time to start writing code. To make the Speed Typing game work, you are going to need to add code to five places, including the btnGo, btnDone, btnExit, and tmrControl controls. In addition, you'll need to add a few lines of code to define a few variables.
Trap | Because we haven't starting dissecting the statements that make up the Visual Basic programming language yet, you may not be able to understand everything that you'll see. So as with the previous two chapters, just key in what you see and follow along. We'll begin covering Visual Basic Language elements in Chapter 5, "Storing and Retrieving Data in Memory," and by Chapter 8, "Enhancing Code Structure and Organization," you should be able to return to this chapter and fully understand all the details of the Speed Typing game. |
For starters, double-click on the Code View icon in the Solution Explorer. The code editor will appear. The following two lines of code will already be displayed.
Public Class Form1 End Class
Add the following three statements between these two lines of code as shown below.
Public Class Form1 Dim intWrong As Integer = 0 Dim intCount As Integer = 0 Dim intTimer As Integer = 0 End Class
These three statements define the variables that the game will use to track the number of strikes made by the player, the number of tries the player has made, and amount of time that has elapsed for each turn.
Next, switch back to the form designer and then double-click on the btnGo button. This will switch you back to the code editor, where the following new code will have been added.
Private Sub btnGo_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnGo.Click End Sub
This code identifies the beginning and ending of the program statements that execute when the user clicks on the btnGo button. Modify this portion of your application by adding the programming statements shown below in between these two statements.
Private Sub btnGo_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnGo.Click If intCount = 0 Then txtDisplay.Text = _ "Once upon a time there were three little pigs." If intCount = 1 Then txtDisplay.Text = _ "In days gone by times were hard but the people were strong." If intCount = 2 Then txtDisplay.Text = _ "Once in a while something special happens even to the " _ & "worst of people." If intCount = 3 Then txtDisplay.Text = _ "When injustice rears its head, it is the duty of all good " _ & "citizens to object." If intCount = 4 Then txtDisplay.Text _ "It has been said that in the end there can be only one. " _ & "Let that one be Mighty Molly." btnDone.Enabled = True btnGo.Enabled = False txtEntry.ReadOnly = False tmrControl.Enabled = True intTimer = 0 txtEntry.Focus() End Sub
The first five statements check to see what turn the game is currently executing (0 – 4) and displays the appropriate text in the txtDisplay control. For example, if this is the player's first turn then "Once upon a time there were three little pigs" will be displayed.
The next two statements enable the btnDone button and disable the btnGo button. Next, the txtEntry control's ReadOnly property is set equal to True in order to allow the player to begin typing text into it. Then the tmrControl is enabled and the value of intTimer is set equal to 0. This begins the 15-second countdown sequence. Finally, the cursor is automatically placed in the txtEntry field using the control's Focus() method.
Trick | The Focus method provides the ability to programmatically specify which control you wish to receive focus. |
Return to the form designer windows and double-click on the btnDone button. This switches you back to the code editor, where code for the btnDone control's click event has been added, as shown below.
Private Sub btnDone_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDone.Click End Sub
Add the following statements between these two statements:
stbControl.Text = "" tmrControl.Enabled = False
The first statement clears out any text that might be displayed in the StatusBar. The second statement disables the game's Timer control so that it won't keep counting and eventually declare a strike at 15 seconds.
Next, add the following statements just beneath the previous statements.
If txtEntry.Text = "" Then MessageBox.Show("Error: You must enter something!") txtEntry.Text = "" txtDisplay.Text = "" btnDone.Enabled = False btnGo.Enabled = True txtEntry.ReadOnly = True intTimer = 0 btnGo.Focus() Return End If
This set of statements checks to make sure that the player has typed something into the txtEntry field. If the user has not typed anything, the indented statements contained within the opening If and closing End If statements will execute, displaying an error message and resetting all the controls back to their initial settings. Note the use of the Return statement in the preceding group of statements. The Return statement tells Visual Basic to stop processing any of the remaining statements in the btnDone control's click event. This is appropriate because there is no point to performing any further processing if the player has not typed anything.
Next, add the following statement just beneath the previous statements.
If txtEntry.Text = txtDisplay.Text Then MessageBox.Show("Match - You typed in the string correctly!") intCount = intCount + 1 intTimer = 0 Else MessageBox.Show("Strike " & intWrong + 1 _ & " - You made at least one typo.") intWrong = intWrong + 1 intTimer = 0 End If
These statements check to see if the text typed by the player exactly matches the text displayed by the game. In other words, does the text string currently stored in the txtEntry control match the text string stored in the txtDisplay control? If there is a match, the MessageBox.Show method is used to inform the player, and the game adds 1 to the number of turns of levels the player has completed and resets the variable used by the timer control (to track the number of seconds that a turn has lasted) back to 0. However, if the text stored in the two controls does not match, an error message is displayed, and the game adds 1 to the number of strikes made by the player before resetting the intTimer variable back to 0.
Now add the following statements just beneath the previous statements.
txtEntry.Text = "" txtDisplay.Text = "" btnDone.Enabled = False btnGo.Enabled = True txtEntry.ReadOnly = True btnGo.Focus()
These statements reset the form's controls back to their default settings and sets the focus back to the btnGo control, in order to prepare the game for the player's next attempt.
Add the following statements just beneath the previous statements.
If intWrong = 3 Then If intCount < 2 Then MessageBox.Show("Game over. Your typing skill level " _ & "is: Beginner. Please play again!") intCount = 0 intWrong = 0 Return End If If intCount < 4 Then MessageBox.Show("Game over. Your typing skill level " _ & "is: Intermediate. Please play again!") intCount = 0 intWrong = 0 Return End If If intCount < 5 Then MessageBox.Show("Game over. Your typing skill level " _ & "is: Advanced. Please play again!") intCount = 0 intWrong = 0 Return End If End If If intCount < 5 Then MessageBox.Show("Game over. Your typing skill level "_ & "is: Advanced. Please play again!") intCount = 0 intWrong = 0 End If
Each time the player clicks on the btnDone button, the game checks to see if the player has struck out or if all five levels have been completed. These statements are responsible for determining whether or not the player won the game and for assigning the player's typing skill level. If the player got three strikes, the game assigns a skill level rating of beginner, if the player was only able to complete the first level of the game. If the player managed to complete the second or third level, a skill level of intermediate is assigned. If the player manages to complete four levels, a skill level of advanced is assigned. Finally, if the player manages to complete all five levels, a skill level of expert is assigned.
Now its time to add code to the btnExit control as shown below.
Private Sub btnExit_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExit.Click Application.Exit() End Sub
The last control that you need to provide code for is the game's Timer control. Switch back to the form designer and then double-click on the tmrControl control. This will switch you back to the code editor where the following new code will have been added.
Private Sub Timer1_Tick(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles tmrControl.Tick End Sub
Modify this section of your application by adding the following statements inside these two statements.
intTimer = intTimer + 1 stbControl.Text = "Seconds remaining: " & (15 - intTimer) If intTimer = 15 Then intWrong = intWrong + 1 tmrControl.Enabled = False stbControl.Text = "" MessageBox.Show("Strike " & intWrong & " - Time is up. " _ & "Please try again.") txtEntry.Text = "" txtDisplay.Text = "" btnDone.Enabled = False btnGo.Enabled = True txtEntry.ReadOnly = True btnGo.Focus() If intWrong = 3 Then If intCount < 2 Then MessageBox.Show("Game over. Your typing skill " _ & "level is: Beginner. Please play again!") intCount = 0 intWrong = 0 Return End If If intCount < 4 Then MessageBox.Show("Game over. Your typing skill " _ & "level is: Intermediate. Please play again!") intCount = 0 intWrong = 0 Return End If If intCount < 5 Then MessageBox.Show("Game over. Your typing skill " _ & "level is: Advanced. Please play again!") intCount = 0 intWrong = 0 Return End If End If If intCount = 5 Then MessageBox.Show("Game complete. Your typing skill " _ & "level is: Expert. Please play again!") intCount = 0 intWrong = 0 End If End If
The first statement adds 1 to the variable used by the Timer control to track the number of seconds that the current play has lasted. The second statement displays this information in the status bar located at the bottom of the window. The Timer control automatically executes every second. In its third statement, it checks to see if the 15 seconds have passed. If this is the case, it declares a strike by adding 1 to the variable used to track the number of failed attempts. The Timer control then disables itself, clears out any text displayed on the status bar, and uses the MessageBox.Show method to tell the player that time has expired.
The rest of the code that you added to the tmrControl control's click event checks to see if the game is over and assigns a skill level to the player using the same logic that you previously added to the btnDone control's click event.
OK. That's it. The Speed Typing game should be ready to go. Press F5 to give it a try. If any errors occur, go back and double-check the code statements that you added to make sure that you did not make any typos.