Chapter 4. Working with Variables and Arrays

All computer programs process some kind of data. This data may be embedded inside the program or it may be supplied from the user—from external files or from the computer itself. Regardless of where it originates, programmers need a means of storing and later retrieving data used during application execution. You have already seen examples of how this works in the game programs you’ve created in this book. In this chapter, you will learn how the retrieval and storage of data in computer memory really works, both in Just BASIC and other programming languages. In addition, you will learn how to create your next computer application, the Ask Mustafa game.

Specifically, you will learn

  • How to store and retrieve individual pieces of data in variables

  • How to store groups of data using arrays

  • The rules to follow when naming variables and arrays

  • About constants and how some programming languages use them

  • About the different types of data that can be stored

  • How to convert numbers to strings and vice versa

Project Preview: The Ask Mustafa Game

In this chapter you will learn how to create a new computer game called Ask Mustafa. This game is loosely based on a character named Mustafa from the Austin Powers movies. Mustafa, an agent of evil, is determined never to cooperate with or answer questions asked by Austin Powers or any other secret agent. However, Mustafa has one weakness; he cannot bear to be asked the same question three times in a row.

The game begins by welcoming the player and providing a little background information, as shown in Figure 4.1.

By specifying different font sizes, you can emphasize different text elements.

Figure 4.1. By specifying different font sizes, you can emphasize different text elements.

The player must click on the Play button to continue, displaying the screen shown in Figure 4.2. A list of questions that can be asked of Mustafa is provided in a listbox control located at the lower-left corner of the window. Once a question has been selected, Mustafa’s answer is displayed in a texteditor control located in the lower-right corner of the window.

To ask Mustafa a question, the player must double-click on one of the questions shown in the listbox control.

Figure 4.2. To ask Mustafa a question, the player must double-click on one of the questions shown in the listbox control.

The trick to winning the game is to remember that Mustafa will answer any question asked of him three times in a row. In the event that the player forgets this fact, a hint can be displayed by clicking on the Hint button. In response, the popup dialog shown in Figure 4.3 is displayed.

The player is discouraged from asking for help.

Figure 4.3. The player is discouraged from asking for help.

If the player insists on seeing the hint (by clicking on the Yes button), the popup dialog shown in Figure 4.4 is displayed.

A clue is provided to help remind the player of Mustafa’s weakness.

Figure 4.4. A clue is provided to help remind the player of Mustafa’s weakness.

Once asked the same question three times in a row, Mustafa gives up and betrays Doctor Evil’s secret location, as shown in Figure 4.5.

After giving the player the information she wants, Mustafa asks to be left alone to deal with his shame.

Figure 4.5. After giving the player the information she wants, Mustafa asks to be left alone to deal with his shame.

Working with Program Data

All computer programs process data in some manner. Data is information that your application collects, stores, processes, and modifies during execution. This data may be embedded within the program. For example, you might create a word guessing game in which you embed a dozen words used to play the game in the program code. Data can also be retrieved from the computer on which your programs run. For example, a program that processes financial transactions may depend on the system clock in order to generate date/time stamps for each record that is generated. That same final program will also depend on data input from other sources. For example, it might look for data files stored on your computer or it might allow users to key input into a graphical user interface.

Any data used by your computer programs must be stored in computer memory. The location in memory where a particular piece of data is stored is referred to as an address. To retrieve a piece of data and work with it again later in a program, the program must reference the address where the data is stored. Some programming languages, including assembly languages and C++, provide programmers with the ability to directly manipulate specific memory addresses. This requires extra care on the part of the programmer because any error can have disastrous consequences, potentially corrupting other programs’ data or even causing the computer to crash. This is why most programming languages insulate programmers from the complexities of dealing directly with memory addresses.

Most programming languages, including Just BASIC, allow you to store individual pieces of data in variables. Rather than allow you to access specific memory addresses, these languages allow you refer to a variable by name and then manage the storage and retrieval process for you. You have seen many examples of this in applications that you have already developed.

Exploring Different Ways of Storing Data

Programming languages provide you with different ways of storing and retrieving data. One way to store data within a program is to hard-code it as a literal value, as demonstrated here:

print "I am 42 years old."

Here, a numeric value of 42 has been embedded within a text string. While certainly useful as a means of displaying static information, using data in this manner is very limited. You cannot, for example, alter its value or use it to perform calculations.

In addition to supporting literal values, all programming languages let you store individual pieces of data in variables and groups of related data in arrays. In addition, most programming languages support the use of constants to store data whose value is known at development time and does not change during program execution. Each of these data storage options has its own unique characteristics and is suited to specific situations. Which ones you use will depend on the programming language you are using as well as the type of data you are working with.

Defining Constants

A constant is a descriptive name assigned to a known value that does not change throughout the execution of a program. Programmers use constants in situations where the data used by an application is known in advance and not subject to change. For example, a mathematical application might store the value of pi (3.14) in a constant at the beginning of the program and then reference it in various locations throughout the rest of the application. Since pi is a numeric constant and is not subject to change, it is a good candidate for assignment to a constant.

By assigning a value to a constant, as opposed to a variable, you eliminate the possibility of accidentally modifying it when the application is run. In addition, constants generally require less memory than variables, making programs slightly more efficient in terms of resources consumed. Simpler BASIC dialects, including Just BASIC, do not support the use of constants. However, most robust BASIC dialects, including Visual Basic and REALbasic, do.

Hint

Hint

To define a constant in programming languages such as Visual Basic, C++, and REALbasic, you use the const keyword.

const defaultScore As Integer = 100

Here, a constant named defaultScore has been defined as an integer and assigned a value of 100. Because you can assign a descriptive name to a constant, they help make program code easier to understand. For example, the above statement might be used to set the default score assigned to players at the beginning of a computer game. By using this descriptive name you help to reference your document whenever this value is used. This is a lot more meaningful than simply embedding the number 100 repeatedly in different code statements. In addition, code maintenance is simplified through the use of constants. In this scenario, all a programmer would have to do to change the default score is modify this value one time in the const declaration statement.

Many programming languages, such as Visual Basic, also provide programmers with access to a collection of pre-defined constants. For example, instead of controlling the display of text using carriage returns by inserting Chr$(13) into strings as is done in Just BASIC, Visual Basic lets programmers reference built-in constants like Control Chars.Cr (carriage return) and ControlChars.CrLf (carriage return and line feed).

Declaring Variables

Any time you have a piece of data to keep track of and modify, such as the value of a player’s score during gameplay, you need to store it in a variable. A variable is a pointer to a location in memory (address) where a value is stored. In most programming languages, including Just BASIC, a value (string or numeric) is assigned to a variable using the equals operator (=), as demonstrated here:

initialScore = 0
confirmMsg$ = "Are you sure you want to quit?"

The first statement shown creates a variable named initialScore and assigns it a numeric value of zero. The second statement creates a string variable named confirmMsg$ and assigns a text string of "Are you sure you want to quit?" to it. In addition to allowing you to create your own variables, many programming languages provide programmers with access to special variables. A special variable is a variable that is predefined by the programming language and can be referenced at any time during program execution. Table 4.1 provides a listing of Just BASIC special variables.

Table 4.1. Just BASIC Special Variables

BackgroundColor$

Joy1x

ListboxColor$

ComboboxColor$

Joy1y

Platform$

CommandLine$

Joy1z

PrinterFont$

DefaultDir$

Joy1button1

TextboxColor$

DisplayHeight

Joy1button2

TexteditorColor$

DisplayWidth

Joy2x

Version$

Drives$

Joy2y

WindowHeight

Err

Joy2z

WindowWidth

Err$

Joy2button1

UpperLeftX

ForegroundColor$

Joy2button2

UpperRightY

You may remember from Chapter 3, “Creating Graphical User Interfaces,” that special variables like BackgroundColor$, ListboxColor$, ComboboxColor$, TextboxColor$, TexteditorColor$, and ForegroundColor$ let you specify the colors used when rendering windows and controls and that DisplayHeight, DisplayWidth, WindowHeight, and WindowWidth can all be used to affect the size of application windows.

Creating Arrays

Variables are generally all that you need in order to effectively define and manipulate a few pieces of data at a time. However, some applications involve the manipulation and storage of a large amount of related information. For these applications, arrays are typically used to handle data storage. An array is an index list of data stored and managed as a unit. Data stored in an array is accessed by specifying the name of the array and the index position of the data to be stored or retrieved.

Suppose you want to create an online contact list for all your friends and associates. One way of doing this is to save a list of contacts and their phone numbers in a text file and then write a program that opens that file and reads this list into an array. Once loaded into an array, you could use data stored in the array to populate a combobox or listbox control.

Just BASIC provides support for single-dimension and double-dimension arrays. A single-dimension array is a list of data such as user names. A two-dimensional array is like a table or an Excel spreadsheet with rows and columns. Other programming languages like Visual Basic, REALbasic, and C++ support arrays with even more dimensions.

Other Data Storage Options

While Just BASIC support for data manipulation is limited to variables and one- or two-dimensional arrays, other programming languages provide additional ways of storing and retrieving data. For example, Perl allows programmers to define hashes, sometimes referred to as associated arrays, in which data is stored in key-value pairs, where each data element stored in a hash is assigned a unique key. Data can then be retrieved from the hash by referencing its associated key. REALbasic provides a similar storage mechanism, which is a dictionary to store key-value pairs.

Other programming languages like Visual Basic and C++ support the use of structures, which allow programmers to define a collection of related variables stored within an array. This allows loosely related data such as customer names, phone numbers, and addresses to be stored together and referenced individually or as a group. Object-oriented programming languages, like REALbasic, C++, and Visual Basic, also allow programmers to store data using custom classes, which can be used as a template to create objects where data can be stored.

In short, different programming languages support different data storage and retrieval options over and above variables and arrays. Still, variables and arrays are by far the most commonly used means of storing and manipulating data. As such, Just BASIC provides an excellent platform from which to experience and learn to work with both.

Working with Different Types of Data

A key concept to understand when developing computer programs is that different types of data are treated differently. For example, different types of numbers require different amounts of storage in memory. Similarly, you can do certain things to some types of data that you cannot do to others. As an example, consider numbers and strings. Numbers can be added, subtracted, multiplied, and divided. Strings, on the other hand, cannot. However, strings can be concatenated together to create larger strings. Simpler programming languages like Just BASIC support two types of values, string and numeric. More industrial-strength programming languages like Visual Basic support a much broader range of data types. For example, the following list shows just a portion of the different data types supported by Visual Basic.

Boolean

A value of True or False.

Date

A value representing date and time.

Decimal

A numeric value up to 79,228,162,514,264,337,593,543,950,335.

Double

A numeric value in the range of –1.79769313486231570E+308 to –4.94065645841246544E-324 for negative numbers and 4.94065645841246544E-324 to 1.79769313486231570E+308 for positive numbers.

Integer

A numeric value in the range of –32,768 to 32,767.

Long

A numeric value in the range of –2,147,483,648 to 2,147,483,647.

Single

A numeric value in the range of –3.402823E+38 to –1.401298E-45 for negative numbers and 1.401298E-45 and 3.4028235E+E38 for positive numbers.

String

A string value in the range of up to two billion characters.

