Microsoft WSH and VBScript Programming for the Absolute Beginner Part 24 ppt

10 196 0
Microsoft WSH and VBScript Programming for the Absolute Beginner Part 24 ppt

Đang tải... (xem toàn văn)

Thông tin tài liệu

210 The Guess a Number Game Revisited So far, you have seen examples of small pieces of code that work with functions and sub- routines. Now let’s take a look at how to apply procedures to a larger script. To begin, take a moment to go back and review the Guess a Number game at the end of Chapter 6. This script, like all other scripts earlier in this book, was written without the use of procedures. As I deliberately avoided using procedures in the script from Chapter 6, I had to use other techniques for organizing the script’s programming logic. What I chose to do was put every- thing in the script’s main processing section as follows: • Added statements that generate a random number • Added a Do Until loop that controls the game’s execution • Embedded an If statement within the Do Until loop that ensures that the player typed a number • Embedded a second If statement within the previous If statement that makes sure that the data the player typed was numeric • Embedded three more If statements within the previous If statement to determine whether the player’s guess was low, high, or correct As you can see, I had to embed a lot of statements within one another to organize the script into a workable game. As the script itself was not exceptionally large, this was a manageable task. However, had the script been much larger or more complex, it would have been diffi- cult to keep track of all the embedded logic. Now that you understand what procedures are and what they’re used for, let’s take a moment and go back and redesign the Guess a Number game using them. One way of doing this is as follows: ‘************************************************************************* ‘Script Name: GuessANumber-2.vbs ‘Author: Jerry Ford ‘Created: 11/29/02 ‘Description: This script plays a number-guessing game with the user ‘************************************************************************* ‘Initialization Section Option Explicit Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Const cGreetingMsg = “Pick a number between 1 - 100” Dim intUserNumber, intRandomNo, strOkToEnd, intNoGuesses, strBadData strOkToEnd = “no” intNoGuesses = 0 ‘Main Processing Section RandomNumber() ‘Get the game’s random number PlayTheGame() ‘Start the game WScript.Quit() ‘End the game ‘Procedure Section ‘Generate the game’s random number Function RandomNumber() ‘Generate a random number Randomize intRandomNo = FormatNumber(Int((100 * Rnd) + 1)) End Function ‘Set up a Do Until loop to control the execution of the game Function PlayTheGame() ‘Loop until either the user guesses correctly or the user clicks on ‘Cancel Do Until strOkToEnd = “yes” ‘Prompt user to pick a number intUserNumber = InputBox(“Type your guess:”, cGreetingMsg) intNoGuesses = intNoGuesses + 1 strBadData = “no” 211 Chapter 7 • Using Procedures to Organize Scripts 212 ‘Go see if there is anything wrong with the player’s input ValidateInput() If strOkToEnd <> “yes” Then ‘The player typed in something If strBadData <> “yes” Then ‘The player typed in a number TestAnswer() ‘Let’s see how good the player’s guess was End If End If Loop End Function ‘Determine if there are any problems with the data entered by the player Function ValidateInput() ‘See if the player provided an answer If Len(intUserNumber) = 0 Then MsgBox “You either failed to type a value or you clicked on “ & _ “Cancel.” “Please play again soon!”, , cGreetingMsg strOkToEnd = “yes” Else ‘Make sure that the player typed a number If IsNumeric(intUserNumber) = False Then MsgBox “Sorry. You did not enter a number. Try again.”, , _ cGreetingMsg strBadData = “yes” End If End If End Function Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition ‘Determine if the player’s guess is too low, too high or just right Function TestAnswer() ‘Test to see if the user’s guess was correct If FormatNumber(intUserNumber) = intRandomNo Then MsgBox “Congratulations! You guessed it. The number was “ & _ intUserNumber & “.” & vbCrLf & vbCrLf & “You guessed it “ & _ “in “ & intNoGuesses & “ guesses.”, ,cGreetingMsg strOkToEnd = “yes” End If ‘Test to see if the user’s guess was too low If FormatNumber(intUserNumber) < intRandomNo Then MsgBox “Your guess was too low. Try again”, ,cGreetingMsg strOkToEnd = “no” End If ‘Test to see if the user’s guess was too high If FormatNumber(intUserNumber) > intRandomNo Then MsgBox “Your guess was too high. Try again”, ,cGreetingMsg strOkToEnd = “no” End If End Function As you can see, the script’s initialization section remained unchanged, except for the addi- tion of one more variable, which will be used to indicate that the player has typed an invalid character. However, the main processing section is now quite different. Instead of having all the script’s statements embedded within it, this section now drives the script by maintain- ing high-level control over a collection of functions, each of which performs a specific process for the script. The main processing section now does three things: It calls a function that gets the game’s random number ( RandomNumber()), it calls a function that controls the play of the game ( PlayTheGame()), and then it ends the game by executing the WScript object’s Quit() method. The RandomNumber() function generates the random number used by the game. The PlayTheGame() function controls play of the game itself. Instead of making this a really large function, I simplified it a bit by removing and modifying the two If statements that perform 213 Chapter 7 • Using Procedures to Organize Scripts 214 input validation and placing them within their own function called ValidInput(). Likewise, I moved and modified the three If statements that determine whether the player’s guess was low, high, or correct to their own function called TestAnswer(). The only other modifi- cation made to the script was the addition of the following statements in the PlayTheGame(). These statements were needed to test the values of variables manipulated in the ValidateInput() and TestAnswer() functions. If strOkToEnd <> “yes” Then ‘The player typed in something If strBadData <> “yes” Then ‘The player typed in a number TestAnswer() ‘Let’s see how good the player’s guess was End If End If Working with Built-In VBScript Functions VBScript provides a large collection of built-in functions that you can add to your scripts to save yourself time and effort. Obviously, leveraging the convenience and power of these built-in VBScript functions is a smart thing to do. In fact, VBScript’s built-in functions are so essential to VBScript development that it’s diffi- cult to write a script of any complexity without using them. I have already demonstrated this fact many times throughout the book. A complete list of all VBScript built-in functions appears in Appendix B, “Built-In VBScript Functions.” Limiting Variables Scope with Procedures You have seen and worked with variables throughout this book. Thus far, all the variables that you have worked with have had a global or script-level scope, meaning they could be accessed from any point within the script. Any variable that is defined outside of a VBScript procedure (that is, function or subroutine) is global in scope. In contrast, any variable defined within a procedure is local in scope , meaning it exists and can only be referenced within the procedure that defines it. The best way to demonstrate the concept of global and local variable scope is in an example. The following script creates two variables, one at the beginning of the script and the other within a function: Option Explicit Dim intFirstRandomNumber Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition intFirstRandomNumber = GetRandomNumber() MsgBox “The first random number is “ & intFirstRandomNumber GenerateLocalizedVariable() MsgBox “The second random number is “ & intSecondRandomNumber WScript.Quit() Function GenerateLocalizedVariable() Dim intSecondRandomNumber intSecondRandomNumber = GetRandomNumber() MsgBox “The second random number is “ & intSecondRandomNumber End Function Function GetRandomNumber() ‘Generate a random number between 1 and 10 Randomize GetRandomNumber = FormatNumber(Int((10 * Rnd) + 1)) End Function When you run this script, the first variable is defined at the beginning of the script, making it a global variable. The value of the variable is then immediately displayed. The second variable is defined within a function named GenerateLocalizedVariable(). As a result, the variable can be referenced only within this function, as proven when the function’s MsgBox() statement displays its value. When the GenerateLocalizedVariable() function completes its execution, processing control returns to the statement that called the function. This state- ment is immediately followed by another MsgBox() statement, which attempts to display the value of the variable defined in the GenerateLocalizedVariable() function. However, this variable was destroyed as soon as that function ended, so instead of seeing the variable’s value, an error message is displayed, as shown in Figure 7.6. 215 Chapter 7 • Using Procedures to Organize Scripts 216 Back to the BlackJack Lite Game Now let’s return to the development of the BlackJack Lite game. In this game, you’ll develop your own version of the casino game blackjack. BlackJack Lite is a card game that pits the player against the computer. The object of the game is to come as close to 21 as possible without going over, to beat the computer’s hand. The computer, like a real casino blackjack dealer, waits for the player to finish before playing. The computer must then take hits until its hand busts (goes over 21) or reaches at least 17, at which time it must stop. Designing the Game The BlackJack Lite game is more complex than the other VBScripts that you’ve seen in this book. The game itself has a large number of different functions to perform. For example, the initial hand must be dealt for both the player and the computer. Then the game has to facil- itate the dealing of cards to the player and later to the computer. In addition, numerous smaller processes must occur along the way. Because this script is rather complex, I’ve decided to organize it into procedures. Each pro- cedure will be assigned a specific activity to perform. As part of my preparation for the design of the game, I have drawn a high-level flowchart of the game’s overall structure and processing logic; the flowchart is shown in Figure 7.7. The script consists of nine functions. These functions and their purposes are as follows: 1. DoYouWantToPlay() . Displays the game’s splash screen and invites the user to play the game. 2. NowGoPlay() . Controls the overall execution of the game, calling upon other procedures as required. 3. DealFirstHand() . Presents the initial cards for both the player and the computer. 4. PlayTheGame() . Asks the player whether he or she would like another card and determines when the player has either busted or decided to hold. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 7.6 Attempting to access a localized variable outside the procedure that defined it results in an error. 5. DealAnotherCard() . Retrieves another card for the player’s hand. 6. GetRandomNumber() . This function is called by several other functions in the script. It returns a random number between 1 and 13 representing the value of a playing card. 7. ComputerPlay() . Plays the computer hand, taking hits until either the computer’s hand is busted or is greater than 17. 217 Chapter 7 • Using Procedures to Organize Scripts Figure 7.7 A flowchart outlining the overall design and execution flow of the BlackJack Lite game. 218 8. DetermineWinner() . Compares the player’s hand against the computer’s hand to deter- mine who has won. It then offers to let the player play another hand. If the player accepts, the NowGoPlay() function is called, starting a new hand. 9. DisplaySplashScreen() . Displays information about the game and its author, and invites the player to return and play again before finally ending the game. Setting Up the Initialization Section Begin the development of the BlackJack Lite game the same way that you’ve begun all your other games, by first creating a new file and adding in your VBScript template, and then set- ting up the variables, constants, and object references in the script’s Initialization Section. ‘************************************************************************* ‘Script Name: BlackJack.vbs ‘Author: Jerry Ford ‘Created: 11/28/02 ‘Description: This script creates a scaled down version of the casino ‘version of the BlackJack card game ‘************************************************************************* ‘Initialization Section Option Explicit Dim intPlayGame, strCardImage, intUserCard, intComputerCard, intAnotherCard Dim intUserNextCard, strUserDone, intNewComputerCard, intPlayAgain Dim strUserBusted, strTextMsg strUserDone = “False” strUserBusted = “False” This game is fairly lengthy and requires a number of variables. • intPlayGame . Stores the player’s reply when asked if he or she wants to play a game. • strCardImage . Stores the message displayed in the game’s initial pop-up dialog. • intUserCard . Stores the total value of the cards dealt to the user. • intComputerCard . Stores the total value of the cards dealt to the computer. • intAnotherCard . Stores the player’s reply to the question of whether he or she wants another card. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition • intUserNextCard . Stores the value returned by the function that retrieves a random number and is later added to the value of the intUserCard variable. • strUserDone . Stores a value indicating whether the player is ready to hold. • intNewComputerCard . Stores the value returned by the function that retrieves a random number and is later added to the value of the intComputerCard variable. • intPlayAgain . Stores the player’s reply when asked whether he or she wants to play another game. • strUserBusted . Stores a value indicating whether the player has busted. • strTextMsg . Stores text to be displayed in pop-up dialogs displayed by the game. Developing the Logic for the Main Processing Section The script’s Main Processing section is very small and consists only of a call to the DoYouWantToPlay() function to determine whether the player wants to play the game, followed by the Select Case statement, which determines the player’s reply. ‘Main Processing Section ‘Ask the user if he or she wants to play intPlayGame = DoYouWantToPlay() Select Case intPlayGame Case 6 ‘User clicked on Yes NowGoPlay() Case 7 ‘User clicked on No DisplaySplashScreen() End Select If the player clicks on the Yes button, then the NowGoPlay() function is called. Otherwise, the DisplaySplashScreen() function is called. This function displays a pop-up dialog providing information about the game and then terminates the game’s execution. Creating the DoYouWantToPlay() Function This function displays the game’s initial pop-up dialog and invites the player to play a game of BlackJack Lite. Much of the text displayed in this pop-up dialog is dedicated to creating an image depicting the ace of spades. Also included in this pop-up dialog is a brief set of instructions. 219 Chapter 7 • Using Procedures to Organize Scripts . variables, one at the beginning of the script and the other within a function: Option Explicit Dim intFirstRandomNumber Microsoft WSH and VBScript Programming for the Absolute Beginner, Second. wants another card. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition • intUserNextCard . Stores the value returned by the function that retrieves a random number and. he or she would like another card and determines when the player has either busted or decided to hold. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 7.6 Attempting

Ngày đăng: 03/07/2014, 18:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan