Game Development Reference
In-Depth Information
public function Game() {
addEventListener(Event.ENTER_FRAME, gameLoop);
gameState = STATE_INIT;
}
This code will call the gameLoop function every time the EnterFrame event is fired in Flash. This
is the most basic game timer we will introduce in this topic. It's a legitimate game timer, but as
you will see later, there are ways to make it work much more efficiently. However, this simple
event illustrates perfectly how a game timer works. The game timer repeatedly calls the
gameLoop function on a regular basis to run the game. We have also set the gameState to
STATE_INIT, which will have our gameLoop() function call initGame() the next time it is called.
Event model
Events tell the game that something interesting has happened so it can perform an action
because of them. AS3 contains many built-in events, and you can create your own, which we will
do later in this topic. For this simple example, we are going to listen for (or more accurately,
observe) the event that is created when someone clicks the mouse button. While this event might
not be very exciting, this basic example will be reused and modified for most other events that we
use, either internal to AS3 or custom ones that we create. We'll now look at the code for setting
up a listener for an event.
The initGame() function defines the event model for this game. The following line of code states
that our class will listen for the mouse button click:
stage.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
The first parameter ( MouseEvent.CLICK ) is the name of the event, and the second parameter
( onMouseClickEvent ) is the function to call when the event is observed. We also set the clicks
variable to 0 and the gameState to STATE_PLAY so the gameLoop() function will know that to do the
next time it is called.
public function initGame():void {
stage.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
clicks = 0;
gameState = STATE_PLAY;
}
The playGame() function is called by gameLoop() if gameState is equal to STATE_PLAY. This
function simply checks the clicks variable to see if it is greater than 10. If so it sets the gameState
to STATE_GAME_OVER.
public function playGame() {
if (clicks >=10) {
gameState = STATE_GAME_OVER;
}
}
The following function is called when the mouse click event occurs. It increases the clicks variable
every time the function is called.
public function onMouseClickEvent(e:MouseEvent):void {
clicks++;
trace("mouse click number:" + clicks);
}
Search WWH ::




Custom Search