In programming languages that support different data types, specifying the appropriate data type associated with a variable or array is important because it impacts the amount of memory dedicated to storing different variables. In addition, data type definitions restrict the types of operations that can be performed on values.

As has been stated, Just BASIC only supports string and numeric data types. In Just BASIC, as in most programming languages, a string is anything enclosed within matching double quotation marks. In Just BASIC, strings can contain up to 2,000,000 characters. Just BASIC also distinguishes between two types of numbers: integer and floating point (e.g., number containing decimals).

Trick

Trick

While Just BASIC does not support date and time data types, it does provide programmers with access to two built-in functions that retrieve date and time data from the computer in the form of a number or a string. Depending on how the Date$() function is used, it returns either a string or numeric value, as demonstrated here:

print date$()  'Returns April 15, 2007 as a string
print date$("mm/dd/yyyy")  'Returns 04/15/2007 as a string
print date$("mm/dd/yy")  'Returns 04/15/07 as a string
print date$("yyyy/mm/dd")  'Returns 2007/04/15 as a string
print date$("days")  'Returns 99999 (days since Jan. 1, 1901) as a
number

Depending on how the Time$() function is used, it returns either a string or numeric value, as demonstrated here:

print time$()  'Returns "12:55:04" as a string
print time$("seconds")  'Returns 28456 as a number (seconds past
midnight)
print time$("milliseconds") 'Returns 99999999 as a number
                            '(milliseconds past midnight)

Learning How to Work with Variables

As has been already stated, variables provide the ability to store individual pieces of data during program execution. Some programming languages, such as REALbasic, require that you formally declare a variable and its type before allowing you to assign data to it or work with it. Other programming languages, such as Just BASIC and JavaScript, let you create variables on the fly, without declaring them in advance or specifying data. Still other programming languages, such as Visual Basic, provide you with the ability to enable or disable the requirement to explicitly define variables in advance of using them.

Hint

Hint

By default, Visual Basic allows for variable creation on the fly just like Just BASIC. However, by adding the following statement at the beginning of a Visual Basic program, you can instruct Visual Basic to enforce strict variable declaration.

Option Explicit

Declaring Variables

Just BASIC does not require programmers to declare variables prior to their use, instead allowing variables to be created and used on the fly. While this allows for flexibility, it also allows for sloppy programming and errors. Therefore, it is important that you take great care to check the spelling of all your variable names. Otherwise, a small typo can lead to errors. Consider the following example.

round1Score = 10
round2Score = 20

totalScore = round1Score + Round2Score
print totalScore

In this example, the intention was to take the values assigned to round1Score and round2Score and add them together and assign the result to totalScore. However, instead of assigning a value of 30 to totalScore, this example assigned a value of 10. The reason for this unexpected turn of events was the change in spelling of the round2Score variable in the third statement. If you look carefully, you will see that the first character of this variable name has been capitalized. Just BASIC is a case-sensitive programming language, meaning that variable names in different case are viewed as being different variables.

Storing Data in Variables

Like most programming languages, if you do not assign an initial value to a variable, Just BASIC will assign a default value for you. By default, numeric values are assigned a value of 0. String variables, on the other hand, are assigned an empty string, equivalent to “”. If you do not want these defaults, you need to make sure that you assign an initial value to your variables.

In most programming languages, including Just BASIC, the = operator is used to assign data to variables, as demonstrated here:

name$ = "William"
age = 8

However, some languages differ. For example, AppleScript uses the keyword "To" to assign a value to a variable.

Understanding Scope

One important concept for you to understand is variable scope. Scope defines the area within a program where a variable can be accessed. Just BASIC supports two levels of variable scope.

  • Local. Local variables are variables that are only accessible from within the function or subroutine in which they were created. (Functions and subroutines are blocks of code that perform a specific task. Both are covered in Chapter 7, “Improving Program Organization with Functions and Subroutines.”)

  • Global. Variables accessible throughout the program.

Hint

Hint

Some programming languages, like Visual Basic .NET, support additional levels of scope, providing programmers with additional degrees of control over variable access.

Working with Local Variables

A local variable can only be accessed within the scope in which it has been created. For example, a variable used inside a subroutine can only be accessed from within that subroutine. By default, variables used outside of functions and subroutines in Just BASIC programs are not visible inside functions and subroutines. Likewise, a variable used inside a function or subroutine is not accessible outside of that function or subroutine. The following example demonstrates how to create a local variable within a subroutine.

sub TestSub
  msg$ = "Hi!"
  notice msg$
end sub

A local variable only exists within the scope in which it is created. If two subroutines were added to the same program and both contain a reference to variables named msg$, Just BASIC would treat each instance of that variable in both subroutines as being entirely different variables. If you wanted both subroutines to be able to access the same variable, then you would want to declare that variable as being global, as explained in the next section.

Working with Global Variables

Variables declared as global can be accessed from anywhere within a Just BASIC program.

Hint

Hint

Special variables, such as BackgroundColor$, ForegroundColor$, DisplayHeight, DisplayWidth, WindowHeight, and WindowWidth, are always global, accessible from anywhere in your Just BASIC programs.

To declare a variable as global you use the global command, which has the following syntax.

global variable1, variable2,... variableN

As you can see, you can declare any number of variables as being global by specifying a comma-separated list of variable names. For example, the following statements declare a variable named totalScore as being global and then assign a value to that variable.

global totalScore
totalScore = 0

Trick

Trick

In general, it is a good idea to limit the scope of your variables whenever possible. This conserves memory and eliminates the possibility of accidentally changing a variable’s value from a different location within your application (which can happen when using global variables).

Variable Naming Rules

