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

BOOK: Foundation Game Design with ActionScript 3.0, Second Edition
8.38Mb size Format: txt, pdf, ePub
private function onKeyDown(
event:KeyboardEvent
):void
{...

You can access this
event
object at any time to use the information it contains. One piece of information is the key code number for the key that's being pressed. This number is stored in a property of the event variable called keyCode. You can access it like this:

event.keyCode

It contains the key code number of the key being pressed. This is important, because it means you can use this information to find out which key on the keyboard is being pressed. The key code is a number (for example, 40 or 37) that corresponds to a specific key on the keyboard. Luckily you don't need to know or remember what these key codes actually are. The
Keyboard
class contains convenient properties called LEFT, RIGHT, UP, DOWN and ENTER that you can use in place of the actual key code numbers.

An
if
statement checks whether the key pressed was the Enter key.

if (event.keyCode == Keyboard.ENTER)
{
  trace(input.text);
}

The code checks whether the
event
object's key code matches the value of Keyboard.ENTER. If it does, the trace directive is run. The trace directive displays the value of the
input
field's text property—and that will be whatever you type into it on the stage. Clever!

The key code number for the Enter key is 13. You could, in fact, have written the conditional statement like the following and it would have worked just fine:

if (event.keyCode == 13)
{
  trace(input.text);
}

And actually, if you want to write it this way, I won't stop you! But AS3.0's
Keyboard
class contains loads of predefined properties that already represent these numbers, like Keyboard.ENTER, so you don't have to memorize the number associated with each key on the keyboard. Instead, you just need to use the
Keyboard
class's easy-to-read-and-remember Keyboard properties. You'll take a look at many more of these Keyboard properties in
Chapter 5
.

In fact, the
Keyboard
class contains a property for every key on the keyboard. If you want to have a look at the whole list, point your web browser to
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/ui/Keyboard.html#?filter_flash=cs5&filter_flashplayer=10.2&filter_air=2.6

You now have a way to get information directly from the player into your program. Plug this into your game to see how it works.

Making decisions

You've done a lot of work on your program, but so far it doesn't yet do anything useful. What you need to do now is build the brains of the game so the program can figure out what number the player has entered and whether it's too high, too low, or correct.

You can do this by using an if/else statement. Note that if/else statements are very similar to the simple if statements that you looked at in
Chapter 3
, except that they provide an extra course of action if the condition being checked turns out to be false.

Here's an example of the basic kind of if statement that you looked at in the previous chapter:

if (this condition or variable is true)
{
  
Perform this directive.
}

But what if the condition is not true? Obviously, the directive inside the if statement won't run. But what if you want
something else
to happen instead? That's where the addition of the keyword
else
comes in. Here's an example of a simple if/else statement:

if (this condition or variable is true)
{
  Perform this directive...
}
else
{
  Perform this directive if the condition or variable isn't true...
}

If the condition turns out to be false, the program will jump straight to the second directive enclosed inside the braces of the else block statement. This allows the program to make a choice between two alternatives, and at least one of them will be chosen.

You can take this system one step further and add a third or more possible choices by throwing an additional else if statement into the mix. Have a look at how this works:

if (this condition or variable is true)
{
  Perform this directive.
}
  else if (some other condition or variable is true)
{
  Perform this directive.
}
else
{
  Perform this directive if neither is true.
}

This if/else statement checks each of the conditions in turn. If the first is false, it skips to the second. If the second is also false, the final directive in the else block statement is run as the default value.

This format is perfect for the number guessing game because you need the program it to check for three possible conditions:

  • If the player's guess is less than the mystery number.
  • If the player's guess is greater than the mystery number.
  • If the player correctly guesses the mystery number.

To implement this decision making in the program, you need to first find a way of getting the number from the
input
text field on the stage into the program so that it can be processed. This is pretty easy to do.

  • You need to create a new variable called
    currentGuess
    to store the number the player enters in the
    input
    text field. You'll use this new variable to convert the text from the
    input
    text field from a string to a number so that an if/else statement can process it.
  • You need to make something happen when the player presses the Enter key on the keyboard.
  • You need to create a new method called
    playGame
    . Its job will be to analyze the player's input and determine whether the guess is too low, too high, or correct.

Let's get to work!

  1. Add the following new variable,
    currentGuess
    , to the class definition, just after the previous two new variables you added:
    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();
      //Game variables
      public var startMessage:String;
      public var mysteryNumber:uint;
      public var currentGuess:uint;
  2. Write the
    playGame
    method. Add it to your code just after the
    startGame
    method, but before the
    keyPressHandler
    . If you're unsure of where to add it, take a look at
    Figure 4-13
    .
    public function playGame():void
    {
      currentGuess = uint(input.text);
      if (currentGuess > mysteryNumber)
      {
        output.text = "That's too high.";
      }
      else if (currentGuess < mysteryNumber)
      {
        output.text = "That's too low.";
      }
      else
      {
        output.text = "You got it!";
      }
    }

    Figure 4-13.
    Add the playGame method between startGame and keyPressHandler.

    It actually doesn't really matter where you add this method as long as it's part of its own block inside the class definition. However, I like to keep event handlers near the end of the program to keep them out of the way.

  3. You now need to connect the
    keyPressHandler
    to the
    playGame
    method. This will make the
    playGame
    method run when the Enter key is pressed. Change the
    keyPressHandler
    so that the trace method is replaced with the
    playGame()
    method call, as shown:
    public function keyPressHandler(event:KeyboardEvent):void
    {
      if (event.keyCode == Keyboard.ENTER)
      {
        playGame();
      }
    }
  4. Compile the program. Enter a number into the
    input
    field and press the Enter key The game will now tell you whether your guess is too high, too low, or correct (see
    Figure 4-14
    ).

Figure 4-14.
With an if/else statement, the game knows whether the player's guess is correct.

When you press the Enter key, the keyboard event listener calls the
keyPressHandler
. If the Enter key is being pressed, the
playGame
method is called. The
playGame
method analyses the player's input and displays the result.
Figure 4-15
shows the route the code follows when the Enter key is pressed.

Figure 4-15.
What happens when you press the Enter key

Let's take a look at how the
playGame
method works.

public function playGame():void
{
  currentGuess = uint(input.text);
  if (currentGuess > mysteryNumber)
  {
    output.text = "That's too high.";
  }
  else if (currentGuess < mysteryNumber)
  {
    output.text = "That's too low.";
  }
  else
  {
    output.text = "You got it!";
  }
}

The first directive may be a little puzzling.

currentGuess = uint(input.text);

What's that all that about? It copies the text from the
input
field in to the
currentGuess
variable. But that's not all; it also converts the input data from plain text into a number.

When you enter text into an
input
text field, that text is stored in the field's built-in text property as a String object. String objects are words or letters, and you can usually spot them because they're surrounded by quotes. Even if you type in numbers, those numbers are interpreted as characters in a line of text, not something that can be processed mathematically. As far as strings are concerned, “789” is just another word like “bike” or “elephant.” That's bit of a problem because the game depends on the player entering numbers that can actually be understood as numbers.

What you need to do then is convert the data from the
input
field's text property from a string to a number. Because the numbers from 0 to 99 are all positive and don't contain decimal values, it makes sense that they should be interpreted as data with a uint type.

It's very easy to convert data types in AS3.0. All you need to do is surround the data you want to convert in parentheses and then add the name of the type you want to convert it to. That's all that this bit of code in bold does:

currentGuess =
uint(
input.text
)
;

It converts the string from the
input
field's text variable into a number of the uint type. This process of converting one type of data to another is called
casting
. You'll be encountering casting a lot over the course of the book. It's often necessary for you to cast data or objects as a certain type to encourage AS3.0's compiler to run the code correctly.

Other books

The Steps by Rachel Cohn
An Inconvenient Wife by Megan Chance
Dragonhold (Book 2) by Brian Rathbone
Summer House by Willett, Marcia
Bringing the Boy Home by N. A. Nelson
B00BWX9H30 EBOK by Woolf, Cynthia