Previous Page TOC Next Page See Page



- 23 -
Programming with VBScript


VBScript provides an alternative to JavaScript for client-end programming in Internet Explorer. VBScript is a subset of Visual Basic—Microsoft's well-known Windows programming language—specially designed for Internet client scripting.

Like JavaScript, VBScript is included in Web pages and is compiled when a page is loaded. VBScript can access all the objects in the Internet Explorer Object Model. VBScript and JavaScript offer similar capabilities, but where JavaScript more closely resembles Java (and through that C and C++), VBScript looks more like Basic.

In this chapter you will learn about VBScript, including:


Basic VBScript Concepts


Before looking at the details of VBScript programming, let's take a look at certain conventions of VBScript programming, including naming standards, and code format, and command syntax.

Naming Standards


Visual Basic—and by extension VBScript—has well-established naming conventions to help make programs and scripts more readable. By contrast, JavaScript is too new to have well-established conventions—and while there are some conventions in Java, these often don't show up in most JavaScript scripts.

The rules fall into four basic areas:


Variable Name Prefixes

Microsoft recommends using prefixes to variable names to specify the type of data stored in a variable and the scope of a variable. Table 23.1 outlines the prefixes for the various variable data subtypes in VBScript.

Table 23.1. Variable subtype prefixes in VBScript.

Subtype Prefix
Boolean bln
Byte byt
Date (Time) dtm
Double dbl
Error err
Integer int
Long lng
Object obj
Single sng
String str

For example, if you wanted to create a variable to store the user's name in a script and the variable was supposed to contain string data, then the naming conventions suggest it should be named strUserName.

Further, variables in VBScript can have either script-level scope or procedure-level scope (just as they can have global scope or function-level scope in JavaScript). The naming conventions suggest that an "s" be added to the start of the name of a script-level variable. This prefix should come before the subtype prefix so that if the preceding username variable had script-level scope, then its name should be sstrUserName.

Object Name Prefixes

Just as variables take prefixes to specify the subtype and scope of a variable, Microsoft recommends using the prefixes in Table 23.2. to specify the types of objects in a name.

Table 23.2 Object-name prefixes.

Object Type Prefix
3D Panel pnl
Animated button ani
Check box chk
Combo box/Drop-down list cbo
Command button cmd
Common dialog dlg
Frame fra
Horizontal scroll bar hsb
Image img
Label lbl
Line lin
List box lst
Spin spn
Text box txt
Vertical scroll bar vsb
Slider sld

So, a text box for user comments could be called txtUserComments.

Formatting and Syntax Conventions


Microsoft's VBScript documentation also outlines standards for script formatting, comments, and basic syntax.

Comments in VBScript start with a single apostrophe ("'") and continue to the end of the line, much like single-line comments in JavaScript start with a double-slash ("//") and continue to the end of the line. Microsoft recommends that important variable declarations should be accompanied by a comment and that the script and each procedure should include overview comments.

In terms of laying out program code, nested blocks should be indented four spaces and overview comments should be indented one space. Lines don't end in a semicolon the way they do in JavaScript.

Variables and Data Types in VBScript


VBScript handles data types somewhat differently than JavaScript. VBScript has one data type—the variant—which in turn has several subtypes. Because a variant can contain any data type, when the data looks like a number it is treated as a number and when it looks like a string it is treated as a string.

In addition, numbers can be made to be treated like a string by enclosing them in quotation marks ("").

The number of data subtypes in VBScript are more than the basic types in JavaScript:


Converting Between Variant Subtypes


Even though variants can hold any type of data, it is useful to be able to convert between data types. VBScript includes several built-in functions for performing this work:

For instance, CStr(15) returns "15" and Cbyte("15") returns 15.

In addition, some other conversion functions in VBScript include the following:


Testing Data Types


In addition to be being able to convert between data types, VBScript provides a series of functions that can be used by scripts to determine some information about data stored in a variant.

The following list highlights the major functions in VBScript that can test various properties of the data stored in a variant:


Working with Variables in VBScript


In JavaScript, variables are declared using the var keyword. The process is similar in VBScript except that the Dim statement is used to declare a variable. For instance,

Dim bytOneVariable

declares a single variable and