All programming languages impose certain rules on programmers when it comes to naming variables. Some programming languages are case sensitive, meaning that they will view two identically named variables with differing case as being different. Other programming languages are case insensitive, meaning that they ignore case and consider any identically named variables to be the same. Some programming languages prohibit the use of certain characters in variable names. Failure to follow variable naming rules will result in errors.

Just BASIC variable names can be of any length. However, you will want to keep them reasonably short and descriptive. As I mentioned, Just BASIC variable names are case sensitive. Two Just BASIC variables named userage and USERAGE represent two different variables. Not all programming languages are case sensitive. For example, REALbasic is case insensitive, meaning that in a REALbasic program, variables named userage and USERAGE would be regarded as being the same variable.

The following list outlines a few rules that you must follow when assigning names to Just BASIC variables.

  • Variable names must begin with a letter.

  • Variable names can only contain letters, numbers, and the dot (.) and dollar sign ($) characters.

  • String variable names must end with the $ character.

  • Variable names cannot include blank spaces.

  • Variable names cannot be reserved words.

Trick

Trick

Make sure you give descriptive names to your variables. This will help make them easier to identify and help to make your program code self-documenting.

Converting Variables

In many programming languages, specifying a variable data type is required. These languages are said to be strongly typed. Programming languages like Just BASIC, which allow you to create variables without formally declaring them or specifying their data type, are considered to be loosely typed.

From time to time you may find that you need to convert data from one data type to another. Just BASIC provides you with access to conversion functions that you can use to convert data from one type to another. These operators include the following:

  • val()

  • str$()

Converting from String to Numeric Values

Using the val() function, you can convert a string that begins with a number or that represents a number into its numeric equivalent. If the string being analyzed cannot be evaluated to a number, a value of 0 is returned. The val() function has the following syntax.

val(expression)

expression can be a literal string or a variable. To get a better understanding of how the val() function works, take a look at the following example.

apples$ = "25"
oranges = 5

apples = val(apples$)
fruit = apples + oranges

print "You have "; fruit; " pieces of fruit."

Here, a string variable named apples$ has been assigned a string value of 25 and a numeric variable named oranges has been assigned a value of 5. Next, the val() function is used to convert the string value assigned to apples$ to its numeric equivalent. The numeric values of apples and oranges are then added together and the results are assigned to a variable named fruit, which is then displayed.

Converting from Numeric to String Values

Using the str$() function, you can convert a numeric value into its string equivalent. The str$() function has the following syntax.

str$(expression)

To get a better understanding of how the str$() function works, take a look at the following example:

oranges = 20
oranges$ = str$(oranges)
print "You have " + oranges$ + " oranges" 'error

Here, a numeric variable named oranges is assigned a value of 20. Next, the str$() function is used to convert the numeric value assigned to oranges to a string value of "20", which is then assigned to oranges$. This value is then displayed as part of a concatenated string in the last statement.

Hint

Hint

Concatenation is the process of joining two or more strings together to create a new string. Different programming languages use different concatenation characters. For example, in Visual Basic, the & character is used to concatenate strings together.

Trick

Trick

Strings are created by enclosing text within a pair of matching double-quotation marks. If you need to include a double-quotation mark within a string, you might be tempted to try something like the following:

print "Tom told Bob to "run" but he wouldn't."

However, Just BASIC will flag this statement as a syntax error. The work-around for this situation in Just BASIC is to use the chr$() function, as demonstrated here:

print "Tom told Bob to " + chr$(34) + "run" + chr$(34) + " but he
wouldn't."

As you can see, chr$(34) evaluates to a value of a double quote, thus allowing you to insert double quotation marks within your text strings.

Other programming languages provide different ways of inserting special characters into text strings. For example, when displaying a text string in a Perl script, you can precede any character that you want to be interpreted literally with the character.

Working with Numeric Variables

Unlike string variables, Just BASIC does not allow you to add a $ as the last character in a numeric variable’s name. Just BASIC numeric variables can store both integers and double-precision floating-point numbers, as demonstrated here:

Trap

Trap

If you attempt to add the $ character to the end of a numeric variable name, Just BASIC will generate a Type Mismatch error.

x = 2    'Integer
y = 1.99 'Floating point number

Like many programming languages, Just BASIC provides programmers with access to a host of built-in functions, which can be used in conjunction with numeric data. The following list shows the numeric functions provided by Just BASIC. This list of functions should look familiar to any Visual Basic or REALbasic programmer.

  • ABS()—. Returns the absolute value of a number.

  • SQR()—. Returns the square root of a number.

  • EXP()—. Returns the exponent of a number.

  • LOG()—. Returns the natural log of a number.

  • INT()—. Returns the integer portion of a number.

  • RND()—. Returns a random number between 0 and 1.

By using built-in numeric functions, you save yourself the trouble of having to develop your own programming logic to perform the same types of calculations, thus simplifying your program code. All that you have to do to use these functions is enclose a numeric value within the numeric function’s parentheses, as demonstrated here:

playerScore = 10.5
playerScore = int(playerScore) 'value is now 10

Here, a floating-point number, 10.5, is converted to an integer using the int() function.

Functions that Manipulate Strings

Most programming languages also provide built-in functions that you can use to manipulate text strings. In the case of Just BASIC, you will find functions that you can use to search strings, extract portions of strings, or convert characters from lower- to uppercase or vise versa. The following list shows the complete collection of Just BASIC’s string functions. Again, this list of functions should look familiar to any Visual Basic or REALbasic programmer.

  • InStr()—. Performs a search, looking for one string within another string, specifying the starting character location of the string if found.

  • Left$()—. Returns a specified number of characters from a string, sometimes referred to as a substring, starting from the left side of the string.

  • Len()—. Returns a value showing the number of characters in a string.

  • Lower$()—. Returns a string that has been converted to all lowercase.

  • Mid$()—. Extracts a specific number of characters from a string (if found), beginning at the specified character position.

  • Right$()—. Returns a specified number of characters from a string, sometimes referred to as a substring, starting from the right side of the string.

  • Space$()—. Returns a string made up of a specified number of characters.

  • Trim$()—. Removes leading blank spaces from the beginning and end of a string.

  • Upper$()—. Returns a string that has been converted to all uppercase.

