Read Foundation Game Design with ActionScript 3.0, Second Edition Online
Authors: Rex van der Spuy
The structure of this program is identical to the other programs you've looked at in this book so far. The only anomaly to point out is that the constructor method has delegated its work of creating the button to themakeButton
method.
public function Buttons()
{
makeButton();
}
This is the same technique you used to modularize the code in the constructor method of the number guessing game.
This is a very common way to make interactive buttons, but AS3.0 also has a specialized class calledSimpleButton
, which is a very efficient way of making interactive buttons. Using theSimpleButton
class requires an advanced understanding of AS3.0 programming, but by the end of the book you should have all the skills you
need to feel comfortable using it. Using theSimpleButton
class is covered in detail in
Advanced Game Design with Flash,
and you can read more about it in Adobe's AS3.0 documentation athttp://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/SimpleButton.html#?filter_flash=cs5&filter_flashplayer=10.2&filter_air=2.6
I'm now going to give you the delicate job of merging the code from the Buttons.as file with the NumberGuessingGame.as file. The number guessing game is going to end up with a button that you can click. Clicking it should have the same effect as pressing the Enter key.
Before you panic, know that you don't need to learn any new code or techniques. As long as you understand how to add code to a program—where to put it and what effect it has—you'll be able to do this. This will be good practice to make sure you've properly absorbed all the concepts covered in the past four chapters. When you're done, you'll end up with a game that looks a bit like
Figure 4-34
.
Figure 4-34.
The number guessing game with an interactive button
Here are some things you'll need to do:
makeButton
method. You can then call that method in the number guessing game's constructor method, like this:public function NumberGuessingGame()
{
setupTextfields();
makeButton();
startGame();
}
startGame
method. This lets you easily reinitialize the game if you want to add a Play again button in later steps. Here's where the button event listeners should be added:public function startGame():void
{
//Initialize variables
startMessage = "I am thinking of a number between 0 and 99";
mysteryNumber = Math.floor(Math.random() * 100);
//Initialize text fields
output.text = startMessage
input.text = "";
guessesRemaining = 10;
guessesMade = 0;
gameStatus = "";
gameWon = false;
//Trace the mystery number
trace("The mystery number: " + mysteryNumber);
//Add an event listener for key presses
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressHandler);
//Add the button event listeners
button.addEventListener(MouseEvent.ROLL_OVER, overHandler);
button.addEventListener(MouseEvent.MOUSE_DOWN, downHandler);
button.addEventListener(MouseEvent.ROLL_OUT, resetHandler);
button.addEventListener(MouseEvent.CLICK, clickHandler);
}
playGame
that analyzes the input. All you need to do is connect it to the button's CLICK event, like this:public function clickHandler(event:MouseEvent):void
{
buttonUpImage.visible = true;
buttonDownImage.visible = false;
buttonOverImage.visible = false;
playGame();
}
Because you've modularized all your code into methods, it's very easy to connect the button to the existingplayGame
method. You don't need to write any new code for your game at all. The Enter key and the button call the same method when they're activated.
When you've got the button working nicely in your game, you may want to disable it when the game is over, the same way you disable the Enter key. To do that, add the following code in bold text to the end of theendGame
method:
public function endGame():void
{
if (gameWon)
{
output.text
= "Yes, it's " + mysteryNumber + "!" + "\n"
+ "It only took you " + guessesMade + " guesses.";
}
else
{
output.text
= "No more guesses left!" + "\n"
+ "The number was: " + mysteryNumber + ".";
}
stage.removeEventListener
(KeyboardEvent.KEY_DOWN, keyPressHandler);
input.type = "dynamic";
input.alpha = 0.5;
button.removeEventListener(MouseEvent.ROLL_OVER, overHandler);
button.removeEventListener(MouseEvent.MOUSE_DOWN, downHandler);
button.removeEventListener(MouseEvent.ROLL_OUT, resetHandler);
button.removeEventListener(MouseEvent.CLICK, clickHandler);
button.alpha = 0.5;
button.mouseEnabled = false
}
This new code removes all the listeners so the button has no more functionality. It also makes the button transparent as a visual cue that the button doesn't work anymore. Finally, it sets the button'smouseEnabled
property to false, which prevents it from being sensitive to the mouse.
Figure 4-35
shows what you'll see.
Figure 4-35.
Dim and disable the button at the end of the game.
This is a lot of new code for you to write! In case you have any doubts as to how it should look, you'll find the entire project, up to this point, in the folder NumberGuessingGameWithButton, in the chapter's source files. Here's a complete listing of all the code for the game so far:
package
{
import flash.net.URLRequest;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.text.*;
[SWF(width="550", height="400",
backgroundColor="#FFFFFF", frameRate="60")]
public class NumberGuessingGame extends Sprite
{
//Create the text objects
public var format:TextFormat = new TextFormat();
public var output:TextField = new TextField();
public var input:TextField = new TextField();
//Create the button objects
public var buttonUpURL:URLRequest
= new URLRequest("../images/buttonUp.png");
public var buttonOverURL:URLRequest
= new URLRequest("../images/buttonOver.png");
public var buttonDownURL:URLRequest
= new URLRequest("../images/buttonDown.png");
public var buttonUpImage:Loader = new Loader();
public var buttonOverImage:Loader = new Loader();
public var buttonDownImage:Loader = new Loader();
public var button:Sprite = new Sprite();
//Game variables
public var startMessage:String;
public var mysteryNumber:uint;
public var currentGuess:uint;
public var guessesRemaining:int;
public var guessesMade:uint;
public var gameStatus:String;
public var gameWon:Boolean;
public function NumberGuessingGame()
{
setupTextfields();
makeButton();
startGame();
}
public function setupTextfields():void
{
//Set the text format object
format.font = "Helvetica";
format.size = 32;
format.color = 0xFF0000;
format.align = TextFormatAlign.LEFT;
//Configure the output text field
output.defaultTextFormat = format;
output.width = 400;
output.height = 70;
output.border = true;
output.wordWrap = true;
output.text = "This is the output text field";
//Display and position the output text field
stage.addChild(output);
output.x = 70;
output.y = 65;
//Configure the input text field
format.size = 60;
input.defaultTextFormat = format;
input.width = 80;
input.height = 60;
input.border = true;
input.type = "input";
input.maxChars = 2;
input.restrict = "0-9";
input.background = true;
input.backgroundColor = 0xCCCCCC;
input.text = "";
//Display and position the input text field
stage.addChild(input);
input.x = 70;
input.y = 150;
stage.focus = input;
}
public function makeButton():void
{
//Load the images
buttonUpImage.load(buttonUpURL);
buttonDownImage.load(buttonDownURL);
buttonOverImage.load(buttonOverURL);
//Make the images invisible, except
//for the up image
buttonUpImage.visible = true;
buttonDownImage.visible = false;
buttonOverImage.visible = false;
//Add the images to the button Sprite
button.addChild(buttonUpImage);
button.addChild(buttonDownImage);
button.addChild(buttonOverImage);
//Set the Sprite's button properties
button.buttonMode = true;
button.mouseEnabled = true;
button.useHandCursor = true;
button.mouseChildren = false;
//Add the button Sprite to the stage
stage.addChild(button);
button.x = 175;
button.y = 155;
}
public function startGame():void
{
//Initialize variables
startMessage = "I am thinking of a number between 0 and 99";
mysteryNumber = Math.floor(Math.random() * 100);
//Initialize text fields
output.text = startMessage
input.text = "";
guessesRemaining = 10;
guessesMade = 0;
gameStatus = "";
gameWon = false;
//Trace the mystery number
trace("The mystery number: " + mysteryNumber);
//Add an event listener for key presses
stage.addEventListener
(KeyboardEvent.KEY_DOWN, keyPressHandler);
//Add the button event listeners
button.addEventListener(MouseEvent.ROLL_OVER, overHandler);
button.addEventListener(MouseEvent.MOUSE_DOWN, downHandler);
button.addEventListener(MouseEvent.ROLL_OUT, resetHandler);
button.addEventListener(MouseEvent.CLICK, clickHandler);
}
public function playGame():void
{
guessesRemaining--;
guessesMade++;
gameStatus
= "Guess: " + guessesMade
+ ", Remaining: " + guessesRemaining;
currentGuess = uint(input.text);
if (currentGuess > mysteryNumber)
{
output.text = "That's too high." + "\n" + gameStatus;
checkGameOver();
}
else if (currentGuess < mysteryNumber)
{
output.text = "That's too low." + "\n" + gameStatus;
checkGameOver();
}
else
{
output.text = "You got it!";
gameWon = true;
endGame();
}
}
public function checkGameOver():void
{
if (guessesRemaining < 1)
{
endGame();
}
}
public function endGame():void
{
if (gameWon)
{
output.text
= "Yes, it's " + mysteryNumber + "!" + "\n"
+ "It only took you " + guessesMade + " guesses.";
}
else
{
output.text
= "No more guesses left!" + "\n"
+ "The number was: " + mysteryNumber + ".";
}
//Disable the Enter key
stage.removeEventListener
(KeyboardEvent.KEY_DOWN, keyPressHandler);
input.type = "dynamic";
input.alpha = 0.5;
//Disable the button
button.removeEventListener
(MouseEvent.ROLL_OVER, overHandler);
button.removeEventListener
(MouseEvent.MOUSE_DOWN, downHandler);
button.removeEventListener
(MouseEvent.ROLL_OUT, resetHandler);
button.removeEventListener
(MouseEvent.CLICK, clickHandler);
button.alpha = 0.5;
button.mouseEnabled = false;
}
public function keyPressHandler(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.ENTER)
{
playGame();
}
}
public function overHandler(event:MouseEvent):void
{
buttonUpImage.visible = false;
buttonDownImage.visible = false;
buttonOverImage.visible = true;
}
public function downHandler(event:MouseEvent):void
{
buttonUpImage.visible = false;
buttonDownImage.visible = true;
buttonOverImage.visible = false;
}
public function clickHandler(event:MouseEvent):void
{
buttonUpImage.visible = true;
buttonDownImage.visible = false;
buttonOverImage.visible = false;
playGame();
}
public function resetHandler(event:MouseEvent):void
{
buttonUpImage.visible = true;
buttonDownImage.visible = false;
buttonOverImage.visible = false;
}
}
}