Foundation Game Design with ActionScript 3.0, Second Edition (41 page)

BOOK: Foundation Game Design with ActionScript 3.0, Second Edition
11.7Mb size Format: txt, pdf, ePub

Figure 4-9.
The game is now initialized.

The first thing you did was to declare two new variables in the class definition. You've used variables in earlier chapters, but there's something new here—the variable types (which follow the colon).

public var startMessage:
String;
public var mysteryNumber:
uint;

What are these variable types, String and uint?

You might recall from the previous chapter that when you created variables to hold Sprite objects, you declared their type to be the class from which they were made. What did this line of code mean?

public var character:Sprite;

It meant that the
character
variable was a type of Sprite. The new code you've just written does something very similar. This line means that
startMessage
is a type of String:

public var startMessage:String;

And this line means that
mysteryNumber
is a type of uint (which stands for
unsigned integer
):

public var mysteryNumber:uint;

Okay, that's pretty meaningless, isn't it? Don't worry; it will become clear soon!

Let's a take a step back. When you declare a variable, you need to tell the program what type of information that variable will be holding. Will you be using the variable to store numbers or words? If you're using it to store numbers, what kind of numbers will they be? Hey, it might seem like more detail than you need, but AS3.0 wants this information to make sure that you don't start trying to mix variables that contain
words with variables that contain numbers or any of the other kinds of possibly incompatible data types that variables can contain.

So what kind of variable types are there? Here are all the data types that can be used by variables in AS3.0:

  • Boolean
    can take one of two values: true or false; its default value is false.
  • Number
    is any number, such as whole numbers (also known as
    integers
    ) and numbers that include decimal places (also known as
    floating point
    numbers).
  • int
    stands for
    integer
    , which is a whole number without a decimal place. It can be positive or negative. Because the CPU doesn't have to calculate any decimal places, using it speeds up the program's performance. It's usually better to use the int type over the Number type if you know you won't need to use decimals. The default value for the int type is 0.
  • uint
    stands for
    unsigned integer
    . uint is an integer that is only positive. This is an even leaner version of the int type, so it's the fastest of them all. Use it whenever you can for the best performance. uint has a default value of 0.
  • String
    can be letters, words, or phrases—any text at all. You can even use the String type to store numbers, but if you do, the numbers will be interpreted as text and you won't be able to manipulate them mathematically. The default value for the String type is null, which means “no data of any kind.”
  • Object
    is a general type. The Object class in AS3.0 is the base class for all other objects. The Object class also has a default value of null.
  • void
    is a very specialized type that is used only for methods that don't return values. It's not used for variables. It can contain only one value: undefined. The undefined value is very similar to the null value, except that it is used when the variable hasn't yet been assigned a data type, or if it contains numbers or Boolean values. All the methods so far have been declared with a data type of void.
  • * (asterisk)
    is used when you want to create a variable that has no specific type or you need it to be really flexible to be able to contain different data types at different times, replace the type name with an asterisk. For example, you might use a line of code like this:
    variableName:*;
  • This variable now can hold any type of data. One suggestion regarding the use of the asterisk is this: don't use it! Unless you have an extremely good reason why you want your variables to be able to contain more than one type of data, you're opening up your program to a potential can of worms. Forcing variables to a particular type is one of the great strengths of AS3.0 because it prevents bugs and errors that are the result of the wrong type of data being stored in the wrong type of variable. These kinds of errors can often be very difficult to debug.

Note: The int, uint, and void data types start with a lowercase letter; the others all start with uppercase letters.

You can file these data types away for later, but you'll be using all of them over the course of this book. From today's menu, you have two of them on the plate:
startMessage
is a String, and
mysteryNumber
is a uint type.

The first thing the
startGame
method does is to assign values to these variables.

startMessage = "I am thinking of a number between 0 and 99";
mysteryNumber = 50;

The next thing that happens is that the text from the
startMessage
variable is copied into the output text field's
text
property.

output.text = startMessage;

output
, of course, is the text field on the stage. You could have easily written this same line of code as follows and the result would have been identical:

output.text =  "I am thinking of a number between 0 and 99";

Why did you go to all that extra trouble of creating the extra
startMessage
variable when you could have assigned the text directly?

First, you got some practice in creating String variables—that's not such a bad reason, is it? Second, it's sometimes useful to store all the text you'll be using in your program in variables that you can access in one spot. If you know that all the text in your program is assigned to variables in your
startGame
method, you don't need to go hunting through your code to find them if you need to make changes. This isn't an important issue in small programs like this number guessing game, but it could become a real chore in bigger programs. Finally, you want to make sure that the
input
text field is completely blank so that players are free to type whatever they want into it. To clear a text field of any characters, assign it a pair of empty quotation marks, like so:

input.text =  "";

Empty quotation marks are to string variables what 0 is to number variables: it just means that there's no text there yet.

Listening for key presses

In
Chapter 3
you made things happen in your game world by clicking buttons. In this game you're going to make things happen by pressing the Enter key on the keyboard. The code you'll need to write follows the same format as the code you wrote for buttons.

  • You need to create an event listener that listens for key presses.
  • You need to create an event handler that tells your program what should happen when a key is pressed.

Let's add an event listener and handler to your program to capture key presses.

  1. Add this new code in bold directly below the previous code you wrote:
    public function startGame():void
    {
      //Initialize variables
      startMessage = "I am thinking of a number between 0 and 99";
      mysteryNumber = 50;
      //Initialize text fields
      output.text = startMessage
      input.text = "";
      
    //Add an event listener for key presses
      stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressHandler);
    }
    public function keyPressHandler(event:KeyboardEvent):void
    {
      if (event.keyCode == Keyboard.ENTER)
      {
        trace(input.text);
      }
    }

    Enter this code carefully—you should have two more closing braces, following this new code, at the end of your program.
    Figure 4-10
    shows what your code editor should look like when you've added this new code.

    Figure 4-10.
    Add the new code to the end of your program.

  2. Compile the program. Enter some numbers in the
    input
    field and press the Enter key. You'll see the number you entered displayed as a trace message.
    Figure 4-11
    illustrates this.

Figure 4-11.
Any number you enter in the input field is displayed as a trace message.

Your code first added a listener to the stage. It works in exactly the same way as the button listeners you used in
Chapter 3
, except it listens for key presses.

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressHandler);

The
KeyboardEvent
class, which you imported along with your other classes for this project, has a special
KEY_DOWN
property that you can use to detect any key pressed on the keyboard. When a key press is detected, the listener launches the
keyPressHandler
to find out what it should do.

public function keyPressHandler(event:KeyboardEvent):void
{
  if (event.keyCode == Keyboard.ENTER)
  {
    trace(input.text);
  }
}

As you learned in
Chapter 3
, event listeners send a lot of information to the event handler in a special event object. You can see the event object in the handler's parameters: it has the name
event
.
Figure 4-12
highlights this for you.

Figure 4-12.
Event objects store a lot of information about the event that happened, including the key that was pressed.

All event handlers must include an event object to store this information—it's just part of the deal. Event objects that contain keyboard information are typed as
KeyboardEvent
objects, like this:

event:KeyboardEvent

They're declared directly in the event handler, as this code in bold highlights:

Other books

Behind Iron Lace by Celeste, Mercy
Darkness Before Dawn by Claire Contreras
The Beasts in the Void by Paul W. Fairman
Rottenhouse by Ian Dyer
Best Laid Plans by Billy London
Night of the Howling Dogs by Graham Salisbury
The Artful Egg by James McClure
SILK AND SECRETS by MARY JO PUTNEY