To see an example of a number of these string manipulation functions in action, take a look at the following example.

storyText$ = "   Once upon a time..."
storyText$ = trim$(storyText$) 'Returns "Once upon a time..."
storyText$ = upper$(storyText$) 'Returns "ONCE UPON A TIME..."
storyText$ = lower$(storyText$) 'Returns "once upon a time..."
x = Len(storyText$) 'X equals 17

Here, a variable named storyText$ is assigned a text string that includes three blank spaces followed by four words and three period characters. The second statement uses the trim$() function to reassign a string with no leading or trailing spaces back to storyText$. The third statement uses the upper$() function to reassign an all-uppercase string to storyText$. The fourth statement converts the string assigned to storyText$ to all lowercase characters. Finally, the last statement uses the len() function to return a numeric value representing the number of characters of the value assigned to storyText$.

Storing Data in Arrays

As handy as variables are for storing individual pieces of data, they lose some value when you need to create programs that must handle large amounts of data. In most cases, the data processed by an application is closely related. For example, an address book application might need to manage a list of names. One way to handle the storage and retrieval of related data is through arrays. An array is an indexed list of data. Just BASIC arrays are zero-based, meaning that the first element stored in an array is assigned an index number of 0, the second element in the array has an index position of 1, and so on.

Virtually every major programming language supports the use of arrays. While many programming languages, including Visual Basic and REALbasic, support the creation of arrays with numerous dimensions, Just BASIC supports the creation of single- and double-dimension arrays. As with variables, you can use arrays to store string and numeric data.

Creating an Array

You can create small, single-dimension arrays of fewer than ten elements by simply assigning nine or fewer elements to a like-named array, as demonstrated here:

names$(0) = "Alexander"
names$(1) = "William"
names$(2) = "Molly"
names$(3) = "Jerry"
names$(4) = "Mary"

Here I’ve created an array containing five elements. For arrays with ten or more elements, Just BASIC requires that you use the dim command to first declare the array. This command has the following syntax.

dim ArrayName(dimensions)

dimensions is a comma-separated list of value representing the different dimensions of an array. Just BASIC arrays can have either one or two dimensions. Once the array has been defined, you can begin assigning data to it, as demonstrated here:

dim names$(20)

Once defined, you can begin assigning data to the array, as shown here:

names$(0) = "Alexander"
names$(1) = "William"
names$(2) = "Molly"
names$(3) = "Jerry"
names$(4) = "Mary"
.
.
names$(19) = "Mike"

Hint

Hint

Just like variables, Just BASIC requires that you add a $ character to the end of array names that will be used to store string data.

Retrieving Data from an Array

Once you have created an array and populated it with data, you can reference elements stored in the array by specifying the name of the array followed by the index number of the element to be retrieved, as shown here:

notice names$(4)

Here, the fifth element stored in an array named names$() is retrieved and displayed in a popup dialog.

Hint

Hint

Referencing array contents an element at a time is okay for small arrays, but for arrays that contain dozens, hundreds, or thousands of elements, it is not practical. Instead, you will want to set up a loop to process all of the contents of the array. Loops are covered in Chapter 6, “Using Loops to Process Data.”

Resizing an Array

You can resize any Just BASIC array using the redim statement. Using this statement, you can change the size of any array.

redim userNames$(9)

Here, the size of the userNames$() array is changed so that it can hold ten elements (0–9).

Two-dimensional arrays can also be resized, as demonstrated here:

redim addressBook$(9, 9)

Here a two-dimensional array has been resized so that it can hold 20 elements of data.

Trap

Trap

There is one major drawback to using the redim statement to resize arrays in Just BASIC. Any data already stored in the arrays is automatically deleted. Other programming languages, such as Visual Basic and REALbasic, provide you with the ability to retain data stored in arrays when resizing them.

Every programming language has a list of reserved words—sometimes referred to as keywords—that have special meaning to the language. These reserved words can only be used as documented by the programming languages in accordance with specific syntax requirements. An example of a Just BASIC reserved word is button. As you know, button is the name of a Just BASIC interface control. Since it is a reserved word, you can only use it when defining a button control on a user interface. If you attempt to use it as the name of a variable or array, you will run into problems.

Table 4.2 provides a listing of Just BASIC’s reserved words. Take a few minutes to scan this table. You may want to bookmark this page and refer back to it any time you are thinking about assigning a name to a variable or array that you think might sound like a reserved word, just to make sure it’s not.

Table 4.2. Just BASIC Reserved Words

And

Gosub

Prompt

Append

Goto

Put

As

Graphicbox

Radiobutton

Beep

Graphics

Random

Bmpbutton

Groupbox

Randomize

Bmpsave

If

Read

Boolean

Input

Readjoystick

Button

Kill

Redim

Byref

Let

Rem

Call

Line

Restore

Case

Listbox

Return

Checkbox

Loadbmp

Run

Close

Long

Scan

Cls

Loop

Select

Combobox

Lprint

Statictext

Confirm

Mainwin

Stop

Data

Maphandle

Stopmidi

Dialog

Menu

Sub

Dim

Name

Text

Do

Next

Textbox

Dump

Nomainwin

Texteditor

Else

None

Then

End

Notice

Timer

