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

BOOK: Foundation Game Design with ActionScript 3.0, Second Edition
11.96Mb size Format: txt, pdf, ePub
displayText("All this text");
displayText("can change whenever you want it to");
displayText("without changing the function definition");

This makes the method very versatile. Here's the key to understanding it:

  • The text in the method call's argument is sent to the function definition.
  • The function definition stores that text in a variable. The name of the variable that it stores it in is supplied in the parameter. In this case, the name of the variable is
    textYouWantToDisplay
    .

Whenever you use
textYouWantToDisplay
in the function definition, it's replaced by the text that was supplied in the method call's argument.
Figure 3-35
illustrates how all this works.

Figure 3-35
. Format for a basic method

Note: You'll notice that the variable textYouWantToDisplay was given the type String. String variables are variables that contain text. We'll be discussing them in detail in
Chapter 4

You'll find this working example program in the folder MethodWithParameters in the chapter source files.

Using multiple arguments and parameters

Methods can use more than one argument or parameter. A function definition that uses more than one parameter looks like this:

public function methodName (valueOne:Type,  valueTwo:Type):void
{
  //directives...
}

The parameters are simply separated by a comma inside the parentheses.

If the function definition uses more than one parameter, the method call also needs to send it the same number of arguments. Here's what a method call with two arguments might look like:

methodName(argumentOne,  argumentTwo);

All you need to do is separate the arguments with a comma. You can create methods with any number of parameters in this same way.

At some point in your programming career you might need to use a method, but you won't know how many parameters you'll need. Suppose that you have a method that needs to track items from trips to the grocery store and you never know how many items you're going to buy. Today you might have three items, like this:

methodName (itemOne,  itemTwo,  itemThree);

Tomorrow you might have five items, like this:

methodName (itemOne,  itemTwo,  itemThree,  itemFour,  itemFive);

To avoid having to write two different function definitions, you can create one that stores the arguments it receives in an array. I'll be introducing arrays in
Chapter 9
, so you'll probably just want to file this information away for reference later. The function definition will look like this:

function methodName (...itemArray):void
{
  //directives…
}

All the arguments are stored as elements in an array called itemArray. The three dots in front of the parameter name indicate that the parameter is an array, not a variable. (For now, you can think of arrays as big filing cabinets that can store lots and lots of variables.)

If you're new to programming, you'll need a bit of practice using methods and looking at different examples before you really start to get any of this. Don't worry! I'm going to give you plenty of practice to do this in the pages and chapters ahead. No one completely understands methods at first. Just keep this chapter at hand and experiment with some of the sample programs included in this chapter's source files. You'll see many concrete examples of methods at work in this book and you'll gradually feel comfortable using them.

Understanding events and event listeners

Events are things in a program that happen. You'll be happy to let most things that happen in your program take care of themselves without needing to be bothered with the details. But you'll want to know about some events, such as button clicks, so that you can specify certain things to happen when they occur.

AS3.0 allows you to attach
event listeners
to objects. An event listener “listens” for things that happen in the program. When an event occurs, the listener triggers instructions for what to do. You can think of an event listener as an extremely clever little dog that loves to bark. You've trained your little dog not only to bark madly at burglars but also to dial the number of the police station while doing so and then bark the address of your house to the officer on the other end of the phone. Clever little dog! And that's the kind of dog you have at your disposal with event listeners in AS3.0.

Creating event listeners is a three-step process. You need to do the following to set them up and use them in the program:

  1. Import an event class from Flash's
    events
    package.
  2. Add an event listener to an object using a method call to AS3.0's built-in
    addEventListener
    method. The method call includes a number of arguments, such as the kind of event to listen for and what to do when the event occurs.
  3. Create an
    event handler
    , which is a specialized function definition that tells the program what to do when the event occurs. It “handles” the event. The event handler includes a special parameter that allows it to accept an event object, which provides quite a bit of information about the event that took place. You can use this information in your program.

The best way to understand how event listeners work is to see one in action. Let's write a simple program that shows you one of the most basic event listeners you can make

Create a new AS3.0 project called EventListener.

Type the following program into the code editor:

package
{
  import flash.display.Sprite;
  import flash.events.MouseEvent;
  public class EventListener extends Sprite
  {
    public function EventListener()
    {
      stage.addEventListener(MouseEvent.CLICK, clickHandler);
    }
    public function clickHandler(event:MouseEvent):void
    {
      trace("You clicked on the stage");
    }
  }
}

