Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning REALbasic - From Novice To Professional (2006)

.pdf
Скачиваний:
233
Добавлен:
17.08.2013
Размер:
18.51 Mб
Скачать

176

C H A P T E R 6 M A K I N G D E C I S I O N S W I T H C O N D I T I O N A L L O G I C

Creating a Computer Game

To finish this chapter, you learn how to create a REALbasic computer game called RB Number Guess. This game gives you the chance to apply the material you’ve just read and to reinforce your understanding of conditional logic even further.

Through the development of the RB Number Guess, you learn how to work with the Slider control, which the player uses on each turn to specify a new guess. This application also introduces you to the Random Class and shows you how to use it to generate a random number needed for game play. In addition, you get to work with various mathematical operators and define window properties.

While this chapter demonstrates how to create the RB Number Guess using the Windows version of REALbasic, you can easily adapt the game to work on Macintosh or Linux with only a few minor adjustments to the size and shape of the controls that make up the game’s graphical user interface (GUI). Compiled examples of the application are available on the book’s companion CD-ROM for Mac OS X, Windows, and Linux.

The objective of the game is for the user to guess a randomly generated number in as few guesses as possible. Rather than require the player to key in each guess, this game uses the REALbasic Slider control to collect user input, as Figure 6-3 shows.

Figure 6-3. The RB Number Guess game challenges the user to guess a number between 1 and 100, using the fewest possible number of guesses.

The rest of the game’s GUI is made up of the StaticText, EditField, and GroupBox controls you have already worked with in previous chapters. In addition, the game also has a small menu system, with menu items for terminating game play and displaying information about the game.

C H A P T E R 6 M A K I N G D E C I S I O N S W I T H C O N D I T I O N A L L O G I C

177

Note When executed on Windows, the RB Number Guess game displays a number representing the current location of the Handle on the Slider control. This number dynamically changes as you move the Handle, allowing the player to specify, with precision, their next guess. This behavior is not replicated on Macintosh and Linux, though. Instead, players do not see this value until they have completed their turn and released the Handle. This application highlights an example of the many differences in how things work on Macintosh, Windows, and Linux. You may want to modify the game, so the Slider control is replaced with a EditField and PushButton control, allowing players to key in their guesses instead, when run on Macintosh or Linux. Making this modification gives you the opportunity to work with the #If…#EndIf statement and can help further enhance your appreciation of the types of obstacles that must be overcome when developing cross-platform applications.

Putting Together the Game’s User Interface

The RB Number Guess game is primarily controlled through a Slider control and two PushButton controls. StaticText and EditField controls are used to display output. In addition, a GroupBox control is used to help organize the display of game statistics that are collected and displayed during and after game play.

The first step involved in creating the RB Number Guess game is to create a new REALbasic desktop application. Next, let’s give the application its own icon by opening the Project Editor and setting the Icon property for App to 123.bmp. You can find a copy of this bitmap file along with the source code for this project on the book’s companion CD.

Note By setting the App item’s Icon property, you change the icon associated with the application, giving it a more professional look. To do so, click the App item’s Icon property. REALbasic responds by displaying the Edit Icon window. Right-click the Image area and select the Add menu item from the context menu that appears. REALbasic then displays an Open dialog, letting you specify the name and location of the desired graphic image. Once selected, click OK to close the Open dialog. The selected graphic now appears in the Edit Icon window. Click OK to close this window and return to the Project Editor.

Next, resize Window1, as specified in Table 6-6. Add a GroupBox control and populate it with four StaticText and four EditField controls. Then, add a Slider control and resize it, so it takes up most of the width of the window. Place two PushButton controls just beneath it and add two StaticText controls, one over each end of the Slider control. Finally, add a EditField Control and a StaticText control just over the top center location of the Slider control. When done, your new application’s interface should look just like the example shown in Figure 6-3.

178

C H A P T E R 6 M A K I N G D E C I S I O N S W I T H C O N D I T I O N A L L O G I C

Once you add all the required controls, modify the property values for the window and its controls, as Table 6-6 specifies.

Table 6-6. Property Modifications for the RB Number Guess Application

Object

Property

Value

Window1

Title

RB Number Guess

 

Width

471

 

Height

292

EditField1

Name

edfGamesPlayed

 

ReadOnly

True

 

Text

0

EditField2

Name

edfAvgNoOfTurns

 

ReadOnly

True

 

Text

0

EditField3

Name

edfNoOfGuesses

 

ReadOnly

True

 

Text

0

EditField4

Name

edfAnalysis

 

ReadOnly

True

EditField5

Name

edfDisplay

 

TextFont

System

 

Font.Size

24

 

Font.Bold

True

 

ReadOnly

True

StaticText1

Name

lblGamesPlayed

 

Text

Games Played:

StaticText2

Name

lblAvgNoOfTurns

 

Text

Average # of Turns:

StaticText3

Name

lblNumberOfGuesses

 

Text

No. of Guesses

StaticText4