Dim bytOneVariable, strTwoVariables, blnThreeVariables

declares three variables.



Note:

Variable names must begin with a letter, cannot contain a period, and must not be longer than 255 characters.

Each array can contain only 127 variables. There can be only 127 script-level variables per script.


Values are assigned to variables using a simple equal sign (=) as in JavaScript:

bytOneVariable = 45
strTwoVariable = "A String"
blnThreeVariable = true

Arrays in VBScript


Unlike JavaScript, VBScript is not inherently object-oriented. Arrays in VBScript, therefore, are not instances of objects. Rather, arrays are declared using the Dim statement, just as with regular scalar variables.

Fixed-sized arrays are created by specifying the number of last index in the array in parentheses after the variable name in the Dim statement. Arrays start with index zero, as in JavaScript, so Dim AnArray(7) creates an array with eight elements.

In JavaScript, arrays are not of fixed size like this. Instead they dynamically change size as values are assigned to them. In VBScript, array size can be changed with the ReDim statement, which enables the size of an array to be extended. For instance, if an array is created with Dim AnArray() then ReDim AnArray(20) would create 21 elements in the array.

If data is already stored in an array, the Preserve statement can be combined with ReDim to change the size of the array without destroying the existing content. For instance, AnArray() could further be expanded to 41 elements with ReDim Preserve AnArray(40).

VBScript Operators


VBScript has a similar set of operators to JavaScript, although the exact symbols for them differ. The operators are outlined in order of precedence in Table 23.3.

Table 23.3. VBScript operators in order of precedence.

Symbol Type Description
^ Arithmetic Exponentiation (for example, 3 ^ 2 returns 9)
- Arithmetic Unary negation
* Arithmetic Multiplication
/ Arithmetic Division
\ Arithmetic Integer division
Mod Arithmetic Modulo (for example, 7 Mod 3 returns 1)
+ Arithmetic Addition
- Arithmetic Subtraction
& String Concatenation (for example, "A" & "B" returns "AB")
= Comparison Equality (for example, "A" = "B" returns false)
<> Comparison Inequality (for example, "A" <> "B" returns true)
< Comparison Less than (for example, 1 < 2 returns true)
> Comparison Greater than (for example, 1 > 2 returns false)
<= Comparison Less than or equal to (for example, 1 <= 2 returns true)
>= Comparison Greater than or equal to (for example, 1 >= 2 returns false)
Is Comparison Object equivalence (Checks if two object references point to the same object)
Not Logical Logical negation (for example, Not true returns false)
And Logical Logical conjunction (for example, true And false returns false)
Or Logical Logical disjunction (for example, true Or false returns true)
Xor Logical Logical exclusion (for example, true Xor true returns false)
Eqv Logical Logical equivalence
Imp Logical Logical implication

Loops and Comparison in VBScript


VBScript offers similar looping and If-statement capabilities as JavaScript.

The basic If-Then-Else construct in VBScript closely resembles JavaScript's. Looping in VBScript, on the other hand, provides more flexibility than in JavaScript.

The If-Then-Else Construct


The basic If-Then construct looks like:

If condition Then
    VBScript code
End If

It can be extended to include an Else component:

If condition Then
    VBScript code
Else
    More VBScript code
End If

The key differences to note are that the condition is not contained in parentheses as in JavaScript, a Then statement starts the command block, and the End If statement closes the command block. Command blocks in VBScript are not delimited by curly braces as they are in JavaScript.

For instance, the code

If bytAnInteger = 11 Then
    bytAnInteger = 1
Else
    bytAnInteger = bytAnInteger + 1
End If

checks if bytAnInteger equals 11. If it does, then the value is reset to 1. Otherwise, the value of bytAnInteger is increased by one. In JavaScript, this if statement could have been written

if (anInteger == 11) {
   anInteger = 1;
} else {
   anInteger ++;
}

Loops in VBScript


VBScript provides more flexible looping capabilities than JavaScript. There are three basic loops in VBScript:


While-Wend loops

The While-Wend loops corresponds to the while loop in JavaScript. The basic structure of a While-Wend loop is

While condition
    Some VBScript Code
Wend

For example,

While bytAnInteger <= 10
    bytAnotherInteger = bytAnotherInteger + 10
    bytAnInteger = bytAnInteger + 1
