Design Lab 5: Game Media [ Monday 6pm - Rm 908 ]
instructor: Jonah Warren
email: jonah AT feedtank DOT com
url: http://www.playfulsystems.com/teaching/2007/gamemedia
Before reviewing basic programming concepts in Actionscript and its syntax, I'm going to take a second to explain the basics of Object Oriented Programming, why it's important, and how you have actually have been using it whenever you create Flash movies.
Traditional programming languages consist of instructions grouped into procedures (similar to functions). This is called Procedural Programming, and includes languages like Basic, Pascal and C.
The core unit of organization in procedural programming is a procedure: a group of instructions that accomplish a given task. If you were to program Space Invaders, you could have a procedure called gameOver that would reset all the game variables and bring you back to a start screen. You could also have a procedure that would shoot a bullet from your ship. Unfortunately, procedural programming can become very confusing when dealing with large programs with lots of interactions between procedures.
When you think about it, a programming language is really like any other language, except its a way of communicating with the computer rather than another person. The way a computer understands information at its lowest form is 1s and 0s. A programmer could conceivably write code in 1s and 0s, but this would be difficult.
The idea of programming languages is to create a system by which humans can interact with computers that closely mimics the way humans think and understand things.
The progression from organizing code in terms of tasks (Procedural Programing) to objects (OOP) reflects this. At the most basic level, humans understand the world in terms of objects, more so than tasks.
Object Oriented Programming is a different approach to programming. Instead of the procedure, its basic unit of organization is the object. We can define these "objects" as a combination of its properties and behaviors.
So what is an object in code?
An object is basically a group of variables (storage) and functions (tasks that use that storage). The big innovation in Object Oriented programming is linking data and the functions that alter that data.
So, if we were to go back to our Space Invaders example, we could have a spaceship as an object. The spaceship would then have a number of variables that would help describe it, such as its x position on the screen, its y position on the screen, whether or not its going right or left, and what type of ship it was.
The ship would have these variables as well as functions that could alter these variables. These functions could be moveLeft, moveRight, and shootBullet.
How does this relate to Flash? Well, anything you put on the stage is an Object. For example, a MovieClip. If we look at the documentation for the MovieClip object in Flash help, we will see that it has a number of variables (_x, _depth, _alpha), and a number of functions that use them (getDepth(), attachMovie()).
Along with the recent release of Flash 9, Adobe released a new version of Actionscript, Actionscript 3.0. While most of the syntax has stayed the same, there are a lot of differences berween Actionscript 2.0 and 3.0, as shown in this document from Adobe's website.
Note that when creating a new Flash project, you must choose whether or not you will be writing your code in Actionscript 2.0 or an Actionscript 3.0. You cannot write Actionscript 3.0 code in an Actionscript 2.0 project or vice versa.
One common complaint about Flash 8 and earlier was the fact that code could be placed in such a wide variety of locations (on MovieClips, on Buttons, on the main timeline, in external files...), it was often difficult to find the code in an Flash project. An an effort to fix this problem, in Flash 9, code can only put code in frames on the timeline, or in external files. You can no longer place code on objects (MovieClips and Buttons) in your Flash movie. You will no longer see code like "on (press)".
For now, put all your code on the main timeline. We will discuss placing your code in external files at a later date.
Read this article on migrating code from Actionscript 2.0 to Actionscript 3.0. Be sure to note number 14, event handling. Its one of the first differences you will notice.
function clickHandler(event:MouseEvent):void
{
var theName:String = input_txt.text;
output_txt.text = "Hi " + theName + ".";
}
ok.addEventListener(MouseEvent.CLICK, clickHandler);
Variables store information. You can think of variables as a locker. It stores stuff in a specific place that you can retrieve at a later date. With a variable, you can store the name of a person, a position on the screen or even something more abstract like the state of a game.
You can name a variable anything you want to, as long as it doesn't start with a number. The syntax for naming variables is var, followed by your variable name:
After you declare a variable, you can put information in it, and then begin to use it. The following sets xPosition to 100:
From this point on, whenever the program sees "xPosition" (as long as you don't change its value) your program will replace the number 50 with your variable.
Just like there are different types of lockers (gym, school, airport..) there are different types of variables. Different types of variables hold different types of information.
In Actionscript 1.0, you didn't have to worry about what type a variable is, you could just start using it. In Actionscript 2.0 and 3.0, you can do the same, or you can specify the type of a variable before you use it. There are advantages to typing your variables.
You specify a datatype for a variable when you declare it. The syntax is var, followed by your variable name, followed by a colon and the datatype:
There are a number of different datatypes in Actionscript. The most commonly used datatypes are Number, String and Array (we'll also use MovieClip quite often). We will go over others in class. Once we start learning how to write Object Oriented code, we'll see how make our own datatypes.
Operators are symbols that manipulates or transforms data. Many operators will be familiar to you, such as multiplication (*), addition(+) or subtraction(-), whereas some may be less familiar (==, %, &&).
Using operators, you can change (or test) the value of variables. If we used the variable xPosition to hold an object's horizontal position on the screen, then to move the object left, we could subtract a number from xPosition:
Some operators can be used in different ways depending on their context. The addition(+) operator can be used with Numbers to add values, or with Strings to concatenate (join). The following uses the addition operator to concatenate two Strings together:
var username:String = "Jonah" var greeting:String; greeting = "Hello" + username + ", welcome to class"; trace(greeting);
This will print "Hello Jonah, welcome to class" in the output window.
Conditional statements are used when you want something to happen only in certain situations. In most cases, you will test the value of a variable and then execute some code based on that test. Conditionals are also refered to as if statements in actionscript. An example of a conditional statement in Space Invaders might be "if the number of lives you have left equals 0 then end the game."
In its most basic form, an if statement consists of an if, a condition that is contained in parentheses and a block of code contained in curly brackets. The code in the curly brackets will only execute if the condition in the parethesis is true.In this example, we are testing to see if the numLives variable is equal to 0 (lets assume that we declared this variable earlier in our program. If it does, we will execute the code in the brackets (which will set a variable called score to 0 and call a function endGame()). If the condition is false, it will skip over the code in the brackets, and continue with the program.
if (numLives == 0) {
score = 0;
endGame();
}
Relational Operators
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)
== (equality)
!= (inequality)
Logical operators
|| (logical OR)
&& (logical AND)
! (logical NOT)
An array is a special type of variable. It keeps track of multiple pieces of information at once. You can think of it as a list of variables, each one being the same type (Number, String...).
We can access each element of the list via its index, a number that uniquely designates its position in the list. You should use arrays whenever you have multiple instances of similar data. You can think of it as a collumn in an excel spreadsheet.
When using arrays you:
var usernames:Array; usernames = new Array(5); usernames[0] = "John"; usernames[1] = "Sarah"; usernames[2] = "Greg"; usernames[3] = "Molly"; usernames[4] = "Bob";
Declaring the variable should look familiar. Its just like you'd declare a Number or String. To allocate the array (which is just setting aside the space for your array), you use the new command, followed by Array and then the number of elements in your array in parantheses.
After you've allocated your array, you can begin to use it. In our example, we set all five elements in the array to peoples' names. Notice that to reference different elements in the list, we use brackets... [ and ]. Inside these brackets, we put the index to a value in that array. Since we allocated our array to have 5 elements, we have 5 indexes and thus 5 places to store data. Notice that these indexes start at 0 and end at 4.
If you didn't know how many elements will end up in your username array, you could allocate your array without a number of elements like the following:
var usernames:Array; usernames = new Array(); usernames[0] = "John"; usernames[1] = "Sarah";
A loop executes a block of code multiple times. Lets say you wanted Flash to execute the same code 10 times, you would use a loop.
The most common loop used in Actionscript is a for loop. A for loop executes a block of code a given amount of times, and keeps a counter (variable) to help you keep track of how many times that loop has executed.
A for loop is made up of three parts:
Initialization: A variable is declared and initialized for use within the body of the loop. This
variable is most often used as a counter.
Boolean Test: This can be any expression that resolves to being true or false. You can think
of it as the ending condition. Usually, you test your counter variable.
Iteration Expression: This instruction that you want to happen with each loop cycle. Most
often it is used to update the counter.
for(var i=0;i<10;i++) {
trace(i);
}
The following example should print out the numbers 0 to 9 to the output window.
Arrays and for loops are often used together. The following code will print out the first 3 names in the username array we created in the Array section ("John","Sarah", and "Greg").
for(var i=0;i<3;i++) {
trace(username[i]);
}
Functions break large computing tasks into smaller ones. It also allows programmers to reuse code. A function in its most basic form is simply giving a name (whatever name you want) to a block of code. After you define a function, whenever you want that code to execute, you can just use the name you gave it.
If we were to go back to our Space Invaders game, we could have a function called moveShipLeft() that would move the ship a given amount of pixels to the left. You could also have a function called createEnemyShips() which would, at the beginning of a level, display all the bad guys to the screen.
The main components of a function are:
function countTo(topNumber:Number) {
for(var i=0;i<topNumber;i++) {
trace(i);
}
}
countTo(6);
In this example, we first define a function called countTo that has parameter passed into it named topNumber. The function prints out the numbers from 0 to that number. After we define it, we call our function, passing in the number 6.
var numClips:Number = 0;
function clickHandler(event:MouseEvent):void
{
var box:Box = new Box();
addChild(box);
box.x = 5 + (numClips*15);
box.y = 50;
numClips++;
}
button.addEventListener(MouseEvent.CLICK, clickHandler);
One of the most powerful and most used objects in Flash and Actionscript is the MovieClip.
You can use MovieClips in Actionscript a number of different ways. One of the easiest ways is to "link" a MovieClip in your library to a Class which can then be referenced in Actionscript (Note: this has changed since Actionscript 2.0) To be able to access a movie clip from Actionscript, do the following:
The following example creates a new instance of a movie clip called box (after exporting it to Actionscript in the Library) and moves it to position (100, 100).
var box:Box = new Box(); addChild(box); box.x = 100; box.y = 100;