Compile the program. Click on the blank Flash Player window with the mouse. You'll see the phrase “You clicked on the stage” displayed as a trace message each time you click.

Figure 3-36
. Every time you click the stage you'll see the trace message displayed.

Let's look at how this program works

Importing an event class

To use an event listener, first import one of AS3.0's event classes. In this book you'll be using the
MouseEvent
and
KeyboardEvent
classes most frequently, although there are many others. The
import
statement for the
MouseEvent
class looks like this:

import flash.events.MouseEvent;

Once it's imported, you can use it to find out what the mouse is doing, such as clicking things or moving around the stage.

Adding an event listener

The next step is to add an event listener, which detects when the mouse is clicked.

stage.addEventListener(MouseEvent.CLICK, clickHandler);

Event listeners are usually added to objects. The dot between “stage” and “addEventListener” shows that the listener is connected to the stage.

Let's break this directive down into smaller pieces. The most important thing is this method call:

addEventListener

It's a method call to one of AS3.0's built- in methods. It's used to register the event so that the listener can start its job.

At its most basic, the
addEventListener
method call takes two parameters:

(MouseEvent.CLICK, clickHandler)

The first parameter is the kind of event you're listening for. In this case, you're listening for mouse clicks. The format for describing the kind of event to listen for is to use the imported event class name, followed by a dot and then the event you're interested in:

MouseEvent.CLICK

The kind of event you want to listen for is the CLICK event. As I'm sure you can guess, it listens for mouse clicks. (Events names are always written in uppercase.)

The reason events names are written in uppercase is because they're actually a programming element called a
constant
. Constants are always written in uppercase, which is the naming convention they follow. (You'll see how to use constants in
Chapter 9
.) The CLICK constant is built in to the AS3.0 MouseEvent class.

The second parameter is the function definition that you want to call when the event occurs. Our example program uses this one:

clickHandler

This is the name of the event handler. Its name must exactly match the name of the function definition that contains the directives you want to run when the mouse button is clicked.

Using the event handler

This is what the event handler looks like in the example program:

public function clickHandler(event:MouseEvent):void
{
  trace("You clicked on the stage");
}

It's exactly like the function definitions that you looked at earlier in the section on methods. however, there are two unique things about event handlers that distinguish them from ordinary function definitions.

The first difference is the name. By convention, the names for event handlers always end with the word
handler
. Programmers choose to give event handlers names like
clickHandler
,
moveHandler
, or
someOtherKindOfEvnetHandler
so that they're easy to spot among the other function definitions. You're free to give the event handler any name you like, but you'll make your life a little easier if you stick to this convention. I'll be doing so for the rest of this book.

The second difference is the function definition's parameter:

(event:MouseEvent)

Event handlers have to declare a special
event variable
, which also has to be the same type as the event that occurred, such as
MouseEvent
.

What is this event variable? It's actually an object that is automatically created by AS3.0 when the event takes place. Here's how it works:

Imagine clicking the stage with the mouse. As soon as that happens, a CLICK event is triggered. The CLICK event is sent by AS3.0 to something called the
event dispatcher
. (You don't need to know much about the event dispatcher except that it's a bit like a little software robot hanging around your program listening for things. But you'll never see it or interact with it directly.) As soon as it hears an event that you've told it to listen for, it takes out a notebook and scribbles down quite a bit of information about the event. For example, if you click a button, it can tell you the name of the button you clicked and where on the stage the click took place. All this information is packaged together into an event object, which is sent to the event handler (the function definition you programmed to run when the event occurs). however, the event handler has to create a variable as one of its parameters to contain the event object. Even though you may not actually need to use this event object in the function definition, AS3.0 requires that you create a variable as a parameter to contain it.

So what kind of information does this event object contain? You can find out by using
trace
to display its contents. You can change the example function definition so that it looks something like this:

public function clickHandler(event:MouseEvent):void
{
  trace(event);
}

Now if you compile the program again, and then click the stage, you'll see a trace message that looks like this:

[MouseEvent type="click" bubbles=true cancelable=false eventPhase=2 localX=360 localY=139
stageX=360 stageY=139 relatedObject=null ctrlKey=false altKey=false shiftKey=false
buttonDown=false delta=0]

Other books

Irene by Pierre Lemaitre
The Vintage Teacup Club by Vanessa Greene
A Special Man by Billie Green
Sonnet to a Dead Contessa by Gilbert Morris
The Trouble with Faking by Rachel Morgan
Samurai Game by Christine Feehan
Agents of the Glass by Michael D. Beil