Wend

would continue increasing the value of bytAnotherInteger by 10 until the value of bytAnInteger exceeds 10. In JavaScript, this loop would have looked like

while (anInteger <= 10) {
    anotherInteger += 10;
    anInteger ++;

}

Do-Loop Loops

The Do-Loop loop provides flexibility missing in the While-Wend loop and Microsoft's documentation recommends using it in favor of the While-Wend loop.

The Do-Loop loop can be used in two different ways: looping while a condition is true (as with the While-Wend loop) and repeating until a condition is true (similar to Pascal's Repeat-Until loop).

The former's structure is

Do While condition
    VBScript code
Loop

or

Do
    VbScript code
Loop While condition

The difference between these is that in the first structure, the condition is tested before the loop; if the condition is false, then the loop doesn't execute. In the second option, the condition is tested after the loop executes; with a false condition, the loop will execute at least once.

The While-Wend loop in the last section could be rewritten as

Do While bytAnyInteger <= 10
    bytAnotherInteger = bytAnotherInteger + 10
    bytAnInteger = AnInteger + 1
Loop

or

Do
    bytAnotherInteger = bytAnotherInteger + 10
    bytAnInteger = AnInteger + 1
Loop While bytAnInteger <= 10

An alternative use of the Do-Loop structure is to loop until a condition is true (as opposed to while a condition is true). This usage has two forms as well:

Do Until condition
    VBScript code
Loop

or

Do
    VBScript code
Loop until condition

In the first, if the condition is true entering the loop, the body of the loop is never executed. In the latter, the loop would be executed once if the condition were true.

For instance, the While-Wend loop from before could be rewritten as

Do Until bytAnInteger > 10
    bytAnotherInteger = bytAnotherInteger + 10
    bytAnInteger = AnInteger + 1
Loop

or

Do
    bytAnotherInteger = bytAnotherInteger + 10
    bytAnInteger = AnInteger + 1
Loop Until bytAnInteger > 10

Do-Loop loops can be exited early using an Exit Do statement.

For-Next Loops

The For-Next loop corresponds to JavaScript's for loop. Its basic structure is

For variable = lower To higher
    VBScript code
Next

where variable is the loop variable and lower and higher are the start and of the range to count through. As with traditional Basic for loops, the For-Next loop increases the variable by one through the range. So,

For bytAnyInteger = 1 To 10
    bytAnotherInteger = bytAnotherInteger + 10
Next

would count from 1 to 10 using bytAnInteger as a counter variable and increase bytAnotherInteger by 10 with each iteration of a loop.

To count by a large increment, or to decrease the counter variable with each iteration of the loop, the Step statement is used:

For bytAnInteger = 1 To 10 Step 2
    bytAnotherInteger = bytAnotherInteger + 10
Next

This would count from 1 to 10, as in the previous example, but would increase bytAnInteger by two with each iteration of the loop. Similarly,

For bytAnInteger = 10 To 1 Step -1
    bytAnotherInteger = bytAnotherInteger + 10
Next

would decrease bytAnInteger by one with each iteration of the loop.

The For-Next loop can be exited early using the Exit For statement, which is similar to the Exit Do statement.

The VBScript For-Next loop offers less flexibility than JavaScript's for loop, which resembles the C and C++ for loops.

Procedures in VBScript


VBScript handles procedures and functions in the way that languages such as Pascal do: it separates procedures from functions. This is different from JavaScript and languages such as C and C++, which have only functions.

The fundamental difference between procedures and functions is that functions are able to return a value, but procedures do not return values.

Procedures


A procedure is defined by a Sub statement and ends with an End Sub statement. As with JavaScript functions, a procedure can take arguments.

A procedure is defined using the following structure:

Sub ProcedureName(ArgumentList)
    VbScript Code
End Sub

where ArgumentList is an optional, comma-separated list of arguments to the procedure. If ArgumentList is omitted, the parentheses are still required, as they are in JavaScript function definitions. Procedures can be exited early using the Exit Sub statement.

For instance,

Sub DisplayName(strFirstName, strLastName)
    alert("Welcome " & strFirstName & " " & strLastName)
End Sub

would produce results similar to those in Figure 23.1 using the alert() method of the window object.

Figure 23.1. Procedures can accept arguments and work with them.

In order to call a procedure, it is sufficient to simply use the name of the procedure:

DisplayName "Arman", "Danesh"

Procedures can also be called using the Call statement:

Call DisplayName("Arman", "Danesh")

Notice that without the Call statement, the argument list has no parentheses around it but when using the Call statement, the parentheses must be used. Both of these forms produce the same result.

Functions


Functions are enclosed between Function and End Function statements and can take an optional argument list like a Sub procedure. The basic form of a function definition is as follows:

Function FunctionName(ArgumentList)
    VBScript Code
End Function

Functions can be exited early with the Exit Function statement.

As mentioned earlier, functions can return values, and this is generally how they are used. Values are returned by functions by assigning a value to the function's name inside the body of the function. For instance, the following function returns a single string, which is the combination of the first and last name passed to the function as arguments:

Function CompleteName(strFirstName, strLastName)
    CompeteName = StrFirstName & " " & strLastName
End Function

Calls to functions enclosed the arguments in parentheses but don't use the Call statement. Function calls should occur on the right side of variable assignments or in expressions. To highlight how this works, the DisplayName procedure from the previous section could be rewritten

Sub DisplayName(strFirstName, strLastName)
    Dim TheName
    strTheName = CompleteName(strFirstName, strLastName)
    alert("Welcome " & strTheName)
End Sub

or simply

Sub DisplayName(strFirstName, strLastName)
    alert("Welcome " & CompleteName(strFirstName, strLastName))
End Sub

User Interface Functions in VBScript


VBScript does not offer many of the user-interface functions offered in Visual Basic or Visual Basic for Applications because the interface functionality is really provided through the Internet Explorer Object Model in the form of form elements, dialog boxes, and so on. Because VBScript can call all the methods in the Internet Explorer Object Hierarchy (as seen in the next section), there is little reason to duplicate this functionality with internal functions in VBScript.

VBScript does provide two user interface functions: InputBox and MsgBox.

InputBox is a VBScript function that takes a prompt string as an argument, asks the user for input in a dialog box displaying the prompt string, and then returns the value input by the user. InputBox resembles the functionality of the window.prompt() method. Because it is a function, its argument must be enclosed in parentheses:

VariableName = InputBox(Argument)

MsgBox, on the other hand, is a procedure that displays the argument in a simple dialog box with a single OK button. The procedure can be called in two ways:

MsgBox Argument

or

Call MsgBox(Argument)

The MsgBox procedure resembles the window.alert() method from the Object Hierarchy.

Although InputBox and prompt() are almost interchangeable and MsgBox and alert() achieve the same result, the visual appearance of the dialog boxes is different as demonstrated in Figures 23.2 through 23.5.

Figure 23.2. An InputBox dialog box.

Figure 23.3. A prompt() dialog box.

Figure 23.4. A MsgBox dialog box.

Figure 23.5. An alert() dialog box.

Accessing the Object Model in VBScript


Properties and methods of the Internet Explorer Object Model can be accessed in VBScript just as they are in JavaScript. For instance, the JavaScript script

<SCRIPT LANGUAGE="JavaScript">
var TestVar = document.forms[2].elements[3].value;
alert (TestVar);
</SCRIPT>

is functionally equivalent to the VBScript script

<SCRIPT LANGUAGE="VBScript">
Dim TestVar
TestVar = document.forms[2].elements[3].value
alert (TestVar)
</SCRIPT>

A VBScript example


To highlight the use of VBScript in producing interactive applications, this section shows the development of a simple tic-tac-toe program using VBScript.

This script provides the following features:

The game is implemented with the following script:

<HTML>
<HEAD>
<TITLE>VBScript Tic-Tac-Toe</TITLE>
<SCRIPT LANGUAGE="VBScript">
Dim strPlayerSymbol
strPlayerSymbol = " X "
Dim strComputerSymbol
strComputerSymbol = " O "
Dim strEmptySymbol 
strEmptySymbol = ""
Dim GameBoard(2,2)
Dim BoardPoint(2,2)
Sub InitializeGame
    MsgBox "Welcome to VBScript Tic-Tac-Toe"
    Set BoardPoint(0,0) = document.board.elements(0)
    Set BoardPoint(1,0) = document.board.elements(1)
    Set BoardPoint(2,0) = document.board.elements(2)
    Set BoardPoint(0,1) = document.board.elements(3)
    Set BoardPoint(1,1) = document.board.elements(4)
    Set BoardPoint(2,1) = document.board.elements(5)
    Set BoardPoint(0,2) = document.board.elements(6)
    Set BoardPoint(1,2) = document.board.elements(7)
    Set BoardPoint(2,2) = document.board.elements(8)
    BuildBoard
End Sub
Sub BuildBoard
    For i = 0 to 2
        For j = 0 to 2
            BoardPoint(i,j).value = GameBoard(i,j)
        Next
    Next
End Sub
Sub ClearBoard
    EmptyBoard
    BuildBoard
    MsgBox "Ready to Play!"
End Sub
Sub EmptyBoard
    For i = 0 To 2
        For j = 0 To 2
            GameBoard(i,j) = strEmptySymbol
        Next
    Next
End Sub
Function Win(CheckI,CheckJ)
    Dim Result
    Result = False
    ' CHECK ROWS
    If GameBoard(0,CheckJ) = GameBoard(1,CheckJ) And GameBoard(1,CheckJ) = GameBoard(2,CheckJ) Then
        Result = True
    End If
    ' CHECK COLUMNS
    If GameBoard(CheckI,0) = GameBoard(CheckI,1) And GameBoard(CheckI,1) = GameBoard(CheckI,2) Then
        Result = True
    End if
    ' CHECK DIAGONALS
    If CheckI = CheckJ Then
        If GameBoard(0,0) = GameBoard(1,1) And GameBoard(1,1) = GameBoard(2,2) Then
            Result = True
        End If
    End If
    If CheckI + CheckJ = 2 Then
        If GameBoard(0,2) = GameBoard(1,1) And GameBoard(1,1) = GameBoard(2,0) Then
            Result = True
        End If
    End If
    Win = Result
End Function
Sub Play(PlayI,PlayJ)
    Dim NewI
    Dim NewJ
    Dim Done
    Done = False
    If GameBoard(PlayI,PlayJ) <> strEmptySymbol Then
        MsgBox "This square is taken."
        Exit Sub
    End If
    GameBoard(PlayI,PlayJ) = strPlayerSymbol
    BuildBoard
    If Win(PlayI,PlayJ) = True Then
        MsgBox "Good Play! You Win!"
        ClearBoard
    Else
        For NewI = 0 to 2
            For NewJ = 0 to 2
                If GameBoard(NewI,NewJ) = strEmptySymbol Then
                    GameBoard(NewI,NewJ) = strComputerSymbol
                    If Win(NewI,NewJ) = True Then
                        Done = True
                        Exit For
                    End If
                    GameBoard(NewI,NewJ) = strEmptySymbol
                End If
            Next
            If Done = True Then
                Exit For
            End If
        Next
        If Done = True Then
            BuildBoard
            MsgBox "The Computer Just Won!"
            ClearBoard
        Else
            For NewI = 0 to 2
                For NewJ = 0 to 2
                    If GameBoard(NewI,NewJ) = strEmptySymbol Then
                        GameBoard(NewI,NewJ) = strPlayerSymbol
                        If Win(NewI,NewJ) = True Then
                            Done = True
                            Exit For
                        End If
                        GameBoard(NewI,NewJ) = strEmptySymbol
                    End If
                Next
                If Done = True Then
                    Exit For
                End If
            Next
            If Done = True Then
                GameBoard(NewI,NewJ) = strComputerSymbol
                BuildBoard
            Else
                For NewI = 0 to 2
                    For NewJ = 0 to 2
                        If GameBoard(NewI,Newj) = strEmptySymbol Then
                            GameBoard(NewI,NewJ) = strComputerSymbol
                            Done = True
                            Exit For
                        End If
                    Next
                    If Done = True Then
                        Exit For
                    End If
                Next
                BuildBoard
            End If
        End If
    End If
End Sub
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white" onLoad="InitializeGame" LANGUAGE="VBScript">
<FORM NAME="board">
<DIV ALIGN=CENTER>
<TABLE CELLPADDING=10 CELLSPACING=10>
<TR>
<TD COLSPAN=3 BGCOLOR="#020A33" ALIGN=CENTER>
<FONT COLOR="white"><H2>VBScript Tic-Tac-Toe</H2></FONT>
<TD>
</TR>
<TR>
<TD BGCOLOR="cyan">
<INPUT TYPE=button VALUE="   " NAME="00" onClick="call Play(0,0)" LANGUAGE="VBScript">
</TD>
<TD BGCOLOR="cyan">
<INPUT TYPE=button VALUE="   " NAME="01" onClick="call Play(1,0)" LANGUAGE="VBScript">
</TD>
<TD BGCOLOR="cyan">
<INPUT TYPE=button VALUE="   " NAME="02" onClick="call Play(2,0)" LANGUAGE="VBScript">
</TD>
</TR>
<TR>
<TD BGCOLOR="cyan">
<INPUT TYPE=button VALUE="   " NAME="10" onClick="call Play(0,1)" LANGUAGE="VBScript">
</TD>
<TD BGCOLOR="cyan">
<INPUT TYPE=button VALUE="   " NAME="11" onClick="call Play(1,1)" LANGUAGE="VBScript">
</TD>
<TD BGCOLOR="cyan">
<INPUT TYPE=button VALUE="   " NAME="12" onClick="call Play(2,1)" LANGUAGE="VBScript">
</TD>
</TR>
<TR>
<TD BGCOLOR="cyan">
<INPUT TYPE=button VALUE="   " NAME="20" onClick="call Play(0,2)" LANGUAGE="VBScript">
</TD>
<TD BGCOLOR="cyan">
<INPUT TYPE=button VALUE="   " NAME="21" onClick="call Play(1,2)" LANGUAGE="VBScript">
</TD>
<TD BGCOLOR="cyan">
<INPUT TYPE=button VALUE="   " NAME="22" onClick="call Play(2,2)" LANGUAGE="VBScript">
</TD>
</TR>
<TR>
<TD COLSPAN=3 ALIGN=CENTER BGCOLOR="maroon">
<INPUT TYPE=button VALUE="Start A New Game" onClick="ClearBoard">
</TD>
</TR>
</TABLE>
</DIV>
</FORM>
</BODY>
</HTML>

This script is fairly simple, but highlights several capabilities of VBScript, including the following:

The script itself is divided into five procedures and one function. Before looking at each of these, take a look at the HTML form that defines the user interface.

The User Interface


The user interface for the tic-tac-toe game consists of a grid of nine buttons. Each of these represents one of the squares in the game. A tenth button enables users to start a new game.

The nine buttons making up the play area all start empty, representing a new game, as shown in Figure 23.6. As the player plays, the button labels change to "X" or "O" as appropriate (see Figure 23.7).

Figure 23.6. The play area consists of nine blank HTML buttons.

Figure 23.7. As play proceeds, the button labels display either "X" or "O".

When a user clicks on a blank button to make a play, the Play subroutine is called. This subroutine makes the user's play and then chooses a play for the computer if the user hasn't won. The Play procedure is discussed later in this chapter.

Global Variables


The script itself starts by declaring global variables and constants. Three global constants—strPlayerSymbol, strComputerSymbol, and strEmptySymbol—represent the strings displayed in the play buttons when the player plays, when the computer plays, and when no play has been made in a square. These are used throughout the script for readability rather than using explicit string literals throughout the script.

Two global arrays—GameBoard() and BoardPoint()—are also declared. GameBoard() reflects the contents of the game board displayed to the user. The values in the array reflect the values displayed in each of the buttons. All work is done with the GameBoard() array and then these values are reflected into the user interface using the BuildBoard procedure, discussed later in this chapter.

BoardPoint() serves a different purpose than GameBoard(). The entries in the BoardPoint() array point directly to the button objects associated with the buttons in the game board.

The InitializeGame Procedure


The InitializeGame procedure is called only when the document is loaded. It is invoked through the onLoad event handler of the <BODY> tag.

The procedure starts by displaying a dialog box welcoming the user. Rather than using the alert() method of the window abject, the MsgBox procedure built into VBScript is used. This looks like Figure 23.8. Next, each of the entries in BoardPoint() is made to point at one of the play buttons in the user interface.

Figure 23.8. The user is welcomed with a dialog box created using the MsgBox procedure.

The Set command is used to create these pointers to the button objects. It isn't possible to simply assign the button objects to the BoardPoint() array without the Set keyword. Notice that the elements() array of the form object is used to access each of the nine play buttons from the form.

Finally, the BuildBoard procedure is called to display the current state of the game (which should consist of nine empty buttons).

The BuildBoard Procedure


The BuildBoard procedure reflects the contents of the GameBoard() array into the actual playing form displayed for the user. This is done with two nested For loops that loop through the GameBoard() and BoardPoint() arrays, assigning the values in GameBoard() to the value properties of each of the button objects pointed to by the BoardPoint() array.

The ClearBoard Procedure


The ClearBoard procedure is called whenever the playing area needs to be cleared for a new game. This is done when the user clicks on the "Start a New Game" button or when either the user or the computer wins a game.

The procedure is simple. It calls the EmptyBoard procedure, calls BuildBoard to display the new empty board, then displays a message box telling the user that the board is ready for play.

The EmptyBoard Procedure


The EmptyBoard procedure clears the GameBoard() array by using nested for loops to assign strEmptySymbol to each entry in the array.

The Win() Function


This function is designed to check if a play leads to a win for either the computer or the user. It takes two parameters: CheckI and CheckJ, which represent the row and column of the play which you need to check for a win.

The function is fairly simple. It starts by creating a variable called Result and setting its value to False. This makes the assumption that no win has happened.

The function then checks across the row the play has been made in to see if all squares in the row contain the same value. If all squares match, then Result is set to true.

Next, the column is checked using a similar technique. Finally, diagonals are checked if the user's play falls on a diagonal. You can check if the play is on a diagonal as follows: If CheckI and CheckJ are equal, then the play is on the diagonal from top-left corner to bottom-right. If CheckI and CheckJ add to a value of two, then play lies on the other diagonal.

Finally, once all the checks have been made, the value of Result is returned by the function.

The Play() Procedure


The Play() procedure is the central portion of the script. It's where a user's play is made and the computer decides where to play. It takes two parameters: PlayI and PlayJ, representing the square the user is trying to play into.

The procedure first checks if a play has already been made in the user's selected position. If the value in this position is not strEmptySymbol then the user is told the square is taken and the procedure is exited using Exit Sub.

If the square is empty, then the user's play is made by assigning strPlayerSYmbol to the selected square.

Next a check is made to see if the player has won by calling Win(). If the player has won, the player is informed, the board is cleared, and a new game is ready to be played.

Failing this, an appropriate play for the computer needs to be found. This is a three-fold process. Using nested For loops, you loop through all the squares looking for empty positions. For each of these positions a test is made to see if the computer would win by playing in the position. If the computer can win with a play, that play is made and the board is redrawn.

If the computer can't win with a single play, the code next loops through all the positions to see if the user can win on their next move. If they can, the computer needs to play in this position to block the user's win.

Finally, if the computer can't win and there is no potential user win to block, the computer plays in the first available empty square.

VBScript into the Future


Although VBScript is based on the widely used Visual Basic programming language and development environment, it still suffers from the shortcoming that there are no strong examples on the Internet of VBScript in action.

In addition, the Internet Explorer Object Model is not yet fully usable from VBScript (for instance, using some objects that work in JavaScript on Internet Explorer may not yet work in VBScript) and the examples of built-in functions and features of VBScript on Microsoft's Web site are limited.

Still, given the popularity of Visual Basic, it seems likely that there are sufficient programmers who will adopt VBScript as their Web scripting language of choice with time.

Summary


This chapter covered the basics of VBScript—Microsoft's alternative to JavaScript for client-side scripting of Web pages. VBScript offers a familiar and easy-to-use programming environment, which should be able to be used to achieve results similar to JavaScript after it is completely implemented.

The next chapter takes a look at ActiveX objects, the other unique feature of Internet Explorer. ActiveX objects provide interactive functionality similar to that in Java and can be used for everything from animation to viewing OLE files such as Word and Excel files.

Previous Page Page Top TOC Next Page See Page