Tải bản đầy đủ (.pdf) (10 trang)

Microsoft WSH and VBScript Programming for the Absolute Beginner Part 9 ppsx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (280.7 KB, 10 trang )

60
The first statement is a comment and can be ignored. The second statement uses the
VBScript
InputBox() function to display a pop-up dialog into which the user can type either
rock, paper, or scissors. The value typed by the user is then assigned to a variable called
Answer.
Setting Up the Script’s Random Selection
Now that the player has selected his or her choice, it’s the script’s turn to make a random
selection on behalf of the computer. This can be done in two statements, as shown by the
following statements:
‘Time for the computer to randomly pick a choice
Randomize
GetRandomNumber = Int((3 * Rnd()) + 1)
The first line is a comment and can be ignored. The second line executes the Randomize state-
ment, which ensures that the computer generates a random number. If you leave this line
out and run the script several times, you’ll notice that after making an initial random
choice, the script always makes the exact same choice time and time again. The
Randomize
statement prevents this behavior by ensuring that a random number is generated each time
the script executes.
The next statement generates a random number between 1 and 3. I’ll break down the activ-
ity that occurs in this statement. First, the
Rnd() function generates a random number
between 0 and 1. Next, the
Int() function, which returns the integer portion of a number,
executes, multiplying 3 times the randomly generated number and then adding 1 to it. The
final result is a randomly generated number with a value between 1 and 3.
Assigning a Choice to the Script’s Selection
Next, you’ll need to assign a choice to each of the three possible numeric values randomly
generated by the script:
‘Assign a value to the randomly selected number


If GetRandomNumber = 3 then CardImage = “rock”
If GetRandomNumber = 2 then CardImage = “scissors”
If GetRandomNumber = 1 then CardImage = “paper”
If the number 1 is generated, then a value of rock is assigned as the computer’s selection. If
the number 2 is generated, then a value of
scissors is assigned as the computer’s selection.
Finally, if the number 3 is generated, then a value of
paper is assigned as the computer’s
selection.
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Displaying the Results of the Game
After the script comes up with the computer’s selection, it’s time to display the results of
the game so that user can see who won:
‘Display the game’s results so that the user can see if he or she won
WshShl.Popup “You picked: “ & Answer & Space(12) & “Computer picked: “ & _
CardImage
The WshShell object’s Popup() method is used to display the results of the game. Using the &
concatenation character, I pieced together the various parts of the message. These parts
included text phrases enclosed within quotation marks; the
Answer variable; the CardImage
variable, which represents the user’s and computer’s choices; the Space() method, which
added 12 blank spaces to the text messages; and the
_ character, which allowed me to spread
the message out over two separate lines.
The Final Result
Now let’s put all the pieces of the script together and then save and run the scripts:
‘Formally declare variables used by the script before trying to use them
Dim WshShl, Answer, CardImage
‘Create an instance of the WScript object in order to later use the
‘Popup method

Set WshShl = WScript.CreateObject(“WScript.Shell”)
‘Display the rules of the game
WshShl.Popup “Welcome to Rock, Paper and Scissors game. Here are the “ & _
“rules of the game: 1. Guess the same thing as the computer “ & _
“to tie. 2. Paper covers rock and wins. 3. Rock breaks “ & _
“scissors and wins. 4. Scissors cut paper and wins.”
‘Prompt the user to select a choice
Answer = InputBox(“Type Paper, Rock, or Scissors.”, _
“Let’s play a game!”)
‘Time for the computer to randomly pick a choice
Randomize
GetRandomNumber = Round(FormatNumber(Int((3 * Rnd()) + 1)))
61
Chapter 2 • Overview of the Windows Script Host
62
‘Assign a value to the randomly selected number
If GetRandomNumber = 3 then CardImage = “rock”
If GetRandomNumber = 2 then CardImage = “scissor”
If GetRandomNumber = 1 then CardImage = “paper”
‘Display the game’s results so that the user can see if he or she won
WshShl.Popup “You picked: “ & Answer & Space(12) & “Computer picked: “ & _
CardImage
Summary
In this chapter, you learned a lot about the WSH core object model. This included a review
of its 14 objects and their methods and properties. You also saw a number of example scripts
that demonstrated the use of various objects and their methods and properties. This infor-
mation and the examples that I covered here have given you the foundation required to
complete the rest of this book, not to mention the games that you will learn. In addition,
you learned how to configure both the WScript and CScript execution hosts to best suit your
personal requirements and preferences.

Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
C HALLENGES
1. See whether you can expand RockPaperScissors.vbs by adding logic that com-
pares the player’s selection to the script’s random selection to determine the
winner.
2. Try adding logic to RockPaperScissors.vbs to see whether you can get the script
to record its start time and completion time in the Windows event log. This way,
you can monitor the event log and track the execution of the script.
3. See whether you can modify NetMessenger.vbs to execute different Windows
commands. For example, try writing a script that uses the NET START and NET STOP
commands to stop and start a Windows service.
Part
Chapter 3: VBScript Basics
Chapter 4: Constants, Variables,
and Arrays
Chapter 5: Conditional Logic
Chapter 6: Processing Collections
of Data
Chapter 7: Using Procedures to
Organize Scripts
Learning VBScript & WSH Scripting
II
This page intentionally left blank
VBScript Basics
3
CHAPTER
T
his chapter begins your VBScript education by teaching you a number of
important concepts. You’ll learn about the objects that make up the
VBScript core and run-time object models. In addition, you’ll learn about