Error

On

Unloadbmp

Exit

Oncomerror

Until

Field

Or

Wait

Filedialog

Open

Window

Files

Output

Wend

For

Playmidi

While

Function

Playwave

Word

Get

Print

Xor

Global

  

Hint

Hint

Just BASIC also considers built-in functions and variables to be reserved words. Just BASIC’s collection of built-in functions includes

ABS()

ACS()

ASC()

ASN()

ATN()

CHR$()

COS()

DATE$()

EOF()

EXP()

INPUT$()

INSTR()

INT()

LEFT$()

LEN()

LOF()

LOG()

LOWER$()

MIDIPOS()

MID$()

MKDIR()

NOT()

RIGHT$()

RMDIR()

RND()SIN()

SPACE$()

SQR()

STR$()

TAB()

TAN()

TIME$()

TRIM$()

TXCOUNT()

UPPER$()

USING()VAL()

WORD$()

Just BASIC’s collection of built-in variables includes

BackgroundColor$

ComboboxColor$

CommandLine$

DefaultDir$

DisplayHeight

DisplayWidth

Drives$

Err

Err$

ForegroundColor$

Joy1x

Joy1y

Joy1z

Joy1button1

Joy1button2

Joy2x

Joy2y

Joy2z

Joy2button1

Joy2button2

ListboxColor$

Platform$

PrinterFont$

TextboxColor$

TexteditorColor$

Version$

WindowHeight

WindowWidth

UpperLeftX

and UpperLeftY.

Back to the Ask Mustafa Game

Okay, let’s turn our attention back to the development of this book’s next game project, the Ask Mustafa game. In this game you will get additional hands-on experience working with variables and arrays. You will also get the chance to work with the listbox and texteditor controls.

Designing the Game

The design of the Ask Mustafa game is relatively straightforward. The Ask Mustafa game will be created in eight steps, as outlined here:

  1. Create a new BASIC file and document its purpose.

  2. Display a welcome screen.

  3. Start game play.

  4. Close the #main window.

  5. Accept player questions.

  6. Generate answers to questions.

  7. Provide the player with a hint.

  8. Terminate game play.

The applications that you are developing in this book are getting more complicated as you move from chapter to chapter. In the last chapter, you learned how to use labels as a way to organize groups of statements that could be called upon from anywhere within a program. In this chapter game project, you will use subroutines (which are more versatile) instead.

Hint

Hint

A subroutine is a collection of related statements that are called and executed as a unit. Once executed, a subroutine returns processing control back to the statement that called on it to execute. More information about subroutines and how to work with them is available in Chapter 7, “Improving Program Organization with Functions and Subroutines.”

Creating a Just BASIC File Script

As with all the previous Just BASIC applications that you have worked on in this book, let’s begin by adding a few comment statements to the beginning of the program file in order to document the overall purpose of the application and provide a little information about its author.

' *************************************************************************
'
' Script Name: AskMustafa.bas (The Ask Mustafa Game)
' Version:     1.0
' Author:      Jerry Lee Ford, Jr.
' Date:        March 1, 2007
'
' Description: In this Just BASIC game the player is challenged to
'              interrogate Doctor Evil's evil assistant Mustafa in order to
'              determine the location of the doctor.
'
' *************************************************************************

Since this application does not use a text window, let’s also add the following statement to the end of the program file to instruct Just BASIC not to generate the default mainwin window.

nomainwin 'Suppress the display of the default text window

Welcoming the Player

The Ask Mustafa game will begin by displaying a welcome screen that introduces the game and provides the player with a little background information. Add the following code statements to the end of the program file to generate this window and manage its interaction with the player.

Hint

Hint

Even though you may be tempted not to key in the comment statements that are provided as part of the code statements shown below, go ahead and do so. These statements provide detailed step-by-step documentation of every code statement and make the program code easier to read and understand.

'Define two global variables to keep track of player guesses
global previousSelection$, consecutiveGuesses

WindowWidth = 600 'Set the width of the application windows to 600 pixels
WindowHeight = 480 'Set the height of the application windows to 480 pixels

BackgroundColor$ = "white" 'Set the window's background color to white
ForegroundColor$ = "black" 'Set the window's background color to black

'Use variables to store text strings displayed in the window

IntroMsg1$ = "A S K   M U S T A F A"
IntroMsg2$ = "Copyright 2007"
IntroMsg3$ = "Welcome to the Ask Mustafa game. In this game, you play " _
  + "the role of a secret agent who has captured Mustafa, an evil doer " _
  + "employed by Doctor Evil for the purpose of taking over and ruling " _
  + "the world. Your task is to interrogate Mustafa and get him to tell " _
  + "you where Doctor Evil is hiding."

'Define the format of statictext controls displayed on the window
statictext #main.statictext1, IntroMsg1$, 135, 50, 330, 32
statictext #main.statictext2, IntroMsg2$, 380, 90, 300, 14
statictext #main.statictext3, IntroMsg3$, 100, 180, 400, 100

'Define the format of button controls displayed on the window
button #main.button " Play ", PrepareGame, UL, 220, 360
button #main.button " Quit ", CloseMain, UL, 305, 360


'Open the window with no frame and a handle of #main
open "Ask Mustafa" for window_nf as #main

'Set the font type, size, and properties for each of the static controls
print #main.statictext1, "!font Arial 24 bold"
print #main.statictext2, "!font Arial 8"
print #main.statictext3, "!font Arial 12"

'Pause the application to wait for the player's instruction
wait

The first code statement shown above declares two global variables, previousSelection$ and consecutiveGuesses. These variables will be used to keep track of the player’s last guess (so that it can be compared against her current guess) and to keep count of the number of times in a row that the most recently asked question has been asked.

