‘The Player wants to quit the gameIf strProcessGuess = “ExitFunction” Then Exit Function End If ‘The player typed invalid input If strProcessGuess “SkipRest” Then strProcessGuess = Seco
Trang 1‘The Player wants to quit the game
If strProcessGuess = “ExitFunction” Then
Exit Function
End If
‘The player typed invalid input
If strProcessGuess <> “SkipRest” Then
strProcessGuess = SecondLevelValidation()
Select Case strProcessGuess
Case “DuplicateWrongAnswer”
MsgBox “Invalid: You’ve already guessed this incorrect letter.” Case “DuplicateRightAnswer”
MsgBox “Invalid: You’ve already guessed this correct letter.”
Case Else
strCheckAnswer = TestLetterGuess()
If strCheckAnswer <> “IncorrectAnswer” Then
‘Reset the value of variable used to build a string containing
‘the interim stage of the word as currently guessed by player strTempStringTwo = “”
NonGuessedString()
‘Check to see if the player has guessed the word
blnGameStatus = CheckIfGameWon()
If blnGameStatus = “True” Then
blnWordGuessed = “True”
Exit Do End If
‘Set the value of the temporary string equal to the string
‘created by the Previous For Next loop
strTempStringOne = strTempStringTwo
‘Clear out the value of the strDisplayString variable
Trang 2strDisplayString = “”
FlipString()
End If
End Select
End If
Loop
DisplayGameResults()
End Function
Building the RetrieveWord() Function
This function is designed to retrieve a randomly selected word to be used by the game. RetrieveWord()first selects a random number between 1 and 10, and then uses that number
to retrieve a game word from the WordList()array This function randomly retrieves a word from an array.
Function RetrieveWord()
Randomize
intRandomNo = FormatNumber(Int(10 * Rnd))
RetrieveWord = astrWordList(intRandomNo)
End Function
This is a good place to perform another test This time, open the temporary script that you created a little earlier and cut and paste it into the statements located in the previous func-tion Paste the three statements into the temporary file, making them lines 3 though 5 in the script Next, add the following statement as line 6:
MsgBox RetrieveWord
Save and run the script Each time you execute the temporary script, a different randomly selected word should be displayed If this is not the case, then something is wrong Locate and fix any errors that may occur until the temporary script works as expected Then, cut and paste any corrected script statements back into your Hangman script and move on to the next section.
Trang 3Building the InitialDisplayString() Function
This function is used to display a series of underscore characters representing each letter that makes up the mystery game word:
Function InitialDisplayString()
‘Create a loop that processes each letter of the word
For intLetterCounter = 1 to Len(strGameWord)
‘Use underscore characters to display a string representing each
‘letter
InitialDisplayString = InitialDisplayString & “_ “
Next
End Function
You can run a quick test of this function by creating a new temporary VBScript, cutting and pasting the statements from within this function into the temporary script, and modifying it.
For intLetterCounter = 1 to Len(“DOG”)
‘Use underscore characters to display a string representing each letter
InitialDisplayString = InitialDisplayString & “_ “
Next
MsgBox InitialDisplayString
You should see three underscore characters separated by blank spaces, indicating the length
of the word If anything is wrong, fix it and then copy the corrected statement(s) back into the Hangman script.
Building the FirstLevelValidation() Function
The FirstLevelValidation()function, shown next, ensures that the player is providing valid input It checks to make sure that the player typed in something, that the player did not type in more than one character, and that a number was not provided as input.
‘Validate the player’s input
Function FirstLevelValidation()
‘See if the player clicked on Cancel or failed to enter any input
If strChoice = “” Then
Trang 4FirstLevelValidation = “ExitFunction”
Exit Function
End If
‘Make sure the player only typed 1 letter
If Len(strChoice) > 1 Then
MsgBox “Invalid: You must only enter 1 letter at a time!”
FirstLevelValidation = “SkipRest”
Else
‘Make sure the player did not type a number by accident
If IsNumeric(strChoice) = “True” Then
MsgBox “Invalid: Only letters can be accepted as valid input!”
FirstLevelValidation = “SkipRest”
Else
FirstLevelValidation = “Continue”
End If
End If
End Function
Building the SecondLevelValidation() Function
Like the previous function, the SecondLevelValidation() function, shown here, performs additional tests on the player’s guess to make sure that the player is not trying to guess the same letter twice.
Function SecondLevelValidation()
‘Check to see if this letter is already on the incorrectly guessed list
If Instr(1, strWrongGuesses, UCase(strChoice), 1) <> 0 Then
SecondLevelValidation = “DuplicateWrongAnswer”
Else
‘Check to see if this letter is already on the correctly guessed list
If Instr(1, strRightGuesses, UCase(strChoice), 1) <> 0 Then
SecondLevelValidation = “DuplicateRightAnswer”
End If
End If
End Function
Trang 5Building the TestLetterGuess() Function
The TestLetterGuess()function, shown here, checks to see whether the letter is part of the word and keeps track of missed guesses If the total number of missed guesses equals 6, then this function assigns a value of Falseto the blnWordGuessedvariable This variable is a flag that is later checked to see whether the player has lost the game.
Function TestLetterGuess()
If Instr(1, UCase(strGameWord), UCase(strChoice), 1) = 0 Then
‘Add the letter to the list of incorrectly guessed letters
strWrongGuesses = strWrongGuesses & “ “ & UCase(strChoice)
‘Increment the number of guesses that the player has made by 1
intNoMisses = intNoMisses + 1
‘If the player has missed 6 guesses then he has used up all chances
If intNoMisses = 6 Then
blnWordGuessed = “False”
End If
TestLetterGuess = “IncorrectGuess”
Else
TestLetterGuess = “CorrectGuess”
End If
End Function
Building the NonGuessedString() Function
This game displays as a string the letters that make up the game’s mystery word and uses VBScript string manipulation functions to control the display of correctly and incorrectly guessed letters As I was creating the game, I wanted an easy way of seeing what game word had been randomly selected and of tracking which letters had yet to be guessed The NonGuessedString()function, shown next, builds a string that, if it were displayed, would show all the letters that make up the word, less the letters that the player has correctly guessed This function gave me a tool for displaying how the game was keeping track of the game word.
Function NonGuessedString()
‘Loop through the temporary string
For intLetterCounter = 1 to Len(strTempStringOne)
Trang 6‘Examine each letter in the word one at a time
strWordLetter = Mid(strTempStringOne, intLetterCounter, 1)
‘Otherwise add an underscore character indicating a nonmatching guess
If UCase(strWordLetter) <> UCase(strChoice) Then
strTempStringTwo = strTempStringTwo & strWordLetter
Else
‘The letter matches player’s guess Add it to the temporary string
intNoRight = intNoRight + 1
strRightGuesses = strRightGuesses & “ “ & UCase(strChoice)
strTempStringTwo = strTempStringTwo & “_”
End If
Next
End Function
After I developed this function, I added the following statement as the last statement in the function:
MsgBox “ **** = “ & strTempStringTwo
This way, each time the function ran, I was able to see the contents of the string For exam-ple, if the game word is DOG and the player has missed his or her first guess, this string would be displayed in a pop-up dialog as D O G If the player then guessed the letter O, then the string would display as D_Gthe next time this function ran This function allowed me to visually track the progress of the string as the game ran and manipulated its contents.
Building the CheckIfGameWon() Function
The CheckIfGameWon() function checks to see whether the number of correctly guessed let-ters is equal to the length of the word If this is the case, then the player has guessed all the letters that make up the word and won the game.
Function CheckIfGameWon()
‘Check and see if the player has guessed all the letters that make up
‘the word If so, set indicator variable and exit the Do Until loop
If intNoRight = Len(strGameWord) Then
CheckIfGameWon = “True”
End If
End Function
Trang 7Again, a well-placed MsgBox() in this function can be used to track the value of the blnCheckIfGameWonvariable.
Building the FlipString() Function
The problem with the string produced by the NonGuessedString()function was that it dis-played a string in exactly the opposite format that I wanted to ultimately display In other words, if the game word was DOG and the player had correctly guessed the letter O, then I wanted the game to display the word as _O_and not as D_G So I developed the FlipString() function It loops through each character of the string created by the NonGuessedString() function and reverses the display of character data.
Function FlipString()
‘Spin through and reverse the letters in the strTempStringTwo variable
‘In order to switch letters to underscore characters and underscore
‘characters to the appropriate letters
For intFlipCounter = 1 to Len(strTempStringTwo)
‘Examine each letter in the word one at a time
strWordLetter = Mid(strTempStringTwo, intFlipCounter, 1)
‘Replace each letter with the underscore character
If strWordLetter <> “_” Then
strDisplayString = strDisplayString & “_ “
Else
‘Replace each underscore with its appropriate letter
strDisplayString = strDisplayString & _
Right(Left(strGameWord,intFlipCounter),1) & “ “
End If
Next
End Function
Here again, a well-placed statement that contains the MsgBox()function can be used to dis-play the activity of this function as it attempts to spin through and reverse the disdis-play of the letters that make up the game word.
Building the DisplayGameResults() Function
The DisplayGameResults()function, shown here, determines whether the player won or lost the game and is responsible for displaying the results of the game and for determining whether the player wants to play again If the user elects to play another game, the strings
Trang 8that are used to track the status of the game word are blanked out and the PlayTheGame() function is called Otherwise, the function ends and processing control is passed back to the end of the current iteration of the PlayTheGame() function, which then returns control to the Main Processing Section where the SplashScreen()function is called.
‘Determine if the player won or lost and display game results
Function DisplayGameResults()
‘Select message based on whether or not the player figured out the word
If blnWordGuessed = “True” Then
strMsgText = “Congratulations, You Win!”
Else
strMsgText = “Sorry, You Lose.”
End If
‘Display the results of the game
intPlayAgain = MsgBox(vbCrLf & “The word was: “ & _
UCase(strGameWord) & vbCrLf & vbCrLf & vbCrLf & strMsgText & _
vbCrLf & vbCrLf & vbCrLf & _
“Would you like to play again?” , 4, cTitleBarMsg)
‘Find out if the player wants to play another game
If intPlayAgain = 6 Then
‘If the answer is yes reset the following variables & start a new game
strDisplayString = “”
strTempStringTwo = “”
PlayTheGame()
End If
End Function
Building the SplashScreen() Function
The SplashScreen() function is the last function in the script As you have seen in other games in this book, this function displays some information about the game and its creator After this function is processed, the Main Processing Section executes the WScript.Quit() method, terminating the game’s execution.
‘This function displays the game splash screen
Function SplashScreen()
Trang 9MsgBox “Thank you for playing VBScript Hangman © Jerry Ford 2002.” & _
vbCrLf & vbCrLf & “Please play again soon!”, , cTitlebarMsg
End Function
The Final Result
By now you should have all the pieces and parts of the Hangman script assembled and ready for execution Save your work and give it a shot After you have everything working correctly, you can remove or comment out any of the extra statements that use the MsgBox()function
to track the game’s intermediate results.
‘*************************************************************************
‘Script Name: Hangman.vbs
‘Author: Jerry Ford
‘Created: 02/30/02
‘Description: This script demonstrates how to create a game of Hangman
‘ using VBScript and the WSH
‘*************************************************************************
‘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 intFlipCounter, intRandomNo, strProcessGuess, blnGameStatus
Dim strCheckAnswer
Dim astrWordList(9) ‘Define an array that can hold 10 game words
‘Main Processing Section
intPlayOrNot = DoYouWantToPlay()
Trang 10If intPlayOrNot = 6 Then ‘User elected to play the game
FillArray()
PlayTheGame()
End If
SplashScreen()
WScript.Quit()
‘Procedure Section
Function DoYouWantToPlay()
‘Display the splash screen and ask the user if he or she wants to play
strSplashImage = Space(100) & “***********” & vbCrLf & _
“W E L C O M E T O “ & Space(68) & “*” & Space(18) & “*” & _
vbCrLf & Space(100) & “0” & Space(18) & “*” & vbCrLf & _
“V B S c r i p t H A N G M A N !” & Space(50) & “—||—” & _
Space(15) & “*” & vbCrLf & Space(99) & “/” & Space(1) & “\” & _
Space(17) & “*” & vbCrLf & Space(120) & “*” & vbCrLf & Space(120) & _
“*” & vbCrLf & space(113) & “ ******* “ & vbCrLf & _
“Would you like to play a game?” & vbCrLf & “ “
DoYouWantToPlay = MsgBox(strSplashImage, 36, cTitlebarMsg)
End Function
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”