basic VBScript syntax, functions, reserved words, and special characters. You’ll
also learn about VBScript and WSH output functions and methods. Along the
way, you’ll create a Math Game while learning more about how VBScript works
with the WSH. You also will learn
• The basic rules that you must follow when writing VBScripts
• The objects that make up the VBScript core and run-time object models
• How to enhance your scripts using built-in VBScript functions
• Different ways of displaying script output
CHAPTER
66
Project Preview: The Math Game
This chapter’s game project shows you a programming technique that enables you to write
VBScripts that can open and interact with other Windows applications. It’s called
MathGame.vbs, and it tests the player’s understanding of the principle of precedence in solving
a numeric expression. If the user gets the answer correct, he or she is congratulated for pos-
sessing superior math skills. If the player provides an incorrect answer, then the game offers
to teach the player how to solve the expression.
To teach the player how to solve the equation, the program opens the Microsoft WordPad
application and types out instructions that explain the steps required to solve the problem.
To further demonstrate how the equation is solved, the program starts the Windows Calcu-
lator application and uses it to solve the equation. The WordPad and Calculator demonstra-
tions play out almost like a movie or slide show, starting automatically, pausing as input
and text are automatically keyed in, and finally automatically closing when the demon-
strations end. Figures 3.1 through 3.6 demonstrate some of the screens that users will see
when they play the Math Game.
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
Figure 3.1
The game begins
by asking the
player to solve a

mathematical
equation.
Figure 3.2
An error occurs if
the player fails to
enter a number.
Figure 3.3
The player is
praised if he or
she correctly
solves the
equation.
As you go through the steps involved in creating this game, you’ll learn how to use a number
of
WScript and WshShell object methods, and you’ll get a brief introduction to VBScript’s
support for conditional programming logic.
67
Chapter 3 • VBScript Basics
Figure 3.4
If the player
provides an
incorrect answer,
the game offers
to demonstrate
how the equation
is solved.
Figure 3.5
Using WordPad,
the game types
out detailed

instructions for
solving the
problem.
Figure 3.6
The game then
starts the
Calculator
application and
solves the
equation again,
just for fun.
68
VBScript Statements
Like any programming language, VBScript is comprised of programming statements. As you
go through the chapters in this book, you’ll be introduced to the statements that make up
the VBScript’s scripting language, learning a few different statements in every chapter,
until, by the end of the book, you’ve seen and worked with most of them.
Table 3.1 lists the statements that make up the VBScript scripting language.
VBScript Syntax Rules
To properly apply the programming statements that make up the VBScript programming
language, you must have an understanding of the syntax rules that govern these statements.
Each VBScript statement has its own particular syntax. The following is a list of rules that
you should keep in mind as you write your VBScripts:
• By default, all VBScript statements must fit on one line.
• As you have already seen in earlier chapters, you can spread a single statement out
over multiple lines by ending each line with the
_ (continuation) character.
• More than one VBScript statement can be placed on a single line by ending each
statement with the
: (colon) character.

• By default, VBScript is not case-sensitive, meaning VBScript regards different case
spelling of words used by variables, constants, procedures, and subroutines as the
same.
• You can enforce case-sensitivity by adding the
Option Explicit statement to the
beginning of your VBScripts. You’ll learn more about this statement later in this
chapter.
• By default, an error will halt the execution of any VBScript.
• You can prevent an error from terminating a VBScript’s execution by adding the
On
Error Resume Next
statement to your VBScripts. You’ll learn more about working with
this statement in Chapter 9, “Handling Script Errors.”
• Extra blank spaces are ignored within scripts and can be used to improve scripts’
format and presentation.
Every VBScript statement has its own specific syntax that must be exactly followed. Failure
to properly follow a statement’s syntax will result in an error. Let’s look at an example. The
following statement tries to use the VBScript’s
MsgBox() function to display a text message:
MsgBox “Thanks for playing!
Microsoft WSH and VBScript Programming for the Absolute Beginner, Second Edition
69
Chapter 3 • VBScript Basics
Statement Description
Call Executes a procedure
Class Defines a class name
Const Defines a constant
Dim Defines a variable
Do Loop Repeatedly executes a collection of one or more statements as long as a
condition remains

True or until the condition becomes True
Erase Reinitializes the elements stored in array
Execute Executes a specified statement
ExecuteGlobal Executes a specified statement in a script’s global namespace
Exit Ends a loop, subroutine, or function
For Each Next Processes all the elements stored in an array or collection
For Next Repeats a collection of one or more statements a specified number of times
Function Defines a function and its associated arguments
If Then Else Executes one or more statements depending on the value of a tested condition
On Error Enables error handling
Option Explicit Forces explicit variable declaration
Private Defines a private variable
Property Get Defines a property name and its arguments and then returns its value
Property Let Defines a property procedure’s name and its arguments
Property Set Defines a property procedure’s name and its arguments
Public Defines a public variable
Randomize Initializes VBScript’s random-number generator
ReDim Defines or redefines the dimension of an array
Rem A comment statement
Select Case Defines a group of tests, of which only one will execute if a matching condition
is found
Set Sets up a variable reference to an object
Sub Defines a subroutine and its arguments
While Wend Executes one or more statements as long as the specified condition is True
With
Associates one or more statements that are to be executed for a specified object
TABLE 3.1 VBSCRIPT STATEMENTS

×