The next four statements set the width and height of the application window as well as its foreground and background colors. The next three statements assign text strings to three string variables. The value of these variables is then displayed in three static text controls that follow. Next, two button controls are defined, one labeled Play and the other labeled Quit. A subroutine named PrepareGame is called whenever the player clicks on the button labeled Play and a subroutine named CloseMain is called when the player clicks on the Quit button.

The open command is then used to open a window with a handle of #main. Next, three print statements are executed, specifying different font type, size, and property characteristics for each of the window’s statictext controls. Finally, the wait command is executed, pausing the game in order to wait for the player’s input.

Starting Game Play

The code statements that make up the PrepareGame subroutine are shown next and should be added to the end of the program file. This subroutine is called and executed whenever the player clicks on the button labeled Play located on the #main window.

'This subroutine is called when the Play button is clicked and is
'responsible for starting gameplay
sub PrepareGame handle$
  close #main    'Close the #main window
  call PlayGame  'Switch to the [PlayGame] static handle

end sub

As you can see, this subroutine begins with the keyword sub followed by the name assigned to the subroutine (PrepareGame) and then a parameter named handle$. This parameter represents the name of the control that has called the subroutine.

The subroutine itself consists of two statements. The first statement closes the #main window and the second statement uses the call command to execute a subroutine named PlayGame. The PlayGame subroutine is responsible for collecting player guesses and determining Mustafa’s responses.

Closing the Opening Window

The code statements that make up the CloseMain subroutine are shown next and should be added to the end of the program file. This subroutine is called whenever the player clicks on the Quit button located on the #main window. It consists of a single statement, which uses the close command to close the #main window.

'When called, this subroutine closes the application's #main window
sub CloseMain handle$

  close #main

end sub

Accepting Player Input

The PlayGame subroutine, shown next, is responsible for displaying the #play window, which is where the game is actually played. It lists questions from which the player can select and displays answers provided on behalf of Mustafa.

'This subroutine accepts player guesses and displays Mustafa's answers
sub PlayGame

  WindowWidth = 600 'Set the width of the window to 600 pixels
  WindowHeight = 480 'Set the height of the window to 480 pixels

  BackgroundColor$ = "White" 'Set the window's background color to white
  ForegroundColor$ = "Black" 'Set the window's foreground color to black
  'The following array contains a list of questions that the player can ask
  'Mustafa to answer
  questions$(0) = "Where is Dr. Evil?"
  questions$(1) = "Can you give me directions to Dr. Evil's lair?"
  questions$(2) = "So, have you seen Mini-Me lately?"
  questions$(3) = "I want to build an evil headquarters. Where's a " _
    + "good spot?"
  questions$(4) = "I found Dr. Evil's wallet. What address should I " _
    + "mail it to?"
  questions$(5) = "Dr. Evil ordered a pizza. Where should I deliver it?"

  loadbmp "copyimage", "C:imageshat.bmp" 'Load the specified bitmap
                                           'file into memory

  'Add a graphicbox control to the #play window
  graphicbox #play.gbox, 340, 20, 216, 216

  'Use variables to store text strings displayed in the window
  Instructions1$ = chr$(34) + "It does not matter what you ask me! I " _
    + "will tell you nothing, you impudent son of a goat!" + chr$(13) _
    + chr$(13) + "I can withstand hours of interrogation without" _
    + " breaking a sweat." + chr$(13) +  chr$(13) + "Go ahead, ask me" _
    + " your questions, you won't get any information from me." + chr$(34)
  Instructions2$ = "Select a question:"
  Instructions3$ = "Mustafa's Answer:"

  'Define the format of statictext controls displayed on the window
  statictext #play.statictext4 Instructions1$, 20, 40, 280, 170
  statictext #play.statictext5 Instructions2$, 20, 260, 280, 14
  statictext #play.statictext6 Instructions3$, 330, 260, 280, 14

  'Add a listbox control to the #play windows and load the contents of
  'the questions$() array into it
  listbox #play.listbox, questions$(), doubleClick, 20, 280, 300, 80

  'Define the format of button controls displayed on the window
  button #play.button1 "  Hint  ", GetHint, UL, 220, 380
  button #play.button2 "  Quit  ", ClosePlay, UL, 305, 380
  'Add a texteditor control to the #play window (used to display Mustafa's
  'answers)
  texteditor #play.texteditor, 330, 280, 240, 80

  'Open the window with no frame and a handle of #play
  open "Ask Mustafa" for window_nf as #play

  'Set the font type and size for the specified statictext control
  print #play.statictext4, "!font Arial 12"

  'Use the flush command to prevent the contents of the graphicbox control
  'from being overwritten when the window is first generated
  print #play.gbox, "flush"

  'Display the pre-loaded bitmap image in the graphicbox control
  print #play.gbox, "drawbmp copyimage 1 1"

  'Use the flush command to prevent the contents of the graphicbox control
  'from being overwritten if the user opens or moves another window on top
  'of the #play window
  print #play.gbox, "flush"

  'Pause the application to wait for the player's instruction
  wait

end sub

The first four statements set the window’s width, height, background, and foreground colors. An array named questions$() is then created and populated with six items. Each item represents a question that the player can select. The loadbmp command is then used to load a bitmap image into memory. This image will be used at the end of the subroutine to display a picture of Mustafa’s trademark Turkish hat (a fey) on the application window. Next, a series of three string variables are created and then used by three statictext controls to display text.

Hint

Hint

You will find a copy of the hat.bmp image file along with the source code for the Ask Mustafa game on this book’s companion website (www.courseptr.com/downloads).