Name

lblAnalysis

 

Text

Analysis:

C H A P T E R 6 M A K I N G D E C I S I O N S W I T H C O N D I T I O N A L L O G I C

179

Object

Property

Value

StaticText5

Name

lblCurrentGuess

 

Text

Current Guess

StaticText6

Name

lblLowRange

 

Bold

Checked

 

Text

1

StaticText7

Name

lblHighRange

 

Bold

Checked

 

Text

100

GroupBox1

Name

grbStats

 

Caption

Stats:

PushButton1

Name

btnPlay

 

Caption

Play

 

Enabled

False

PushButton2

Name

btnExit

 

Caption

Exit

Slider1

Name

sdrControl

 

Minimum

0

 

Value

0

 

Maximum

100

 

 

 

The next step in setting up the GUI for the RB Number Guess game is to create its menu system. To do so, double-click the MenuBar1 item found on the Project screen. This displays the menu in REALbasic’s MenuBar Editor. By default, REALbasic automatically adds a File and Edit menu for your application. However, because the RB Number Guess game does not have a Edit menu, you should delete the View menu by selecting it and clicking Delete. Next, modify the menu system for MenuBar1, as Table 6-7 outlines.

Table 6-7. Menus and Menu Items for the RB Number Guess Game

Menu

Menu Item

Text Property

File

FileQuit

E&xit

Help

HelpAbout

&About

 

 

 

180

C H A P T E R 6 M A K I N G D E C I S I O N S W I T H C O N D I T I O N A L L O G I C

Because REALbasic automatically takes care of it for you, you needn’t add the FileQuit menu item on the File menu. The user interface for the RB Number Guess game is now complete, as Figure 6-4 shows.

Figure 6-4. The interface layout for the RB Number Guess game

Defining Properties

The RB Number Guess game uses several variables to store and track information needed by the game. These variables are accessed by different parts of the application, so rather than declaring them as local variables, you must set them with a higher-level scope. To accomplish this, set up each of these variables as window properties with a public-level scope. Table 6-8 outlines these properties and their data type.

Table 6-8. Custom Properties Added to the RB Number Guess Game

Property

Data Type Description

intNoGuessed

Integer

Keeps track of the number of guesses made

intSecretNumber

Integer

Stores the game’s randomly generated secret number

intTotalNoOfTurns

Integer

Keeps track of the total number of turns taken

 

 

 

C H A P T E R 6 M A K I N G D E C I S I O N S W I T H C O N D I T I O N A L L O G I C

181

The following procedure outlines the steps involved in declaring each of these properties.

1.Double-click the application’s window to switch over to the Code Editor.

2.Click the Add property button located on the Code Editor toolbar or click Project Add Property.

3.REALbasic responds by displaying a property declaration field at the top of the code pane. Enter intNoGuessed as Integer in the declaration field, as Figure 6-5 shows.

Figure 6-5. Adding a new property to a window

4.Repeat steps 2 through 4 to define the intSecretNumber and intTotalNoOfTurns properties.

Adding a Little Program Code

Once you finish adding the three properties, you are ready to begin writing the code statements needed to make the game work. Begin by switching back to the Window Layout view of the Windows Editor, and then double-click the window. REALbasic responds by opening the Code Editor and displaying the Open event belonging to the window. Enter the following code statements.

182 C H A P T E R 6 M A K I N G D E C I S I O N S W I T H C O N D I T I O N A L L O G I C

Dim r as New Random

'Instantiate a Random Object

intSecretNumber = r.InRange(1,100)

'Generate a random number

The first statement uses the New keyword to instantiate a Random object. The second statement uses the Random class’s InRange method to randomly generate a number from 1 and 100, and to store it in the intSecretNumber property.

Note The Random class is a built-in REALbasic class from which you can instantiate a new object based on that class. Classes and objects have not been covered yet, so for now, just enter these code statements as shown. You learn about classes and objects in Chapter 8.

Together, these two statements generate an initial secret number the player must guess to win the game. Next, switch back to the Window Layout view of the Windows Editor, and then double-click the Slider control. REALbasic responds by opening the ValueChanged Subroutine for the Slider control. Enter the following code statements.

intNoGuessed = intNoGuessed + 1

'Increment variable value by 1

edfNoOfGuesses.Text = CStr(intNoGuessed) 'Display the number of guesses

If sdrControl.Value

= intSecretNumber Then 'Check to see

if the player won

edfAnalysis.Text = "You Win!"

'Update

game

status

 

 

sdrControl.Enabled = False

 

'Disable access

to the

Slider

control

btnPlay.Enabled

= True

'Enable access

to the Play

button

 

'Display the total number of games played edfGamesPlayed.Text = CStr(Val(edfGamesPlayed.Text) + 1)

'Calculate the total number of turns taken since the game was started intTotalNoOfTurns = intTotalNoOfTurns + intNoGuessed

