Microsoft WSH and VBScript Programming for the Absolute Beginner Part 36 potx

10 206 0
Microsoft WSH and VBScript Programming for the Absolute Beginner Part 36 potx

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

Thông tin tài liệu

330 Creating the Setup Script In stage 1, you’ll create a VBScript called HangmanSetup.vbs. This script will create and store a Registry key called Hangman in the HKEY_CURRENT_USER root key (referred to in the script as HKCU). Within this key, a value called ListLocation will be created and assigned a string iden- tifying the location where you plan to store your Hangman word files. The HangmanSetup.vbs script will be developed in three steps. 1. Create a new script, adding your VBScript template and defining the variables and objects used by this VBScript. 2. Set up the controlling logic in the Main Processing Section, first prompting for con- firmation before continuing, and then finally calling the procedure that creates the Registry key and value. 3. Set up the Procedure Section by adding the SetHangmanKeyAndValue() function, which performs the actual modification of the Registry. Defining Variables and Objects By now, this step should be very familiar to you. Begin by copying over your VBScript tem- plate and filling in information about the new script. ‘************************************************************************* ‘Script Name: HangmanSetup.vbs ‘Author: Jerry Ford ‘Created: 12/14/02 ‘Description: This script configures Registry entries for the Hangman.vbs ‘game. ‘************************************************************************* ‘Initialization Section Option Explicit Next, define the variables and objects required by the script. As you can see here, this is a very simple script, with only a few items that need to be defined: Dim objWshShl, intResponse Set objWshShl = WScript.CreateObject(“WScript.Shell”) The first variable represents the WshShell object, and the second variable stores the user’s response when asked whether he or she wants to make the Registry change. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition 331 Chapter 10 • Using the Windows Registry to Configure Script Settings Get Confirmation First The Main Processing Section prompts the user for confirmation and then tests the results returned by the InputBox() function before proceeding. If the value returned is equal to 6, then the user elected to continue. Otherwise, the WScript object’s Quit() method terminates script execution. ‘Main Processing Section ‘Ask for confirmation before proceeding intResponse = MsgBox(“This VBScript establishes registry settings “ & _ “for the Hangman game. Do you wish to continue?”, 4) If intResponse = 6 Then SetHangmanKeyAndValue() End If WScript.Quit() Modify the Registry The final step in creating this script is to define a function that creates the new Registry key and value. As you saw earlier in this chapter, this operation is accomplished using the WshShell object’s RegWrite() method. When deciding what Registry key and value to create in situations like this, it’s critical that you take steps to ensure that you don’t accidentally overwrite an already existing key or value of the same name. Otherwise, you might acciden- tally disable another application or even a Windows component. In the case of this script, it’s virtually certain that the key and value I defined will not be in use. However, if there is any doubt, you can add logic to your VBScripts that first check to determine whether the key and value already exist before proceeding. ‘Procedure Section Function SetHangmanKeyAndValue() objWshShl.RegWrite “HKCU\VBGames\Hangman\ListLocation”, “c:\Hangman” End Function TRAP 332 Assembling the Entire Setup Script Now let’s put the three sections of this script together; then run the script and click on Yes when prompted for confirmation. If you want to, you can use the Regedit utility to go behind your script and make sure that it created the new Registry key and value as expected. ‘************************************************************************* ‘Script Name: HangmanSetup.vbs ‘Author: Jerry Ford ‘Created: 12/14/02 ‘Description: This script configures Registry entries for the Hangman.vbs ‘game. ‘************************************************************************* ‘Initialization Section Option Explicit Dim objWshShl, intResponse Set objWshShl = WScript.CreateObject(“WScript.Shell”) ‘Main Processing Section ‘Ask for confirmation before proceeding intResponse = MsgBox(“This VBScript establishes registry settings “ & _ “for the Hangman game. Do you wish to continue?”, 4) If intResponse = 6 Then SetHangmanKeyAndValue() End If WScript.Quit() ‘Procedure Section Function SetHangmanKeyAndValue() Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition objWshShl.RegWrite “HKCU\VBGames\Hangman\ListLocation”, “c:\Hangman” End Function You only need to run this script one time to set up a computer to play the Hangman game. However, you need to modify and rerun this script if you decide to change the location of the folder in which you plan to store your Hangman word files. Updating the Hangman Game In this second part of the project’s development, you will modify the original Hangman script so that it retrieves from the Registry the location of the folder that stores the Hang- man word files. You’ll also add logic that enables the script to open and read the contents of the word files. To accomplish this goal, the original Hangman script needs to be modified in five steps. 1. Open the Hangman script and modify its Initialization Section to include additional variables and object references required to support the script’s new functionality. 2. Delete the FillArray() function, which was responsible for retrieving a randomly selected word from an internal array, from the script. 3. Modify the RetrieveWord() function to call two new functions, GetWordFileLocation() and SelectAWordCategory(). Add logic that processes the word file specified by the player to randomly select a game word. 4. Create the GetWordFileLocation() function, which retrieves the location of the folder where the word files are stored from the Windows Registry. 5. Create the SelectAWordCategory() function, which presents the player with a list of word categories based on the word files that it finds in the folder. You should make a copy of your current Hangman script and modify the copy instead of the original script. This way, if something goes wrong, you’ll still have your original working version of the game to play. Updating the Initialization Section You need to make several changes to the Hangman script’s Initialization Section. These include defining new variables used by new portions of the script. These variables appear in boldface in the following: ‘Initialization Section TRICK 333 Chapter 10 • Using the Windows Registry to Configure Script Settings 334 Option Explicit Const cTitlebarMsg = “VBScript HANGMAN” Dim strChoice, strGameWord, intNoMisses, intNoRight, strSplashimage Dim intPlayOrNot, strMsgText, intPlayAgain, strWrongGuesses Dim strRightGuesses, blnWordGuessed, intLetterCounter Dim strTempStringOne, strTempStringTwo, strWordLetter, strDisplayString Dim strFlipCounter, intRandomNo, strProcessGuess, blnGameStatus Dim strCheckAnswer, objWshShl, strGameFolder, objFsoObject, objGameFiles Dim strSelection, strFileString, strCharactersToRemove Dim blnValidResponse, strSelectCategory, strInputFile, strWordFile Dim intNoWordsInFile, intLinesInFile, strWordList In addition, you need to delete the following statement because the array that held the game words used in the original version of the script is no longer supported: Dim astrWordList(9) ‘Define an array that can hold 10 game words Finally, you need to instantiate both the FileSystemObject and the WshShell object like this: ‘Set up an instance of the FileSystemObject Set objFsoObject = CreateObject(“Scripting.FileSystemObject”) ‘Set up an instance of the WshShell object Set objWshShl = WScript.CreateObject(“WScript.Shell”) Methods and properties belonging to the FileSystemObject object are required to read and process the words stored in the game’s word files. In addition, the WshShell object’s RegRead() method is needed to retrieve the location of the folder where the game’s word files are stored. Removing Obsolete Statements The next thing to do is delete the FillArray() function, shown next, from the VBScript. Before doing so, copy and paste each of the words defined by this array into a blank Notepad file, each on its own separate line. Save the file in a folder called Hangman on your com- puter’s C: drive and name the file General.txt (that is, save it as C:\Hangman\General.txt). This text file will be used to retrieve game words for the new and improved version of the game. Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition FillArray() Function FillArray() ‘Add the words to the array astrWordList(0) = “AUTOMOBILE” astrWordList(1) = “NETWORKING” astrWordList(2) = “PRACTICAL” astrWordList(3) = “CONGRESS” astrWordList(4) = “COMMANDER” astrWordList(5) = “STAPLER” astrWordList(6) = “ENTERPRISE” astrWordList(7) = “ESCALATION” astrWordList(8) = “HAPPINESS” astrWordList(9) = “WEDNESDAY” End Function While you’re at it, you might want to create one or two other word files, give them names that describe their contents, and then save them in the Hangman folder. This way, the player will have more than one category of words to choose from when playing the game. Modifying the RetrieveWord() Function You should begin modifying the RetrieveWord() function by first deleting all its statements and then adding the statements shown next. As you can see, I have added a number of com- ments to this code to explain its construction in detail. ‘This function retrieves a randomly selected word from a word file Function RetrieveWord() ‘Locate the folder where collections of game words are stored strGameFolder = GetstrWordFileLocation() ‘Get the player to select a word category strSelectCategory = SelectAWordCategory(strGameFolder) ‘Create the complete path and file name for the selected word file strInputFile = strGameFolder & “\” & strSelectCategory ‘Open the file for reading 335 Chapter 10 • Using the Windows Registry to Configure Script Settings 336 Set strWordFile = objFsoObject.OpenTextFile(strInputFile, 1) ‘Set this variable to zero. It represents the No of words in the file intNoWordsInFile = 0 ‘Count the number of words in the file Do while False = strWordFile.AtEndOfStream ‘Read a line strWordFile.ReadLine() ‘Keep count of the number of words (or lines) read intNoWordsInFile = intNoWordsInFile + 1 ‘If the loop iterates more than 50 times something is wrong If intNoWordsInFile > 50 Then Exit Do End If Loop ‘Close the file when done counting the number of words (or lines) strWordFile.Close ‘Pick a random number between 1 and the number of words in the file Randomize intRandomNo = FormatNumber(Int((intNoWordsInFile + 1) * Rnd),0) ‘Open the file for reading Set strWordFile = objFsoObject.OpenTextFile(strInputFile, 1) ‘Skip the reading of all words prior to the randomly selected word For intLinesInFile = 1 to intRandomNo - 1 ‘Read the randomly selected word strWordFile.SkipLine() Next ‘Return the randomly selected word to the calling statement RetrieveWord = strWordFile.ReadLine() ‘Close the file when done strWordFile.Close End Function Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Create the GetWordFileLocation() Function The RetrieveWord() function calls upon the GetWordFileLocation() function, shown here, to retrieve the location of the folder where the Hangman game’s word files are stored (that is, the function retrieves the information stored in the Windows Registry by the HangmanSetup.vbs script). ‘This function retrieves the location of folder where word files are stored Function GetstrWordFileLocation() ‘Get the folder name and path from its assigned Registry value GetstrWordFileLocation = _ objWshShl.RegRead(“HKCU\VBGames\Hangman\ListLocation”) End Function Create the SelectAWordCategory() Function The RetrieveWord() function also calls upon the SelectAWordCategory() function, shown next, to prompt the player to select a word category from which the game’s mystery word should be randomly selected. This function takes one argument, TargetFolder, which is the location of the folder where the word files are stored. The function then displays a list of word categories based on the word files stored in the folder and prompts the player to select one. If the player fails to make a selection, the function automatically specifies the General category as the default. Again, I’ve added plenty of comments to the function to document its construction. ‘This function returns a word category Function SelectAWordCategory(TargetFolder) ‘Specify the location of the folder that stores the word files Set strGameFolder = objFsoObject.GetFolder(TargetFolder) ‘Get a list of files stored in the folder Set objGameFiles = strGameFolder.Files strSelection = “” ‘Loop through the list of word files For Each strWordList In objGameFiles 337 Chapter 10 • Using the Windows Registry to Configure Script Settings 338 ‘Build a master string containing a list of all the word files strFileString = strFileString & strWordList.Name ‘Remove the .txt portion of each file’s file name. strCharactersToRemove = Len(strWordList.Name) - 4 ‘Build a display string showing the category names of each word file strSelection = strSelection & _ Left(strWordList.Name, strCharactersToRemove) & vbCrLf Next blnValidResponse = “False” ‘Loop until a valid category strSelection has been made Do Until blnValidResponse = “True” ‘Prompt the player to select a word category strChoice = InputBox(“Please specify the name of a word category “ & _ “from which game words will be selected.” & vbCrLf & vbCrLf & _ “Available Categories:” & vbCrLf & vbCrLf & _ strSelection, “Pick a Category” , “General”) ‘If input is not in master string the player must try again If InStr(UCase(strFileString), UCase(strChoice)) = 0 Then MsgBox “Sorry but this is not a valid category. Please try again.” Else blnValidResponse = “True” End If Loop ‘If the player typed nothing then specify a default word category If Len(strChoice) = 0 Then strChoice = “General” End If ‘Add the .txt portion of the file name back SelectAWordCategory = strChoice & “.txt” End Function Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Viewing the Completed Hangman Script That’s it! Your new and improved version of the Hangman script, shown next, should be ready for testing. Don’t forget to test it thoroughly and to have someone else test it as well. ‘************************************************************************* ‘Script Name: Hangman-2.vbs ‘Author: Jerry Ford ‘Created: 12/14/02 ‘Description: This is a Registry-enabled version of Hangman.vbs. ‘************************************************************************* ‘Initialization Section Option Explicit Const cTitlebarMsg = “VBScript HANGMAN” Dim strChoice, strGameWord, intNoMisses, intNoRight, strSplashimage Dim intPlayOrNot, strMsgText, intPlayAgain, strWrongGuesses Dim strRightGuesses, blnWordGuessed, intLetterCounter Dim strTempStringOne, strTempStringTwo, strWordLetter, strDisplayString Dim strFlipCounter, intRandomNo, strProcessGuess, blnGameStatus Dim strCheckAnswer, objWshShl, strGameFolder, objFsoObject, objGameFiles Dim strSelection, strFileString, strCharactersToRemove Dim blnValidResponse, strSelectCategory, strInputFile, strWordFile Dim intNoWordsInFile, intLinesInFile, strWordList ‘Set up an instance of the FileSystemObject Set objFsoObject = CreateObject(“Scripting.FileSystemObject”) ‘Set up an instance of the WshShell object Set objWshShl = WScript.CreateObject(“WScript.Shell”) ‘Main Processing Section intPlayOrNot = DoYouWantToPlay() If intPlayOrNot = 6 Then ‘User elected to play the game PlayTheGame() 339 Chapter 10 • Using the Windows Registry to Configure Script Settings . WScript.CreateObject(“WScript.Shell”) The first variable represents the WshShell object, and the second variable stores the user’s response when asked whether he or she wants to make the Registry change. Microsoft WSH and VBScript. done strWordFile.Close End Function Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Create the GetWordFileLocation() Function The RetrieveWord() function calls upon the GetWordFileLocation(). “.txt” End Function Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition Viewing the Completed Hangman Script That’s it! Your new and improved version of the Hangman script,

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

Từ khóa liên quan

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

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

Tài liệu liên quan