‘Formally declare each variable used by the script before trying to ‘use them Dim objWshShell, strAnswer, strCardImage, intGetRandomNumber ‘Create an instance of the WScript object in or
Trang 1You can expand the Ifstatement by adding one or more ElseIfkeywords, each of which can test another alternative condition For example, look at the following VBScript statements:
If X = 250 Then
WScript.Echo “Go and buy that TV!”
WScript.Echo “Buy a TV Guide while you are at it.”
WScript.Echo “And do not forget to say thank you.”
ElseIf X = 200 Then
WScript.Echo “Buy the VCR”
ElseIf X = 100 Then
WScript.Echo “Buy the Radio.”
Else
WScript.Echo “OK Maybe you had best just eat lunch.”
End If
Nesting If Statements
Another way to use Ifstatements is to embed them within one another This enables you to develop scripts that test for a condition and then further test other conditions based on the result of the previous test To see what I mean, look at the following example (I have bolded the embedded Ifstatement to make it easier to see):
X = 250
If X = 250 Then
In the Real World
A flowchart is a graphical depiction of the possible logical flow of a script or program
Pro-grammers sometimes begin script development by first creating a flowchart The flowchart serves as a visual tool for script development and provides a valuable documentation tool Flowchart development can be a big help in the creation of complex scripts Flowcharts help programmers formalize their thoughts before script development begins Sometimes an automation task requires the development of several scripts, all of which must work together Flowcharts provide a way of designing and documenting the logical flow between each script Flowcharts can also facilitate script development when multiple programmers are involved, as they can be used to break down a task into discrete parts, each of which can then be assigned
to a different person to work on
Trang 2If Weekday(date()) = 1 Then
WScript.Echo “It’s Sunday The TV store is closed on Sundays.”
Else
WScript.Echo “Go and buy that TV!” & vbCrLf & _
“Buy a TV Guide while you are at it.” & vbCrLf & _
“And do not forget to say thank you.”
End If
Else
WScript.Echo “OK Just purchase the radio for today.”
End If
In this example, the first statement performs a test to see whether the value assigned to a variable named Xis equal to 250 If it’s not equal to 250, the script skips all the statements located between the If X = 250 Thenline and the Elseline and displays the message “OK Just purchase the radio for today.” However, if the value of X is equal to 250, then the embedded Ifstatement executes This Ifstatement begins by determining whether the cur-rent day of the week is Sunday, and if it is, the script informs the user that the TV store is closed Otherwise, it tells the user to go and make the purchase
The test performed by the Ifstatement in the previous example deserves a little extra explanation As you saw, it retrieved a numeric value representing the current day of the week Here’s how to break down the logic used by this state-ment: First, it executed the built-in VBScript Date() function The value retrieved by this function was then used by the built-in VBScript Weekday() function to determinate the numeric value that represents the current day of the week These values are 1 = Sunday, 2 = Monday, 3 = Tuesday, 4 = Wednesday,
5 = Thursday, 6 = Friday, 7 = Saturday Once this value was established, the If statement simply checked to see if it was equal to 7 (Sunday)
As you can see, by taking advantage of built-in VBScripts functions you can per-form some fairly complex tasks with minimal coding It’s a good idea to always check to see whether VBScript has a built-in function before attempting to write
a piece of code to perform a generic task, such as date manipulation or checking
By embedding, or nesting one Ifstatement within another Ifstatement, you can develop complex programming logic There’s no limit on the number of If statements you can embed within one another, although going more than a few layers deep can become confusing and difficult to follow.
H I N T
T R I C K
Trang 3RockPaperScissors.vbs Revisited
Okay You’ve now learned a lot about the Ifstatement, including its syntax and various ways
in which it can be used One of the biggest challenges that I faced in coming up with the VBScript examples for the first four chapters of this book was how to create VBScript-based games without using VBScript programming statements that I had not yet covered For the most part I was successful, but there was one exception: I just could not avoid using the If statement—although I tried to use it as little as possible In most cases, this meant limiting the completeness of the games presented
One such game was the RockPaperScissors.vbsgame Now that I’ve finally provided a com-plete review of the Ifstatement, let’s revisit the game and see how we can make it better
‘Formally declare each variable used by the script before trying to
‘use them
Dim objWshShell, strAnswer, strCardImage, intGetRandomNumber
‘Create an instance of the WScript object in order to later use
‘the Popup method
Set objWshShell = WScript.CreateObject(“WScript.Shell”)
‘Display the rules of the game
objWshShell.Popup “Welcome to Rock, Paper, and Scissors game “ & _
“Here are the “ & _
“rules of the game: 1 Guess the same thing as the computer “ & _
“to tie 2 Paper covers rock and wins 3 Rock breaks “ & _
“scissors and wins 4 Scissors cut paper and win.”
‘Prompt the user to select a choice
strAnswer = InputBox(“Type Paper, Rock, or Scissors.”, _
“Let’s play a game!”)
‘Time for the computer to randomly pick a choice
Randomize
intGetRandomNumber = Round(FormatNumber(Int((3 * Rnd) + 1)))
‘Assign a value to the randomly selected number
If intGetRandomNumber = 3 then strCardImage = “rock”
If intGetRandomNumber = 2 then strCardImage = “scissors”
If intGetRandomNumber = 1 then strCardImage = “paper”
‘Display the game’s results so that the user can see if he won
Trang 4objWshShell.Popup “You picked: “ & strAnswer & Space(12) & _
“Computer picked: “ & strCardImage
Figure 5.6 shows the output of a complete game as the script currently is written.
First off, let’s update the script by adding the script template that was introduced back in Chapter 3, “VBScript Basics.”
‘*************************************************************************
‘Script Name: RockPaperScissors-2.vbs
‘Author: Jerry Ford
‘Created: 11/16/02
‘Description: This script revisits the RockPaperScissors.vbs script, first
‘introduced in Chapter 2, and updates it using advanced conditional logic
‘*************************************************************************
Next, let’s rewrite the Dimstatement by adding another variable called Results
Dim objWshShell, strAnswer, strCardImage, strResults
Resultsis used later in the scripts to store the results of the game (that is, who wins and who loses) Next let’s add the following statement to the script:
Set objWshShell = WScript.CreateObject(“WScript.Shell”)
This statement creates an instance of the objWshShellobject This object’s Quit()method is used later in the script to terminate its execution in the event that the user fails to provide
a valid selection (that is, the player does not pick rock, paper, or scissors)
Now that the variables and objects to be used by the script have been defined, let’s assign a default value of Noneto the strResultsvariable, like this:
strResults = “None”
Unless the player provides a correction selection, this value will remain equal to None throughout the script’s execution, and will eventually cause the script to terminate and dis-play an error message However, if the dis-player supplies a correct response, the response will
be assigned to the strResultsvariable and then will be analyzed by the script
Figure 5.6
Playing Rock,
Paper, and
Scissors
Trang 5The original RockPaperScissors.vbs script displayed the game’s instructions in one popup dialog, and then prompted the player to specify a selection of rock, paper, or scissors in a second pop-up dialog This works, but using two pop-up dialogs is a bit clunky Let’s modify the scripts to display the game’s directions and collect the player’s input at the same time, like this:
strAnswer = InputBox(“Please type paper, rock, or scissors.” & _
vbCrLf & vbCrLf & “Rules:” & vbCrLf & vbCrLf & _
“1 Guess the same thing as the computer to tie.” & vbCrLf & _
“2 Paper covers rock and wins.” & vbCrLf & _
“3 Rock breaks scissors and wins.” & vbCrLf & _
“4 Scissors cut paper and win.” & vbCrLf, “Let’s play a game!”)
As you can see, I used the VBScript InputBox()function to display the pop-up dialog, and I formatted the instructions for better presentation using the vbCrLfconstant.
The next two sections of the script remain the same as in the original script
Randomize
intGetRandomNumber = Round(FormatNumber(Int((3 * Rnd) + 1)))
If intGetRandomNumber = 3 then strCardImage = “rock”
If intGetRandomNumber = 2 then strCardImage = “scissors”
If intGetRandomNumber = 1 then strCardImage = “paper”
As explained in Chapter 2, “Overview of the Windows Script Host,” the first pair of state-ments results in the selection of a random number with a value between 1 and 3 The next three lines assign a value of rock, paper, or scissors to each of these values The rest of the script will be comprised of all new code Instead of simply displaying the player’s and the script’s selection of rock, paper, or scissors and then leaving it up to the player to figure out who won, the script now performs the analysis To begin, add the following lines to the bot-tom of the script:
If strAnswer = “rock” Then
If intGetRandomNumber = 3 Then strResults = “Tie”
If intGetRandomNumber = 2 Then strResults = “You Win”
If intGetRandomNumber = 1 Then strResults = “You Lose”
End If
Trang 6This set of statements executes only if the player typed rock Three Ifstatements then com-pare the user’s selection to the script’s randomly selected decisions and determine the results of the game Now replicate this collection of statements two times, and then modify each set as follows to add tests for the selection of both scissors and paper:
If strAnswer = “scissors” Then
If intGetRandomNumber = 3 Then strResults = “You Lose”
If intGetRandomNumber = 2 Then strResults = “Tie”
If intGetRandomNumber = 1 Then strResults = “You Win”
End If
If strAnswer = “paper” Then
If intGetRandomNumber = 3 Then strResults = “You Win”
If intGetRandomNumber = 2 Then strResults = “You Lose”
If intGetRandomNumber = 1 Then strResults = “Tie”
End If
Now add the following statements to the script:
If strResults = “None” Then
objWshShell.Popup “Sorry Your answer was not recognized “ & _
“Please type rock, paper, or scissors in all lowercase letters.”
WScript.Quit
End If
These statements only execute if the player fails to provide a correct response when playing the game If this happens, the value of strResultsis never changed and will still be set equal
to None as assigned at the beginning of the script In this case, the objWshShell object’s Popup()and Quit()methods are used to display an error message and then end the game Now let’s wrap up this script by adding these last few lines of code.
objWshShell.Popup “You picked: “ & space(12) & strAnswer & vbCrLf & _
vbCrLf & “Computer picked: “ & space(2) & strCardImage & vbCrLf & _
vbCrLf & “================” & vbCrLf & vbCrLf & “Results: “ & _
strResults
Trang 7These statements are only executed if the player provided a valid response They used the objWshShellobject’s Popup()method to display the results of the game, including both the player’s and the script’s selections
The fully assembled script should now look like the following:
‘*************************************************************************
‘Script Name: RockPaperScissor-2.vbs
‘Author: Jerry Ford
‘Created: 11/16/02
‘Description: This script revisits the RockPaperScissors.vbs script first
‘introduced in Chapter 2 and updates it using advanced conditional logic
‘*************************************************************************
‘Perform script initialization activities
Dim objWshShell, strAnswer, strCardImage, strResults
Set objWshShell = WScript.CreateObject(“WScript.Shell”)
strResults = “None”
‘Prompt the user to select a choice
strAnswer = InputBox(“Please type paper, rock, or scissors.” & _
vbCrLf & vbCrLf & “Rules:” & vbCrLf & vbCrLf & _
“1 Guess the same thing as the computer to tie.” & vbCrLf & _
“2 Paper covers rock and wins.” & vbCrLf & _
“3 Rock breaks scissors and wins.” & vbCrLf & _
“4 Scissors cut paper and win.” & vbCrLf, “Let’s play a game!”)
‘Time for the computer to randomly pick a choice
Randomize
intGetRandomNumber = Round(FormatNumber(Int((3 * Rnd) + 1)))
If intGetRandomNumber = 3 then strCardImage = “rock”
If intGetRandomNumber = 2 then strCardImage = “scissors”
If intGetRandomNumber = 1 then strCardImage = “paper”
Trang 8‘When you select rock
If strAnswer = “rock” Then
If intGetRandomNumber = 3 Then strResults = “Tie”
If intGetRandomNumber = 2 Then strResults = “You Win”
If intGetRandomNumber = 1 Then strResults = “You Lose”
End If
‘When you select scissors
If strAnswer = “scissors” Then
If intGetRandomNumber = 3 Then strResults = “You Lose”
If intGetRandomNumber = 2 Then strResults = “Tie”
If intGetRandomNumber = 1 Then strResults = “You Win”
End If
‘When you select paper
If strAnswer = “paper” Then
If intGetRandomNumber = 3 Then strResults = “You Win”
If intGetRandomNumber = 2 Then strResults = “You Lose”
If intGetRandomNumber = 1 Then strResults = “Tie”
End If
If strResults = “None” Then
objWshShell.Popup “Sorry Your answer was not recognized “ & _
“Please type rock, paper, or scissors in all lowercase letters.”
WScript.Quit
End If
objWshShell.Popup “You picked: “ & space(12) & strAnswer & vbCrLf & _
vbCrLf & “Computer picked: “ & space(2) & strCardImage & vbCrLf & _
vbCrLf & “================” & vbCrLf & vbCrLf & “Results: “ & _
strResults
Save and execute the script Figure 5.7 shows the initial pop-up dialog displayed by the script.
Trang 9Figure 5.8 shows the results of a typical game.
The Select Case Statement
The If statement provides a great tool for testing two expressions Using ElseIf you can modify the Ifstatement to perform additional tests VBScripts supplies another statement, called Select Case, which also lets you perform comparative operations Functionally, it’s not really very different from the Ifstatement However, the Select Case statement is better equipped to perform large numbers of tests against a single expression
Here is the syntax of the Select Casestatement:
Select Case expression
Case value
statements
Case value
statements
Case Else
statements
End Select
Figure 5.7
The new version
of RockPaper
Scissors.vbs
displays a
friendlier initial
dialog
Figure 5.8
The results of
a typical game
of the new
version of
RockPaper
Scissors.vbs
Trang 10The Select Casestatement begins with Select Case, and then specifies the expression to be compared against one or more values specified in Casestatements that follow the Select Casestatement and precede the End Select statement Optionally, a Case Elsestatement can also be added to provide an alternative course of action should none of the Casestatement’s values match up against the expression specified by the Select Casestatement
Look at the following example:
Select Case strAnswer
Case “rock”
If intGetRandomNumber = 3 Then strResults = “Tie”
If intGetRandomNumber = 2 Then strResults = “You Win”
If intGetRandomNumber = 1 Then strResults = “You Lose”
Case “scissors”
If intGetRandomNumber = 3 Then strResults = “You Lose”
If intGetRandomNumber = 2 Then strResults = “Tie”
If intGetRandomNumber = 1 Then strResults = “You Win”
Case “paper”
If intGetRandomNumber = 3 Then strResults = “You Win”
If intGetRandomNumber = 2 Then strResults = “You Lose”
If intGetRandomNumber = 1 Then strResults = “Tie”
Case Else
objWshShell.Popup “Sorry Your answer was not recognized “ & _
“Please type rock, paper, or scissors in all lowercase letters.”
WScript.Quit
End Select
Here I have rewritten most of the logic implemented in the RockPaperScissors.vbsscript As the following complete script shows, not only did I reduce the number of lines of code required by the script to work, but I also improved the script’s readability:
‘*************************************************************************
‘Script Name: RockPaperScissors-3.vbs
‘Author: Jerry Ford
‘Created: 11/16/02
‘Description: This script revisits the RockPaperScissors-2.vbs script,
‘replacing some of the If statement’s logic with a Case Select statement
‘*************************************************************************
‘Perform script initialization activities