'Calculate the average number of turns per game (as an Integer value) edfAvgNoOfTurns.Text = CStr(intTotalNoOfTurns \ Val(edfGamesPlayed.Text))

End If

C H A P T E R 6 M A K I N G D E C I S I O N S W I T H C O N D I T I O N A L L O G I C

183

If sdrControl.Value < intSecretNumber Then 'See if the player's guess was low

edfAnalysis.Text = "Too Low!"

'Update game status

End If

If sdrControl.Value > intSecretNumber Then 'See if the player's guess was high

edfAnalysis.Text = "Too High!"

'Update game status

End If

'Do not update the display of the Slider control's value when it is zero If sdrControl.Value <> 0 Then

'Display the Slider control's value as the player moves the its handle edfDisplay.Text = Cstr(sdrControl.Value)

End If

Note A subroutine is a collection of programming statements that can be called and executed as a unit. Subroutines are sometimes referred to as procedures.

This subroutine is called whenever the player moves and releases the Slider control’s handle. It begins by incrementing the value of intNoGuessed by 1, and then displays its value in the appropriate EditField, after converting its value to a string data type. Three If…Then blocks are then set up, each of which tests for a different condition.

The first If…Then block executes when the player correctly guesses the game’s secret number (for example, when sdrControl.Value is equal to intSecretNumber). When this occurs, a series of code statements are executed that update the information displayed in the GroupBox control. In addition, the Slider control is disabled to stop game play and the PushButton labeled Play is enabled, allowing the player to start a new game.

The second If…Then block executes when the value specified by the player is less than the game’s secret number. Similarly, the third If…Then block executes when the value specified by the player is higher than the secret number. In both of these cases, a text string is displayed in the EditField control labeled Analysis to provide the player with a clue that guides her next guess.

184

C H A P T E R 6 M A K I N G D E C I S I O N S W I T H C O N D I T I O N A L L O G I C

Tip Take note of the comments embedded throughout this subroutine. By embedding comments into your program code, you help to document it and make it easier to understand.

The way this game is played, the player is permitted to select a number between 1 and 100. However, the Slider control has been set up to allow input between 0 and 100. The reason is to provide the Slider control’s handle a place to rest at the beginning of the game that does not represent a initial value (for example, to enable the user to start playing without have his first move preselected). Because of this set up, it is necessary to prevent the value of 0 from being displayed when the player moves the Slider control’s handle all the way to the left. This is accomplished by adding a If…Then block to the Slider control’s Mouse Move drag event, as the following shows.

'Do not update the display of the Slider control's value when it is zero If sdrControl.Value <> 0 Then

'Display the Slider control's value as the player moves its handle edfDisplay.Text = Cstr(sdrControl.Value)

End If

As you can see, as long as the slider control’s value is not equal to zero, it is displayed. The next set of code statements you need to add to the RB Number Guess games is associated with the PushButton control labeled Play (that is, btnPlay). This code, which the following shows, executes each time the player clicks the play button and, thus, belongs in the PushButton control’s Action event.

'A new game is being started

Dim r as New Random

'Instantiate

a Random Object

 

 

intSecretNumber = r.InRange(1,100)

'Generate

a random

number

 

sdrControl.Enabled

= True

'Enable the Slider

control to allow game

play

sdrControl.Value =

0

 

'By default

the Slider Control's

value is set

to zero

intNoGuessed = 0 'Reset the variable used to track the number of guesses made

edfNoOfGuesses.Text = CStr(intNoGuessed) 'Display the number of guesses made edfDisplay.Text = CStr(sdrControl.Value) 'Display Slider Control's value

edfAnalysis.Text = "" 'Clear out the display of the previous game's status

btnPlay.Enabled = False

'Disable access to the Play button

C H A P T E R 6 M A K I N G D E C I S I O N S W I T H C O N D I T I O N A L L O G I C

185

The first two code statements instantiate a Random object and assign a randomly generated number (with a value between 1 and 100) to the intSecretNumber property. The next two statements enable the Slider control and set its initial value to zero. The property representing the number of guesses made is reset to zero, the rest of the EditField controls are updated and the PushButton control labeled Play is disabled, thus preventing the player from starting a new game until the current game ends.

Next, add the following code statement to the Action event belonging to the PushButton control labeled Exit.

Quit

'Terminate the application's execution

The last of the code to be added to this application supports the display of About information, which the player can access by clicking Help About. To add these statements, you must first add a menu handler to your application by clicking the Add Menu Handler button on the Code Editor. Once this is done, you can enter the two code statements shown in the following.

'Display About Message

MsgBox("RB Number Guess - By Jerry Ford - Copyright 2006")

Testing RB Number Guess

If you have not done so already, go ahead and save your application. Name it RB Number Guess or any other name you prefer. Now, take a little time to test the execution of the game to make sure it works as expected. Figure 6-6 demonstrates how the game looks when it’s being played.

Figure 6-6. Game stats are updated dynamically at the end of each move.

Figure 6-7 shows the pop-up dialog window that appears if you click Help About.