Microsoft WSH and VBScript Programming for the Absolute Beginner Part 20 doc

10 192 0
Microsoft WSH and VBScript Programming for the Absolute Beginner Part 20 doc

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

Thông tin tài liệu

170 “**” & 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) If intPlayGame = 6 Then ‘User elected to play the game 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 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 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 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition 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 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 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 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” 171 Chapter 5 • Conditional Logic 172 Case 0 ‘User did not get any answers right strFederationRank = “Ensign” End Select MsgBox “You answered “ & intNumberCorrect & “ out of 5 correct.” & _ vbCrLf & vbCrLf & “Your Star Fleet rank is : “ & _ strFederationRank, , cTitlebarMsg Summary This chapter covered a lot of ground. You learned how to use the If and Case Select state- ments in a number of different ways. Using this new information, you updated the Rock, Paper, and Scissors game and created the Star Trek Quiz game. In addition, you learned how to create VBScripts that could generate reports and log files. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition C HALLENGES 1. Modify the Star Trek Quiz game so that it asks players for their names and then use the players’ names at the end of the game to address them according to their ranks. 2. Modify the Star Trek Quiz so that it displays the correct answer for any question that the player misses. 3. Expand the Star Trek Quiz game by adding more questions. Store a list of ques- tions in an array and then use a For Each Next loop to display and process both the questions and the player’s answers. Processing Collections of Data 6 CHAPTER I n this chapter, you’ll learn how to use a number of VBScript statements that can help you develop scripts capable of processing extremely large amounts of information—in most cases with only a handful of script statements. Using these statements, you can establish loops within your scripts to let the user iteratively enter as much data as needed, to process the contents of array, to read the content’s files, and to control the execution of VBScript games. I’ll also show you how to create shortcuts for your scripts, as well as how to place them on the Windows desktop, Start Menu, and Quick Launch toolbar. Specifically, you will learn how to • Work with five different types of VBScript loops • Use loops to control the execution of your scripts (and games) • Programmatically create Windows shortcuts and use them to configure Windows resources such as the desktop and Start Menu Project Preview: The Guess a Number Game In this chapter’s project, you’ll create a script that plays a number guessing game. The game generates a random number between 1 and 100, then instructs the player to try to guess it. As the player enters guesses, the game provides the player with hints to help him figure out the number. If the player types an invalid guess, the game will let him know that only numeric input is accepted. CHAPTER 174 The player may quit at any time by simply clicking on the Cancel button, or by failing to type a guess before clicking on OK. Once the player guesses the correct answer, the game displays the number of guesses it took him to find the correct answer. Figures 6.1 through 6.6 provide a sneak peek of the game’s interaction. The game uses a VBScript loop to continue executing until either the player guesses the correct answer or quits. By developing and working with this game, you will solidify your understand- ing of iterative programming while also learning specifically how to apply a loop using VBScript. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 6.1 The Guess a Number game begins by prompting the player to type a number between 1 and 100. Figure 6.2 The game tells the player to try again if his or her guess is too low. Figure 6.3 The game tells the player to try again if his or her guess is too high. Figure 6.4 The game instructs the player to provide only numeric input. Figure 6.5 The game ends if the player clicks on Cancel or fails to provide a guess. Adding Looping Logic to Scripts One of VBScript’s best programming features is its strong support for looping or iterative statements . VBScript provides five different statements that can create loops. Loops provide your scripts with the capability to process large collections of data using a minimal num- ber of programming statements that are repeatedly executed, either for each member of the collection or for a specified number of times. The following list provides a high-level description of each of VBScript’s looping statements: • For Next. Establishes a loop that iterates for a specified number of times. • For Each Next. Establishes a loop that iterates through all the properties associated with an object. • Do While. Establishes a loop that iterates for as long as a stated condition continues to be true. • Do Until. Establishes a loop that iterates until a stated condition finally becomes true. • While Wend. Establishes a loop that iterates for as long as a condition continues to be true. The For…Next Statement The For Next statement is used to create loops that execute a specific number of times. For example, if you’re creating a game requiring the player to enter five guesses, you could use a For Next loop to control the logic that supports the data collection portion of the script. The syntax for the For Next statement is as follows: For counter = begin To end [Step StepValue] statements Next 175 Chapter 6 • Processing Collections of Data Figure 6.6 Once the player has correctly guessed the game’s number, the player is congratulated. Definition A loop is a collection of statements repeatedly executed to facilitate the processing of large amounts of data. 176 counter is a variable used to control the execution of the loop. begin is a numeric value that specifies the starting value of the counter variable. end specifies the ending value for the counter variable (that is, the value that, when reached, terminates the loop’s execution). StepValue is an optional setting that specifies the increment that the For Next statement uses when incrementing the value of counter (that is, the value added to counter at the end of each iteration). If omitted, the value assigned to StepValue is always 1. To better understand the operation of a For Next loop, look at one example that collects data without using a loop and one that collects the same data using a For Next loop. In the following example, let’s assume that you’re creating a game in which the player is expected to enter the name of his or her five favorite foods. You could always handle this type of situation as follows: Dim strFoodList strFoodList = “ “ strFoodList = strFoodList & “ “ & InputBox(“Type the name of a food “ & _ “that you really like.”) strFoodList = strFoodList & “ “ & InputBox(“Type the name of a food “ & _ “that you really like.”) strFoodList = strFoodList & “ “ & InputBox(“Type the name of a food “ & _ “that you really like.”) strFoodList = strFoodList & “ “ & InputBox(“Type the name of a food “ & _ “that you really like.”) strFoodList = strFoodList & “ “ & InputBox(“Type the name of a food “ & _ “that you really like.”) MsgBox “You like : “ & strFoodList As you can see, this example repeats the same statement over and over again to collect user input. Then, as proof that it did its job, it displays the data it collected using the MsgBox() function. Collecting five pieces of data like this is a bit of a chore. Now imagine a situation in which you want to collect a lot more data. Instead of typing the same statement over and over again, as done in the previous example, you can use the For Next loop. Dim intCounter, strFoodList strFoodList = “ “ For intCounter = 1 To 5 strFoodList = strFoodList & “ “ & InputBox(“Type the name of a “ & _ “food that you really like.”) Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Next MsgBox “You like : “ & strFoodList Figure 6.7 demonstrates the output produced by this example. Notice this new script is two lines shorter than the previous example. Unlike the previous example, other than the value of the loop’s ending value, this script does not have to be modified to accommodate the collection of additional data. For example, to change the For Next loop so that it can accommodate the collection of ten pieces of data, all you’d have to do is modify it like this: For intCounter = 1 To 10 strFoodList = strFoodList & “ “ & InputBox(“Type the name of a “ & _ “food that you really like.”) Next Optionally, you can use the Exit For statement to break out of a For Next loop at any time, like this: Dim intCounter, strFoodList, strNewFood strFoodList = “ “ For intCounter = 1 To 5 strNewFood = InputBox(“Type the name of a food that you really like.”) If strNewFood = “beans” Then MsgBox “Sorry, but I don’t want to talk to anyone who likes beans!” Exit For End If strFoodList = strFoodList & “ “ & strNewFood Next MsgBox “You like : “ & strFoodList 177 Chapter 6 • Processing Collections of Data Figure 6.7 Using a For Next loop to collect and process user input. 178 In this example, the assignment of data has been split into two different statements. The first of these statements assigns the name of the food entered by the user to a variable called strNewFood. The value of strNewFood is then added to the list of foods liked by the user only if it is not “beans,” in which case the script displays a message and then terminates the exe- cution of the For Next loop. As a result, only the foods entered by the user up to the point where beans was typed are displayed. Let’s look at one last example before we examine the other loop statements supported by VBScript. In this example, the For Next statement’s optional keyword Step has been added to change the behavior of the loop. Dim intCounter For intCounter = 1 To 9 Step 3 WScript.Echo intcounter Next In this example, the script will display the value of the counter variable, which is used to control the loop’s execution. Instead of counting to 9 by 1s, the script will count by 3s as demonstrated here. C:\>CScript TextScript.vbs Microsoft (R) Windows Script Host Version 5.1 for Windows Copyright (C) Microsoft Corporation 1996-1999. All rights reserved. 1 4 7 C:\> The For Each…Next Statement VBScript’s For Each Next statement is a programming tool for working with all the proper- ties associated with objects. Every object has a number of properties associated with it. Using the For Each Next loop, you could write a script to loop through all an object’s properties. The syntax of the For Each Next statement is as follows: For Each element In collection statements Next [element] Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition 179 Chapter 6 • Processing Collections of Data element is a variable representing a property associated with the collection (or object). Look at the following example: Dim objFsoObject, objFolderName, strMember, strFileList, strTargetFolder Set objFsoObject = CreateObject(“Scripting.FileSystemObject”) Set objFolderName = objFsoObject.GetFolder(“C:\Temp”) For Each strMember in objFolderName.Files strFileList = strFileList & strMember.name & vbCrLf Next MsgBox strFileList, ,”List of files in “ & objFolderName This example begins by defining its variables and then establishing an instance of the FileSystemObject. It then uses the FileSystemObject object’s GetFolder() method to set a ref- erence to a folder. Next, using the folder reference, a For Each Next loop processes all the files (which, in this case, are considered to be properties of the folder) stored within the folder. As the For Each Next loop executes, it builds a list of files stored within the folder and uses the vbCrLf constant to format the list in an attractive manner. The final statement displays the results, as shown in Figure 6.8. For Each Next loops also are an excellent programming tool for processing the contents of arrays. For example, the following statements are all that are needed to process and dis- play an array called astrGameArray, and to display each of its elements: For Each intCount In astrGameArray strMessage = strMessage & intCounter & vbCrLf Next WScript.Echo strMessage To learn more about arrays and see a more complete example of a script that uses the For Each Next statement, refer to the Processing Array Contents section in Chapter 4, “Constants, Variables, and Arrays.” Figure 6.8 Using a For Each Next loop to process the contents of a folder. . properties. The syntax of the For Each Next statement is as follows: For Each element In collection statements Next [element] Microsoft WSH and VBScript Programming for the Absolute Beginner, . players for their names and then use the players’ names at the end of the game to address them according to their ranks. 2. Modify the Star Trek Quiz so that it displays the correct answer for any. solidify your understand- ing of iterative programming while also learning specifically how to apply a loop using VBScript. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second

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

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

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

Tài liệu liên quan