160 Dim objWshShell, strAnswer, strCardImage, strResults, intGetRandomNumber 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 break 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” 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. “ & _ Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition “Please type rock, paper, or scissors in all lowercase letters.” WScript.Quit End Select objWshShell.Popup “You picked: “ & space(12) & strAnswer & vbCrLf & _ vbCrLf & “Computer picked: “ & space(2) & strCardImage & vbCrLf & _ vbCrLf & “================” & vbCrLf & vbCrLf & “Results: “ & _ strResults Performing More Complex Tests with VBScript Operators Up to this point in the book every example of the If or a Select Case statement that you have seen has involved a single type of comparison, equality. This is a powerful form of com- parison, but there will be times when your scripts will need to test for a wider range of values. For example, suppose you wanted to write a script that asked the user to type in their age so that you could determine whether the user was old enough to play your game (say you didn’t want a user to play the game if he or she was younger than 19). It would be time-consuming to write a script that used a 100 If statements, or 1 Select Case statement with 100 corre- sponding Case statements, just to test a person’s age. Instead, you could save a lot of time by comparing the user’s age against a range of values. To accomplish this task, you could use the VBScript Less Than operator as follows: intUserAge = InputBox(“How old are you?”) If intUserAge < 19 Then MsgBox “Sorry but you are too young to play this game.” WScript.Quit() Else MsgBox “OK. Let’s play!” End If In this example, the VBScript InputBox() function was used to collect the user’s age and assign it to a variable called intUserAge. An If statement then checks to see whether intUserAge is less than 19, and if it is, the game is stopped. Another way you could write the previous example is using the VBScript Less Than or Equal To operator, like this: If intUserAge <= 18 Then 161 Chapter 5 • Conditional Logic 162 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition If you use the Less Than or Equal To operator, this statement will not execute if the user is 18 or fewer years old. VBScript also supplies Greater Than and Greater Than or Equal To oper- ators, allowing you to invert the logic used in the preceding example. intUserAge = InputBox(“How old are you?”) If intUserAge > 18 Then MsgBox “OK. Let’s play!” Else MsgBox “Sorry but you are too young to play this game.” WScript.Quit() End If Table 5.1 lists VBScript comparison operators. VBScript does not impose an order or precedence on comparison operators like it does with arithmetic operators. Instead, each comparison operation is performed in the order in which it appears, going from left to right. Back to the Star Trek Quiz Game Now let’s return to where we began this chapter, by developing the Star Trek Quiz game. In this program, you will create a VBScript that presents the player with a quiz about Star Trek. The game presents questions, collects the player’s answers, scores the final results, assigns a rank to the player based on his or her score, and finally creates a summary text report. By working your way through this project, you will work more with both the If and Select Case statements. You’ll also learn how to work with a number of built-in VBScript functions. Operator Description = Equal <> Not equal < Less than > Greater than <= Less than or equal to >= Greater than or equal to TABLE 5.1 VBSCRIPT C OMPARISON O PERATORS Game Development The following steps outline the process you’ll need to go through to complete the develop- ment of the game: 1. Add the standard documentation template and fill in its information. 2. Define the constants and variables that will be used by the script. 3. Create the splash screen that welcomes the user to the story and determines whether the user wants to play the game. 4. Use the InputBox() function to display questions and collect the player’s answers and to add logic to determine whether the player’s answers are right or wrong. 5. Use the Select Case statement to determine the rank to be assigned to the player, based on the number of correctly answered questions. 6. Display the player’s score and rank. Beginning the Star Trek Quiz Game Begin this script by opening your script editor and cutting and pasting your script template from another script; then go back and modify the template with information relevant to the Star Trek Quiz game. ‘************************************************************************* ‘Script Name: StarTrekQuiz.vbs ‘Author: Jerry Ford ‘Created: 11/17/02 ‘Description: This script creates a Star Trek Quiz game. ‘************************************************************************* ‘Perform script initialization activities Option Explicit Setting Up Constants and Variables The next step is to define the variables and constants used by the script. Dim intPlayGame, strSplashImage, strAnswerOne, strAnswerTwo, strAnswerThree Dim strAnswerFour, strAnswerFive, intNumberCorrect, strFederationRank Dim objFsoObject 163 Chapter 5 • Conditional Logic 164 Const cTitlebarMsg = “The Star Trek Quiz Game” ‘Start the user’s score at zero intNumberCorrect = 0 The intNumberCorrect variable is used to count the number of quiz answers the player gets right. I set intNumberCorrect equal to zero here to ensure that it has a value because it is always possible that the player will miss every answer and this variable might not otherwise get set. I’ll explain what each of these variables is used for as we go through the rest of the script development process. Creating a Splash Screen Let’s create a spiffy splash screen that asks the user whether he or she wants to play the game. As you can see, I added a graphic to spice up things a bit. Graphic development of this type takes a little time, as well as some trial and error. ‘Display the splash screen and ask the user if he or she wants to play strSplashImage = space(11) & “********” & vbCrLf & _ “ ******************” & space(20) & “**************************” & _ space(20) & vbCrLf & “*” & space(35) & “*” & space(18) & _ “**” & space(46) & “*” & vbCrLf & “ ******************” & _ space(20) & “*************************” & vbCrLf & space(31) & _ “******” & space(26) & “***” & vbCrLf & _ space(34) & “******” & space(22) & “***” & vbCrLf & _ space(37) & “******” & space(17) & “***” & vbCrLf & _ space(26) & “ ****************************” & vbCrLf & _ space(26) & “*******************************” & vbCrLf & _ space(26) & “******************************” & vbCrLf & _ space(26) & “ ****************************” & vbCrLf & vbCrLf & vbCrLf &_ space(10) & “Would you like to boldly go where no one has gone before?” intPlayGame = MsgBox(strSplashImage, 36, cTitlebarMsg) The splash screen is created using the VBScript InputBox() function. It displays the invitation to play the game as well as Yes and No buttons. The value of the button the user clicks is assigned to the PlayGame variable (that is, PlayGame will be set equal to 6 if the player clicks on the Yes button). Now let’s check to see whether the user wants to play the game. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition If intPlayGame = 6 Then ‘User elected to play the game ‘Insert statements that make up the game here . . . Else ‘User doesn’t want to play MsgBox “Thank you for taking the Star Trek Quiz © Jerry Ford 2002.” & _ vbCrLf & vbCrLf & “Live long and prosper!”, , cTitlebarMsg WScript.Quit() End If As you can see, the first statement checks to see whether the user clicked on the Yes button. I left some room to mark the area where you will need to add the statements that actually make up the game, in case the user does want to play. If the user clicked No, then the VBScript displays a “thank you” message and terminates its execution using the WScript object’s Quit() method. Display Quiz Questions and Collect the Player’s Answers The next step is to add the questions that make up the game. The following questions make up the quiz: • What was the Science Officer’s name in the original Star Trek series? • What Star Trek villain appeared in both the original series and a Star Trek movie? • What was the numeric designation of Voyager’s on-board Borg? • Name the only Star Trek character to regularly appear on two series and at least two Star Trek movies. • What is the last name of your favorite Captain? The statements that display and grade the first quiz questions are as follows: strAnswerOne = InputBox(“What was the Science Officer’s name in the “ & _ “original Star Trek series?”, cTitlebarMsg) If LCase(strAnswerOne) = “spock” Then intNumberCorrect = intNumberCorrect + 1 End If 165 Chapter 5 • Conditional Logic 166 First the VBScript InputBox() function displays the question. The answer typed by the user is then assigned to a variable named strAnswerOne. Next, an If statement is used to interrogate the player’s answer and determine whether it’s correct. The VBScript LCase() function is used to convert the answer the player types to all lowercase . This way, it doesn’t matter how the player types in the answer. For example, SPOCK, spock, SpOcK, and Spock would all end up as spock. Finally, if the player provides the correct answer, then the value of intNumberCorrect is increased by 1. As you can see, the second quiz question, shown next, is processed exactly like the first ques- tion. The only difference is the content of the question itself and the name of the variable used to store the player’s answer to the question. strAnswerTwo = InputBox(“What Star Trek villain appeared in both the “ & _ “original series and a Star Trek movie?”, cTitlebarMsg) If LCase(strAnswerTwo) = “khan” Then intNumberCorrect = intNumberCorrect + 1 End If The statements that make up and process the quiz’s third question are shown next. As you can see, I have altered the logic a bit by adding an ElseIf statement to accommodate either of two possible answers to this question. strAnswerThree = InputBox(“What was the numeric designation of “ & _ “Voyager’s on-board Borg?”, cTitlebarMsg) If CStr(strAnswerThree) = “7” Then intNumberCorrect = intNumberCorrect + 1 ElseIf CStr(strAnswerThree) = “7 of 9” Then intNumberCorrect = intNumberCorrect + 1 End If The statements that make up the fourth question follow the same pattern as the first two questions. strAnswerFour = InputBox(“Name the only Star Trek character to “ & _ “regularly appear on two series and at least two Star Trek “ & _ “movies?”, cTitlebarMsg) If LCase(strAnswerFour) = “worf” Then intNumberCorrect = intNumberCorrect + 1 End If Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition The construction of the fifth question, shown next, merits some additional examination. First of all, the fourth statement uses the VBScript LCase() function to convert the player’s answer to all lowercase. The VBScript Instr() function then takes the answer and searches the string “kirkpicardsiscojanewayarcher” to see whether it can find a match. This string contains a list of last names belonging to various Star Fleet captains. strAnswerFive = InputBox(“What is the last name of your favorite “ & _ “Captain?”, cTitlebarMsg) If Len(strAnswerFive) > 3 Then If Instr(1, “kirkpicardsiscojanewayarcher”, LCase(strAnswerFive), 1) _ <> 0 Then intNumberCorrect = intNumberCorrect + 1 End If End If So the InStr() function begins its search starting with the first character of the string to see whether it can find the text string that it’s looking for (that is, kirk, picard, janeway, sisco, or archer). The syntax of the Instr() function is as follows: InStr([start, ]string1, string2[, compare]) Start specifies the character position in the script, from left to right, where the search should begin. String1 identifies the string to search. String2 identifies the text to search for, and compare specifies the type of search to perform. A value of 0 specifies a binary compari- son, and a value of 1 specifies a textual comparison. The InStr() function returns the location of the beginning location of a matching text string. If it does not find a matching text string in the list, then it will return to zero, in which case the user provided the wrong answer. Otherwise, it will return the starting char- acter position where the search string was found. If the search string is found in the list, then the value returned by the InStr() function will be greater than 1, in which case the value of intNumberCorrect will be incremented by 1. However, it is always possible that the player doesn’t know the name of one Star Ship cap- tain, and that he or she will just type a character or two, such as the letter “A.” Because the letter “A” is used in at least one of the captain’s last names, the player would end up getting credit for a correct answer to the question. Clearly, this is not good. To try to keep the game honest, I used the VBScript Len() function to be sure that the user provided at least a four- character name (that is, the length of the shortest last name belonging to any captain). This way, the player must know at least the first four characters of a captain’s last name to get credit for a correct answer. 167 Chapter 5 • Conditional Logic 168 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Scoring the Player’s Rank At this point, the script has enough logic to display all five questions and determine which ones the player got correct. In addition, it has been keeping track of the total number of correct answers. What you need to do next is add logic to assign the player a rank based on the num- ber of correctly answered questions. This can be done using a Select Case statement, like this: Select Case intNumberCorrect Case 5 ‘User got all five answers right strFederationRank = “Admiral” Case 4 ‘User got 4 of 5 answers right strFederationRank = “Captain” Case 3 ‘User got 3 of 5 answers right strFederationRank = “Commander” Case 2 ‘User got 2 of 5 answers right strFederationRank = “Lieutenant-Commander” Case 1 ‘User got 1 of 5 answers right strFederationRank = “Lieutenant” Case 0 ‘User did not get any answers right strFederationRank = “Ensign” End Select The variable intumberCorrect contains the number of answers that the player has correctly answered. The value of this variable is then compared against six possible cases, each of which represents a different score the player could have gotten from the game. When a match is found, the player’s rank is assigned based on the values listed in Table 5.2. Number of Correctly Federation Rank Answered Questions 5 Admiral 4 Captain 3 Commander 2 Lieutenant-Commander 1 Lieutenant 0 Ensign TABLE 5.2 DETERMINING THE P LAYER’S FEDERATION R ANK Displaying the Player’s Score and Rank The last thing the game does is display the player’s score and rank in a pop-up dialog. MsgBox “You answered “ & intNumberCorrect & “ out of 5 correct.” & _ vbCrLf & vbCrLf & “Your Star Fleet rank is : “ & _ strFederationRank, , cTitlebarMsg As you can see, there is not much to this last statement. All you need to do is to use the VBScript MsgBox() function, the strNumberCorrect, and strFederationRank variables, as well as the vbCrLf constant, to display the message for the player to see. The Fully Assembled Script Okay, let’s take a look at how the script looks now. Run it and be sure that everything is working as advertised. ‘************************************************************************* ‘Script Name: StarTrekQuiz.vbs ‘Author: Jerry Ford ‘Created: 11/17/02 ‘Description: This script creates a Star Trek Quiz game. ‘************************************************************************* ‘Perform script initialization activities Option Explicit Dim intPlayGame, strSplashImage, strAnswerOne, strAnswerTwo, strAnswerThree Dim strAnswerFour, strAnswerFive, intNumberCorrect, strFederationRank Dim objFsoObject Const cTitlebarMsg = “The Star Trek Quiz Game” ‘Start the user’s score at zero intNumberCorrect = 0 ‘Display the splash screen and ask the user if he or she wants to play strSplashImage = space(11) & “********” & vbCrLf & _ “ ******************” & space(20) & “**************************” & _ space(20) & vbCrLf & “*” & space(35) & “*” & space(18) & _ 169 Chapter 5 • Conditional Logic . to see whether the user wants to play the game. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition If intPlayGame = 6 Then ‘User elected to play the game ‘Insert. using the VBScript Less Than or Equal To operator, like this: If intUserAge <= 18 Then 161 Chapter 5 • Conditional Logic 162 Microsoft WSH and VBScript Programming for the Absolute Beginner, . Lose” If intGetRandomNumber = 1 Then strResults = “Tie” Case Else objWshShell.Popup “Sorry. Your answer was not recognized. “ & _ Microsoft WSH and VBScript Programming for the Absolute Beginner,