Microsoft WSH and VBScript Programming for the Absolute Beginner Part 39 pot

10 188 0
Microsoft WSH and VBScript Programming for the Absolute Beginner Part 39 pot

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

Thông tin tài liệu

360 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Function ProcessFirstHero() Set objFirstHero = New SuperHero ‘Instantiate a new SuperHero object objFirstHero.Name = “Captain Adventure” ‘Assign value to Name property objFirstHero.Power = “Laser Vision” ‘Assign value to Power property objFirstHero.Weakness = “Dog Whistle” ‘Assign value to Weakness property objFirstHero.Identity = “Bruce Tracy” ‘Assign value to Identity property objFirstHero.DisplayIdentity() ‘Execute the SuperHero object’s method End Function Function ProcessSecondHero() Set objSecondHero = New SuperHero objSecondHero.Name = “Captain Marvelous” ‘Assign value to Name property objSecondHero.Power = “Lightning Speed” ‘Assign value to Power property objSecondHero.Weakness = “Blue Jello” ‘Assign value to Weakness property objSecondHero.Identity = “Rob Denton” ‘Assign value to Identity property objsecondHero.DisplayIdentity() ‘Execute the SuperHero object’s method End Function Class SuperHero Private strName, strPower, strWeakness, strIdentity ‘Define variables ‘used by this class Public Property Let Name(strIdentity) ‘Define the Name property strName = strIdentity End property Public Property Let Power(strSuperPower) ‘Define the Power property strPower = strSuperPower End property Public Property Let Weakness(strHurtBy) ‘Define the Weakness property strWeakness = strHurtBy End property Public Property Let Identity(strSecretIdentity) ‘Define the Identity strIdentity = strSecretIdentity ‘property End property Function DisplayIdentity ‘This function defines the SuperHero object’s ‘DisplayIdentity() method MsgBox strName & vbCrLf & vbCrLf & _ “Hero Power: “ & vbTab & strPower & vbCrLf & _ “Hero Weakness: “ & vbTab & strWeakness & vbCrLf & _ “Hero Identity: “ & vbTab & strIdentity End Function Private Sub Class_Initialize ‘This event automatically executes when ‘the SuperHero object is instantiated MsgBox “In a blast of smoke and lightning another new super “ & _ “hero is born!” End Sub End Class As the script runs, pop-up dialogs will be displayed as shown in Figures 11.8 and 11.9 demon- strating the execution of the Class_Initialize event and the object’s DisplayIdentity() method. 361 Chapter 11 • Working with Built-In VBScript Objects Figure 11.8 The Class_Initialize event occurs every time a new instance of the SuperHero object is established. 362 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Working with the Err Object The Err object provides access, via its properties, to information about run-time errors. For example, using the Err object’s Description property you can retrieve a string containing an error’s description. Using the Err object’s Number property you can retrieve the error number associated with an error and using the Err object’s Source property you can retrieve the name of the resource that reported the error. The Err object also provides access to two methods. The Clear() method clears out the prop- erties belonging to the Err object. This is handy in situations where you can develop an effective error handling routine that enables your script to recover from an error and keep running. The Raise() method is equally useful, giving you the capability to simulate run- time errors so that you can test out your script’s error handling procedures. For additional information and examples on how to work with the Err object, refer to Chapter 9, “Handling Script Errors.” Working with Regular Expressions All remaining VBScript built-in objects and collections deal with regular expressions. A regular expression is a pattern consisting of characters and metacharacters. Regular expressions are used as a means of searching and replacing patterns within strings. The first step in preparing your VBScripts to work with regular expressions is to instantiate the RegExp object. This object provides access to the remaining built-in VBScript objects. The RegExp object is instantiated as follows: Dim objRegExp Set objRegExp = New RegExp Figure 11.9 The SuperHero object’s Display Identity() method displays the value of all properties assigned to an instance of an object. The RegExp object provides access to the following properties: • Pattern. Identifies the pattern to be matched. • IgnoreCase. Contains a value of True or False depending on whether a case-sensitive search is performed. • Global. An optional Boolean value used to specify whether all occurrences of the spec- ified pattern are to be replaced. The RegExp object provides access to several methods, including: • Replace(). Replaces matching string patterns. • Test(). Performs a pattern search, generating a Boolean value based on whether a match is found. • Execute(). Provides the ability to generate a Matches collection. Replacing Matching Patterns Using the RegExp object’s Replace() method, you can replace matching patterns within a string. The syntax for this method is RegExp.Replace(String1, String2) String1 identifies the string to search and String2 identifies the replacement string. To demonstrate how to work with the Replace() method, look at the following example: Dim objRegExp Set objRegExp = New RegExp objRegExp.Pattern = “planet” MsgBox objRegExp.Replace(“A long time ago on a far away planet”, “world”) In this example, a variable name objRegExp is defined, and then used to instantiate a refer- ence to the RegExp object. Next a value of planet is assigned to the RegExp object’s Pattern property to define a search pattern. Finally, the Replace() method is used to force the replacement of the word planet with the word world. Figure 11.10 shows the output gener- ated when this example is run. 363 Chapter 11 • Working with Built-In VBScript Objects 364 By default, the Replace() method only replaces the first occurrence of a match within the specified search string. However, by setting the value of the RegExp object’s Global property to True you can force the replacement of all matching patterns. To see this in action, mod- ify the previous example as follows. Dim objRegExp Set objRegExp = New RegExp objRegExp.Pattern = “planet” objRegExp.Global = “True” MsgBox objRegExp.Replace(“A long time ago on a far away planet”, “world”) VBScript’s support for regular expres- sions includes the capability to define a host of complex pattern matches through the use of metacharacters. Table 11.3 lists all the metacharacters supported by VBScript. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 11.10 Using regular expression matching you can substitute a portion of any string. Definition A metacharacter is a special character used to provide information about other characters. In the case of regu- lar expression, metacharacters specify how a matching pattern is to be processed. Character Description \ Sets the next character as a special character, a back reference, a literal, or an octal escape ^ Matches the beginning of the input string $ Matches the end of the input string * Matches the preceding expression (zero or more times) TABLE 11.3 VBSCRIPT REGULAR EXPRESSION METACHARACTERS 365 Chapter 11 • Working with Built-In VBScript Objects Character Description + Matches the preceding expression (one or more times) ? Matches the preceding expression (zero or one time) {n} Matches exactly n times {n,} Matches a minimum of n times {n,m} Matches a minimum of n times and a maximum of m times . Matches any individual character except the newline character (pattern) Matches a pattern and allows the matched substring to be retrieved from the Matches collection. x|y Matches x or y [xyz] Matches any of the specified characters [^xyz] Matches any character except those specified [a-z] Matches character specified in the range [^a-z] Matches character except for those specified in the range \b Matches on a word boundary \B Matches on a non-word boundary \cx Matches the control character specified as x \d Matches a single digit number \D Matches any single non-numeric character \f Matches the form-feed character \n Matches the newline character \r Matches the carriage return character \s Matches any white space character (for example, space, tab, form-feed) \S Matches any non-white-space character \t Matches the tab character \v Matches the vertical tab character \w Matches any word character \W Matches any non-word character \xn Matches n, where n is a two-digit hexadecimal escape value TABLE 11.3 VBSCRIPT R EGULAR E XPRESSION M ETACHARACTERS ( CONTINUED) (continues) 366 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Character Description \num Matches num, where num is a positive integer in a backward reference to captured matches \n Specifies an octal escape value or a back reference \nml Matches octal escape value nml where n is an octal digit in the range of 0–3 and m and l are octal digits in the range of 0–7 \un Matches n, where n is a four-digit hexadecimal Unicode character TABLE 11.3 VBSCRIPT R EGULAR E XPRESSION M ETACHARACTERS ( CONTINUED) To better understand how to take advantage of metacharacters, take a look at the following example: Dim objRegExp Set objRegExp = New RegExp objRegExp.Pattern = “[\d]” objRegExp.Global = “True” MsgBox objRegExp.Replace(“1 years ago on a far away planet”, “1000”) In this example, specifying the \d metacharacter as the value assigned to the RegExp object’s Pattern property results in a replacement operation where any single numeric character is identified as a match. Figure 11.11 shows the output generated when you run this example. As you can see, in this example the number 1 is replaced by the number 1000. Testing for Matching Patterns The RegExp object’s Test() method performs a pattern match without actually performing a replacement operation. The syntax for the Test() method is RegExp.Test(string) The following statements demonstrate how to use this method. In this example, the script displays one of two messages, depending on whether the string assigned to the Pattern prop- erty is found within the search string. Dim objRegExp Set objRegExp = New RegExp objRegExp.Pattern = “planet” If objRegExp.Test(“A long time ago on a far away planet”) = “True” Then MsgBox “The word “ & objRegExp.Pattern & “ was found!” Else MsgBox “The word “ & objRegExp.Pattern & “ was not found!” End If Creating Matches Collections Using the RegExp object’s Execute() method, you can generate a Matches collection as a result of a regular expression search. The syntax of the Execute() method is RegExp.Execute(string) Once generated, the Matches collection is read-only. It is made up of individual Match objects. Each Match object has its own set of properties, which include: • FirstIndex. Retrieves the starting character positions of a match within a string • Length. Returns the length of a match found within a string • Value. Retrieves the text of the match found within a string Once a Matches collection has been generated, you can process all the members of the col- lection using a loop, as demonstrated by the next example. Dim objRegExp, objMatchCollection, objMatch, strStory, strDisplayMsg Set objRegExp = New RegExp 367 Chapter 11 • Working with Built-In VBScript Objects Figure 11.11 Using metacharacters enables you to perform complex substitutions. 368 objRegExp.Pattern = “bear” objRegExp.Global = “True” strStory = “Once upon a time there were three little bears. There “ & _ “was mama bear, papa bear and baby bear. There was cousin bear too!” Set objMatchCollection = objRegExp.Execute(strStory) For Each objMatch in objMatchCollection strDisplayMsg = strDisplayMsg & “An instance of “ & _ objRegExp.Pattern & “ found at position “ & objMatch.FirstIndex & _ vbCrLf Next MsgBox strDisplayMsg In this example, a For Each Next loop was set up to process each Match object in the col- lection. The Match object’s FirstIndex property was used to retrieve the starting position of each matching pattern in the search string, which was then used to generate the output shown in Figure 11.12. Back to the Tic-Tac-Toe Game The heart of the Tic-Tac-Toe game lies in the design of its game board, which is divided into three sections. Status and error messages are displayed at the top of the board to assist play- ers when mistakes are made playing the game. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Figure 11.12 Using the RegExp objects Execute() method to generate and process the contents of a Matches collection. 369 Chapter 11 • Working with Built-In VBScript Objects In the middle of the board is an image of a traditional Tic-Tac-Toe board. To the right and top of the Tic-Tac-Toe board are letters and numbers, the coordinates of each cell that make up the game board. Players play the game by using these letters and numbers to specify what cell they want to select as their next move. Embedded within the board are variables representing each cell on the board. The values assigned to these variables are set to either an X or O based on the moves made by each player as the game progresses. The bottom of the game board is made up of an input text field that enables players to enter their moves. In addition, instruction is provided just above this text field in the form of a text message that is used to keep track of player turns. Designing the Game Besides its Initialization and Main Processing sections, the game is made up of nine func- tions. Each function performs a specific task. Here is a list of the script’s functions along with a brief description of their associated tasks: • SetVariableDefaults(). Establishes default values for various script variables. • ClearGameBoard(). Resets each cell on the Tic-Tac-Toe game board so that it appears as blank or empty. • ManageGamePlay(). Controls the overall execution of the game, calling on other func- tions as necessary. • DisplayBoard(). Displays the game board along with instruction, error messages, and any moves already made by each player. • DisplayGameResults(). Displays the final results of each game, identifying who won or whether the game results in a tie. • ValidateInput(). Ensures that players are only allowed to enter valid cell coordinates when taking their turns. • MarkPlayerSelection(). Associates input provided by players with the appropriate cell coordinates on the game board. • SeeIfWon(). Checks the game board to determine whether a player has won or whether the game has ended in a tie. • DisplaySplashScreen(). Displays information about the script and its author. Setting Up the Script’s Template and Initialization Section The Tic-Tac-Toe game begins by defining the constants and variables used by the game. Because the game uses a large number of variables, I embedded comments to the right of each variable to identify its purpose. . sections. Status and error messages are displayed at the top of the board to assist play- ers when mistakes are made playing the game. Microsoft WSH and VBScript Programming for the Absolute Beginner, . time a new instance of the SuperHero object is established. 362 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Working with the Err Object The Err object provides. 360 Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Function ProcessFirstHero() Set objFirstHero = New SuperHero ‘Instantiate a new SuperHero object objFirstHero.Name

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

Từ khóa liên quan

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

Tài liệu liên quan