Next, a listbox control is added to the #play window. The elements stored in the questions$() array are loaded into this control. To select one of the questions listed in the control (in order to ask Mustafa a question), the player must double-click on it. When this occurs, the doubleClick subroutine is called. Next, two button controls and a texteditor control are added to the window, which is then opened. A series of print statements follow that set font size and type and display the bitmap image previously loaded into computer memory. To display the bitmap image, the drawbmp command is used. In addition, the flush command is also used. This command prevents the bitmap image from disappearing in the event that the player opens or moves another window on top of the bitmap image.

Hint

Hint

loadbmp, drawbmp, and flush are all examples of graphic commands. You will learn more about how to work with graphics in Chapter 9, “Working with Sound and Graphics.”

Answering Player Questions

The doubleClick subroutine, shown next, is responsible for keeping track of each question asked by the player and for generating answers on behalf of Mustafa.

'This subroutine processes player questions and generates Mustafa's
'answers
sub doubleClick handle$

  'Retrieve the question selected by the player
  #play.listbox "selection? choice$"

  'check to see if this is the first time in a row that this question has
  'been asked
  if previousSelection$ <> choice$ then

    print #play.texteditor, "!cls"  'Clear the texteditor control

    'Display the specified answer
    print #play.texteditor, "Stop asking questions. I don't know anything!"

    consecutiveGuesses = 1  'Reset the variable used to keep track of
                            'consecutively asked questions to 1

  else  'The question has been asked at least twice in a row
    print #play.texteditor, "!cls"  'Clear the texteditor control
    'Display the specified answer

    print #play.texteditor, "Your questions are making my head hurt. " _
      + chr$(13) + "I beg you to stop!"
    consecutiveGuesses = consecutiveGuesses + 1  'Increment the variable
                                                 'used to keep track of
                                                 'consecutively asked
                                                 'questions by 1

    if consecutiveGuesses = 3 then  'The player has asked the same question
                                    '3 times in a row

      print #play.texteditor, "!cls"  'Clear the texteditor control

      'Display the specified answer
      print #play.texteditor, "All right, I can't take it anymore! Dr. " _
      + "Evil " + chr$(13) + "is on Evil Island, 50 miles east of the New " _
      + "Jersey" + chr$(13) + "coast. Please leave me alone with my shame."

    end if

  end if

  previousSelection$ = choice$  'Save the player's choice so that it can
                                'be compared against when the player
                                'makes a new guess

  wait

end sub

The first statement in this subroutine determines which listbox entry the player selected and assigns its value to a variable named choice$. Next, an if...else...end if code block executes. It is responsible for analyzing the value of previousSelection$ and choice$ to see if they are different. If their values are not equal, then this is the first time that the player has asked this question. If these two variables’ values are equal, the question has been asked at least twice in a row. If this is the case, the value of consecutiveGuesses is checked to see if it is equal to 3, in which case it is time for Mustafa to break down and give away Doctor Evil’s location. If this is only the second time in a row that the same question has been asked, Mustafa instead responds by telling the player that his head is beginning to hurt (indicating that the player’s line of questioning is starting to have an effect). Mustafa’s answers are displayed inside the texteditor control using play statements.

Hint

Hint

You will learn all about if...else...end if code blocks in Chapter 5, “Making Decisions with Conditional Logic.”

Providing the Player with a Hint

If, after playing for a while, the player cannot figure out how to get Mustafa to yield Doctor Evil’s location, she can get a hint by clicking on the button labeled Hint (located on the #play window). When this happens, the code statements located inside the GetHint subroutine are executed. The code statements for this subroutine are shown here and should be added to the end of the program file.

'This subroutine is called when the player clicks on the Hint button
sub GetHint handle$

  'Get confirmation before displaying a hint
  confirm "Hints are for wimps! Are you sure you want one?"; answer$

  if answer$ = "yes" then  'The player clicked on Yes

    'Display the hint
     notice "Ask Mustafa" + chr$(13) + "Mustafa hates repetition. Ask " _
       + "him the same question over again and he'll start giving you " _
       + "the information you want."

  end if

end sub

Before displaying the hint, the subroutine executes the confirm command, displaying a popup dialog window that requires that the player re-confirm the decision to see the hint message. If the player clicks on the button labeled Yes, the notice command is used to display the hint in a popup dialog window. Otherwise, the hint is not shown and gameplay resumes.

Terminating Game Play

The last subroutine in the program file is the ClosePlay subroutine. It is called when the player clicks on the button labeled Quit (located on the #play window).

'This subroutine is called when the Quit button is clicked and is
'responsible for closing the #play window and ending the game
sub ClosePlay handle$

  close #play
  end

end sub

This subroutine consists of two statements. The first statement closes the #play window and the second statement executes the end command, terminating the application’s execution.

The Final Result

Okay, that’s it. You have finished the development of your next computer application. Assuming that you did not accidentally make any typos or skip any steps, you should be ready to test the Ask Mustafa game and put it through its paces. Remember to check out the operation of all the interface controls and to feed the application both valid and invalid data to make sure it reacts appropriately. Once you have everything working, create a distribution package and ask your friends to try it out and give you their feedback.

Summary

In this chapter you learned how to store and retrieve data using variables and arrays. You also learned a little about constants and how they can be used to store data whose value never changes. You learned the rules that must be followed when naming variables and arrays in Just BASIC. You learned about different data types and how to convert data from strings to numbers and vice versa. You saw examples of different types of functions that are provided by most programming languages for the purpose of manipulating data in various ways. You also learned about Just BASIC reserved words and the importance of not using them as variable and array names.

Before moving on to Chapter 5, “Making Decisions with Conditional Logic,” I suggest you set aside a little extra time to work on the Ask Mustafa game by tackling the following list of challenges.

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.137.67