1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft WSH and VBScript Programming for the Absolute Beginner Part 30 pps

10 129 0

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 282,1 KB

Nội dung

270 ProcessRandomNumber() DetermineIfSetIsComplete() Loop BuildDisplayString() ResetVariableDefaults() Next DisplayFinalResults() DisplaySplashScreen() ‘Procedure Section ———————————————————————————- Function SetVariableDefaults() ‘Establish default variable settings blnAllNumbersPicked = “False” blnInputValidated = “False” intNumberCount = 0 intNoOfValidPicks = 0 End Function Function ProcessScriptIniFile() Dim FsoObject ‘Sets up a reference to the FileSystemObject Dim OpenFile ‘Sets up a reference to the script’s .ini file Set FsoObject = WScript.CreateObject(“Scripting.FileSystemObject”) Dim intEquals ‘Used to parse .ini file data Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Dim strKeyName ‘Represents a key in the script’s .ini file Dim strSourceFile ‘Specifies the name of the script’s .ini file Dim strInput ‘Represents a line in the script’s .ini file strSourceFile = “LuckyLotteryNumberPicker.ini” ‘Identify script’s .ini file If (FsoObject.FileExists(strSourceFile)) Then Set OpenFile = FsoObject.OpenTextFile(strSourceFile, 1) Do Until Mid(strInput, 1, 15) = “[GameControls]” strInput = OpenFile.ReadLine Loop Do Until OpenFile.AtEndOfStream = “True” strInput = OpenFile.ReadLine If Mid(strInput, 1, 1) = “[“ Then Exit do End If If Len(strInput) <> 0 Then intEquals = Instr(strInput, “=”) strKeyName = Mid(strInput, 1, intEquals - 1) Select Case strKeyName Case “Greeting” strTitleBarMsg = Mid(strInput, intEquals + 1, Len(strInput)) Case “DisplayFormat” strDisplayType = Mid(strInput, intEquals + 1, Len(strInput)) Case “NoOfPicks” intNoOfPicksToSelect = Cint(Mid(strInput, intEquals + 1, _ Len(strInput))) Case “RangeOfNumbers” intRangeOfNumbers = Cint(Mid(strInput, intEquals + 1, _ Len(strInput))) 271 Chapter 8 • Storing and Retrieving Data 272 End Select End If Loop OpenFile.Close() Else MsgBox “The .ini file is missing. Unable to execute.” WScript.Quit() End If End Function Function CollectPlayerInput() ‘Ask player how many sets of #s to create Do Until blnInputValidated = “True” intNoOfPlays = InputBox(“How many sets of numbers do “ & _ “you want?”, strTitleBarMsg) If IsNumeric(intNoOfPlays) <> True Then MsgBox “Sorry. You must enter a numeric value. Please “ & _ “try again.”, ,strTitleBarMsg Else If Len(intNoOfPlays) = 0 Then MsgBox “Sorry. You must enter a numeric value. Please “ & _ “try again.”, ,strTitleBarMsg Else If intNoOfPlays = 0 then MsgBox “Sorry. Zero is not a valid selection. Please “ & _ “try again.”, ,strTitleBarMsg Else blnInputValidated = “True” End If Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition End If End If Loop End Function Function GetRandomNumber() ‘Generate a random number Randomize intRandomNo = cInt(FormatNumber(Int((intRangeOfNumbers * Rnd) + 1))) End Function Function ProcessRandomNumber() ‘Prevent the selection of duplicate # Select Case intRandomNo Case aintLotteryArray(0) Case aintLotteryArray(1) Case aintLotteryArray(2) Case aintLotteryArray(3) Case aintLotteryArray(4) Case aintLotteryArray(5) Case aintLotteryArray(6) Case aintLotteryArray(7) Case aintLotteryArray(8) Case aintLotteryArray(9) Case aintLotteryArray(10) Case Else strLotteryList = strLotteryList & “ “ & intRandomNo & vbTab intNoOfValidPicks = intNoOfValidPicks + 1 aintLotteryArray(intNumberCount) = intRandomNo intNumberCount = intNumberCount + 1 End Select 273 Chapter 8 • Storing and Retrieving Data 274 End Function Function DetermineIfSetIsComplete ‘Determine if we have a full set of #s If intNoOfValidPicks = intNoOfPicksToSelect Then blnAllNumbersPicked = “True” End If End Function Function BuildDisplayString() ‘Assemble a string to display lottery #s strLotteryList = intSetCount & “)” & vbTab & strLotteryList strDisplayString = strDisplayString & strLotteryList & _ vbCrLf & vbCrLf & vbCrLf End Function Function ResetVariableDefaults() ‘Reset variables in order to prepare ‘for the selection of the next set of #s blnAllNumbersPicked = “False” intNoOfValidPicks = 0 intNumberCount = 0 strLotteryList = “” End Function Function DisplayFinalResults() ‘Display game’s randomly generated #s If strDisplayType = “Full” Then MsgBox vbCrLf & _ “L U C K Y L O T T E R Y N U M B E R P I C K E R” & _ Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition vbCrLf & vbCrLf & _ “——————————————————————————-” & _ “——————————————-” & vbCrLf & vbCrLf & _ “Number of plays: “ & intNoOfPlays & vbCrLf &vbCrLf & _ “Number of picks per play: “ & intNoOfPicksToSelect & _ vbCrLf & vbCrLf & _ “——————————————————————————-” & _ “——————————————-” & vbCrLf & vbCrLf & vbCrLf & _ “Your lottery numbers are: “ & vbCrLf & vbCrLf & vbCrLf & _ strDisplayString, , strTitleBarMsg Else MsgBox vbCrLf & _ “L U C K Y L O T T E R Y N U M B E R P I C K E R” & _ vbCrLf & vbCrLf & _ “——————————————————————————-” & _ “——————————————-” & vbCrLf & vbCrLf & _ “Your lottery numbers are: “ & vbCrLf & vbCrLf & vbCrLf & _ strDisplayString, , strTitleBarMsg End If End Function Function DisplaySplashScreen() ‘Display splash screen and terminate game MsgBox “Thank you for using the Lucky Lottery Number Picker “ & _ “© Jerry Ford 2004.” & vbCrLf & vbCrLf & “Please play again “ & _ “soon!”, 4144, strTitleBarMsg WScript.Quit() End Function Okay. Why don’t you crank it up and see how it works. After you’ve cleaned out any errors that you might have made when typing, you’ll have a pretty cool script. 275 Chapter 8 • Storing and Retrieving Data 276 Summary In this chapter, you learned how to create and store data in text files. You also learned how to open text files and read or process their contents as input. You also learned how to use properties and methods belonging to the WSH FileSystemObject to perform assorted file administration tasks, including copying, moving, and deleting individual and groups of files and folders. You now understand the fundamentals of working with files and folders and know every- thing you need to begin developing scripts that can create reports and log files. On top of all this, you also can now develop and leverage the power of INI files as a repository for exter- nalizing script configuration settings. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition C HALLENGES 1. As it is currently written, the Lucky Lottery Number Picker game attempts to dis- play as many sets of lottery numbers as it is asked for. However, depending on the screen resolution, only so many sets of numbers can be displayed at one time. The result is that when too many sets of numbers are specified, some won’t be visible to the player. To remedy this, modify the script so that it will only display 10 sets of numbers at a time using as many pop-up dialogs as required to display all the script’s output. 2. Provide the player with the capability to save the lottery numbers generated by the game to a text file. This allows players to print their numbers and take the list with them when they go to purchase their lottery tickets. 3. The Lucky Lottery Number Picker game is set up so that it always displays a closing splash screen before ending. Modify the script and its associated INI file so that the player can enable or disable the display of the splash screen. 4. As it is currently written, the Lucky Lottery Number Picker game prevents the player from entering nonnumeric input such as letters and special characters. It also forces the player to enter something (the player can’t just click on OK or Cancel). However, there is no logic in the script to prevent negative numbers from being accepted. As unlikely as it may be for the player to enter a negative number, it’s a good idea to modify the script to prevent them from being accepted anyway. Handling Script Errors 9 CHAPTER E very programmer, no matter how good he or she may be, runs into errors when writing and testing scripts and programs. Like any other program- ming language, VBScript is subject to many types of errors. Errors may be inevitable, but you can minimize their number or lessen their effects. In this chapter, I’ll demonstrate a number of scripting errors and show you how to deal with them. Specifically, you will learn how to • Fix errors by reading and analyzing error messages • Write VBScripts that can ignore errors and keep going • Create error-handling routines to recover from many error situations • Generate test errors in order to validate the performance of your error- handling routines • Keep a record of errors using log files and the Windows application event log Project Preview: The Hangman Game This chapter’s programming project is the creation of a VBScript version of the classic children’s game Hangman. Developing this game will require you to use all the VBScript knowledge that you’ve accumulated so far, including applying advanced conditional logic, organizing critical processes into procedures, and validating player input to prevent errors from prematurely terminating the game. CHAPTER 278 The Hangman game begins by presenting the player with a number of blank spaces repre- senting the letters of the game’s mystery word. The player is then allowed to begin guessing the letters that make up the word. If the player guesses the word before making six incor- rect guesses, he or she wins. Otherwise, the game ends by displaying the mystery word, and the player is asked if he or she would like to play again. Unfortunately, because of the dis- play limitations of the WSH, you won’t be able to actually animate a hanging in the event that the player loses. Still, by creating a well-formatted output, the player will probably never even notice. Figures 9.1 through 9.5 demonstrate the overall flow of the game from beginning to end. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 9.1 The Hangman game begins with a graphical welcome message and an invitation to play. Figure 9.2 The game displays both the letters that the player has correctly guessed and the letters the player has incorrectly guessed. Figure 9.3 A number of possible messages may be displayed if the player does not play the game correctly. Understanding VBScript Errors Errors can appear, even in small scripts, for many reasons. Errors may be generated when a script is first loaded or interpreted. Errors occurring at this stage are referred to as syntax errors. Syntax errors are often the result of typos. For example, you might accidentally type a single quote when you meant to type a closing double quote. Syntax errors also occur when you inadver- tently mistype a VBScript keyword. Because syntax errors are discovered during the initial loading of a script, they are usually easily caught and corrected during script development. Errors can also be generated during script execution. These types of errors are referred to as run-time errors. Run-time errors only appear when the statements that generate them are executed. As a result, some run-time errors might not be detected when the script executes (if the statement containing the error is not executed). For example, a run-time error might be hidden deep within a function or subroutine that is seldom called. 279 Chapter 9 • Handling Script Errors Figure 9.4 Each game ends by displaying the hidden word, the results of the game, and an invitation to play again. Figure 9.5 A splash screen is displayed when the player decides to stop playing. Definition A syntax error is an error that occurs as a result of improperly formatted statements within scripts. Definition A run-time error is an error that occurs when a script tries to perform an illegal action, such as multiplying a numeric and a character value. . data Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Dim strKeyName ‘Represents a key in the script’s .ini file Dim strSourceFile ‘Specifies the name of the script’s. through 9.5 demonstrate the overall flow of the game from beginning to end. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 9.1 The Hangman game begins. repository for exter- nalizing script configuration settings. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition C HALLENGES 1. As it is currently written, the Lucky

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

TỪ KHÓA LIÊN QUAN