Read Foundation Game Design with ActionScript 3.0, Second Edition Online
Authors: Rex van der Spuy
You'll look at a few different ways to usefor
loops over the course of this chapter.
Figure 9-10
is a quick- reference diagram of the wayfor
loops work.
Figure 9-10.
How for loops work
Although the for loop is a perennial favorite, AS3.0 allows you to create loops in a few other ways as well. You can also create a while loop or a do-while loop. They all do the same things as the for loop, although they have nuances that might be useful in certain situations.
The while loop can be particularly useful for games. It looks like this:
while(a certain condition is true)
{
//...do this
}
While loops don't run for a set number of times; they run as many times as necessary until the condition becomes false. When you use while loops in your programs, you have to make sure that the condition eventually will become false. If it doesn't, the loop will run “forever” and the Flash Player might hang. The Flash Player usually quits the loop automatically if it runs for 15 seconds without ending, but sometimes it doesn't! Use while loops with caution and always save your work before you test them.
I won't be covering while and do-while loops in detail in this book, but it's worth doing a bit of further research into them just to see their capabilities. For more information, see the section titled “Looping” in the chapter “ActionScript Language and Syntax” from Adobe's online document,
Programming Adobe ActionScript 3.0 for Adobe Flash.
If you understand howfor
loops work, you're half way to writing code that can check for collisions with multiple objects. The next piece in the puzzle is arrays. You can think of arrays big cupboards for storing many objects in one place.
Arrays can actually be used to store anything: variables, numbers, strings, objects, methods, or even other arrays. Everything inside the array is indexed with a number. You'll take a look at some practical examples of how you can use the index number of array objects to access and modify them.
In the book's download package you'll find a case study of a platform game called Bug Catcher where the player has to collect flying bugs in a jar. Let's get into the mood of the game and create an array calledcollectionJar
. Before you can use an array, you need to instantiate it using thenew
keyword. If you want to create an empty collection jar to collect bugs with, you can create one like this:
var collectionJar:Array = new Array();
collectionJar = [];
Arrays contain their objects inside square brackets, like this:
[anything between these square brackets is part of the array]
A pair of empty brackets means that the array is empty, which is how you've initialized thecollectionJar
array. But an array doesn't need to start out empty. You can initialize the array so that it's already filled with objects.
collectionJar = [fly, mosquito, bee];
All objects in an array are numbered sequentially, starting with zero. These numbers are called
index numbers
. In this example, fly has an index number of 0, mosquito has an index number of 1, and bee has
an index number of 2. You can find out which object is at which index number using the array access operator. Here's an example:
collectionJar[1]
This has the value ofmosquito
becausemosquito
has an index number of l. It's really very simple. An array is just a numbered list of things known as
elements
.
Figure 9-11
illustrates an empty array compared with an array with three elements.
Figure 9-11.
Arrays and array elements
There are several ways to put elements into arrays. In the previous example, the three elements were added to the array when it was initialized. You'll usually start with an empty array and add elements to it as necessary.
One way to put elements into an array is to assign elements directly to a position in the array's index.
collectionJar[2] = fly;
So whenever your code seescollectionJar[2]
it returns the value offly
.
Let's look at a slightly more concrete example. The chapter source files include a folder called BasicArray. Open it and take a look at the application class.
package
{
import flash.display.Sprite;
public class BasicArray extends Sprite
{
//Declare the array
private var _collectionJar:Array;
public function BasicArray()
{
//Instantiate the array
_collectionJar = new Array();
//Add elements to the array
_collectionJar[0] = "fly";
_collectionJar[1] = "mosquito";
_collectionJar[2] = "bee";
//Trace the entire array contents
trace("Entire Array: " + _collectionJar);
//Trace individual elements
trace("Element 0: " + _collectionJar[0]);
trace("Element 1: " + _collectionJar[1]);
trace("Element 2: " + _collectionJar[2]);
}
}
}
If you test this, the trace displays this:
Entire Array: fly,mosquito,bee
Element 0: fly
Element 1: mosquito
Element 2: bee
It's easy to see from this example that arrays are just storage containers.
Another very common way to get elements into an array is to use an array's built-inpush
method. You can use push to literally push an element into an array by using this format:arrayName.push(elementName);
When you push an object into an array, it gets an index number that's one higher than the last element added. This means that if the last element has an index number of [2], the object that you push into it will have an index number of [3].
Usingpush
is really helpful because you don't need to worry about which index number to add the element to. The array figures this out for you.
The chapter source files include a folder called ArrayPush. Open it as a project and have a look at the application class. It's identical to the first example, except that it usespush
to add the elements to the array.
_collectionJar.push("fly");
_collectionJar.push("mosquito");
_collectionJar.push("bee");
The trace output is exactly the same as the first example. The fact that you don't need to worry about the index numbers is very convenient.
To remove an element from an array, you can use the array'spop
method. The following code usespop
to remove the last element from an array and assign it to a variable:
removedElement = _collectionJar.pop()
;
If the last element was "bee
",removedElement
has the value of "bee
". It also means that_collectionJar
now contains only two elements: "fly
" and "mosquito
".
You can also add and remove elements to an array using thesplice
method. I'll explain how to usesplice
in detail in the next chapter.
Arrays become extraordinarily useful when they're used along with a loop. You can use a for loop to loop through every element in array, even if you have hundreds of elements, with just one line of code. Arrays and loops are almost always used together like this. Let's find out how you can use a loop to read all the elements of an array.
Arrays have a built-in property called length, which tells you how many elements the array has. You can access an array's length property like this:
arrayName.length
The numbering of the length property starts at 0. That means if you have an array with ten elements, the length property will be9
.
To find the index number of the last element in an array, you could use some code that looks like this:
arraryName.length - 1
You can use an array's length property to control the number of times a for loop repeats. Here's a basic example of the format you can use:
for (var i:int = 0; i <
arrayName.length;
i++)
{
trace(arrayName[i]);
}
This code displays all the elements in the array, starting with element 0 and running through all the way to the end of the array, however long it happens to be.
The chapter's source files include a folder called ArrayLoop. It contains an example of how to use a for loop to list the contents of an array. Open the application class and compile it to see the effect.
package
{
import flash.display.Sprite;
public class ArrayLoop extends Sprite
{
//Declare the array
private var _collectionJar:Array;
public function ArrayLoop()
{
//Instantiate the array
_collectionJar = new Array();
//Add elements to the array
_collectionJar.push("fly");
_collectionJar.push("mosquito");
_collectionJar.push("bee");
for (var i:int = 0; i < _collectionJar.length; i++)
{
trace("Element " + i + ": " + _collectionJar[i]);
}
}
}
}
This displays the following trace output:
Element 0: fly
Element 1: mosquito
Element 2: bee
This little bit of code is one of the most common and useful for game design. You'll be using variations of it hundreds or thousands of times in slightly different contexts to do everything from making objects, moving them, changing their properties, and checking for collisions.
Another interesting feature of this system is that you can create basic search functionality by throwing an if statement into the mix. It's really simple: just check to see whether an array element in the loop matches a certain search term. If you have a match, the element you're looking for has been found.
Here's the basic format for searching an array:
for (var i:int = 0; i < arrayName.length; i++)
{
if(arrayName[i] == "searchTerm")
{
trace("Search term found.");
break;
}
}
One new thing here is the keywordbreak
, which is used to stop a loop immediately without waiting for it to complete. When you use loops to search through arrays, you're often looking for only one item. Once that item has been found, it doesn't make sense to continue the loop, so you can usebreak
to stop it early. Because your program doesn't have to do any unnecessary checking, your game will run faster.
You'll find a project folder called ArraySearch in the chapter's source files. Open it and take a look at the application class. It uses an if statement inside a loop to check whether the array contains an element called “mosquito”. Once the if statement finds the correct element, abreak
directive runs to stop the loop from continuing.
package
{
import flash.display.Sprite;
public class ArraySearch extends Sprite
{
//Declare the array
private var _collectionJar:Array;
public function ArraySearch()
{
//Instantiate the array
_collectionJar = new Array();
//Add elements to the array
_collectionJar.push("fly");
_collectionJar.push("mosquito");
_collectionJar.push("bee");
for (var i:int = 0; i < _collectionJar.length; i++)
{
if(_collectionJar[i] == "mosquito")
{
trace("Mosquito found at position " + i);
break;
}
}
}
}
}