****UPDATED EXAMPLE FILE*****
Please try the above file and see if it is working for you. I changed the text fields to “use device fonts” and resaved it as CS5. I don’t know which of these made it work. Please let me know if it works for you, and if you still have trouble as you do the homework.
Topics:
- Building an Adding Machine
- Setting up Your File
- Creating the ActionScript
- Defining Variables
- Using Trace to Check Your Code
- Mathematical Operations
- Defining a Function
- Building the Interface
- Building Buttons and Button Actions
- Working with Text Fields
- Reading a value from a text box
- Writing a value to a text box
- Creating feedback / error messaging
- Conditional Statements
Today we are going to create a simple interface that allows the user to input two numbers and get the sum of them. This exercise uses some basic Actionscript fundamentals and connects them to interface elements built on the stage. This is how it’s going to look and work when we are finished with it:
And here are some example files to get us started:
Setting Up Your File
As your interfaces become more complex, it is especially important to keep your files organized. When you first open up your file, check the settings. Unless I tell you otherwise, you should be using Actionscript 3.0 and publishing for Flash Player 10 (if you are using CS4, Flash Player 9).
When you create a new file, the first thing you should do, before creating an elements on the stage, is to create a layer for your Actionscript, called “Actions”. All your code will go in this layer, and no display objects (anything on the stage) should go here.
Note: If you’ve only worked with Actionscript 2.0 previously, you should be aware that you can no longer apply code directly to symbols on the stage with AS 3.0.
As you are creating your interface, keep your layers organized and named. For the adding machine elements, I created two additional layers, one for the static elements like instructions text, and one for dynamic elements like the input boxes:
Creating the Actionscript
While you are still learning to code, it’s good practice to work out the logic and steps your application will need to perform before trying to hook it up to the interface. The first thing you need to figure out is what data you will need to keep track of. In the case of our adding machine, we need to take two numbers as input, and output a third number. Since the values of these numbers all depend on what the user puts in, we will need to create variables to hold those values.
Defining Variables
A variable is a construct to hold a piece of data that may change in the course of your code. In Actionscript, there are several types of data that a variable can hold:
- String - a single character or sequence of characters, in other words, text.
- Number - any kind of numerical value, including positive, negative, fractional and whole numbers.
- int – (integer) is a postive or negative whole number
- uint – (unsigned integer) is a postive whole number
- Boolean – stores only two values, true or false.
You define, or declare, a variable like this:
var NameOfVariable:VariableType;
Actionscript 3.0 requires that you define the type of variable when it is declared, and this can not change later in your script, so plan ahead!
So, if you want to define a variable of the Number type, it would look like this:
var x:Number;
Until you assign a value to the variable, it’s value is “undefined” or null. To assign a value to the variable, you use the = operator:
x = 12;
You can also declare and assign the value in one step:
var x:Number = 12;
Assigning a value to a String is a little bit different, because you want to be able to distinguish between a string of characters and another variable. So with a String, you put the value in double quotes:
var firstName:String = "Catherine";
Note: Variable names (and everything in ActionScript) are case sensitive, so X and x would be two different variables. You also can’t start a variable name with a number or a non-alphabetical character, and you should only use A-Z, a-z, numbers, and the underscore ( _ ) or hyphen ( – ) characters in your names.
Using Trace to Check Your Code
When you are working purely in code in the actions panel, you’ll want a way to check the data that the code is manipulating. You do this with a trace statement. trace is a built in method of ActionScript that allows you to send information to the Output panel in the Flash interface. Using it is simple:
trace(Something here);
In between the parentheses you can put anything – most commonly some combination of variable names and strings. If I wanted to get the current value of a variable named x I’d use trace like this:
trace(x);
If I wanted to output some abitrary text without first storing it in a variable, I’d put it between double quotes:
trace("Hello, World");
If you want to use a combination of variables and text, you can string them together using the + operator:
trace("The value of x is: "+x);
This is called concatenation and you can use it anywhere in your Actionscript that you want to combine Strings or add Strings and numerical values together. The result of this will be a String.
When you test your movie, anything in a trace statement is sent to the Output panel. This can be really useful for debugging!
Mathematical Operations
Once we’ve defined our variables and assigned values to them, we need to add them together to get a third value. To do this kind of simple arithmetic you can use standard mathematical operators:
x+y;
You’ll need to capture this new value somewhere though, so you can assign the value of the mathematical operation to another variable:
z = x+y;
Just remember that the variable that you are assigning the value to needs to be on the left side of the equals sign:
x+y = z <--- wrong!
Other arithmetic operators:
- - Subtraction
- * Multiplication
- / Division
- % Modulo
Most of these whould be self explanatory, but the modulo operator may be new. This operator returns the remainder after the second operand has been divided by the first. For example, 4 goes into 10 twice with 2 left over – 10 % 4 = 2.
Defining a Function
The code in Example 1 works, but you’ll notice pretty quickly that if you want to add another set of numbers, you’d have to duplicate all the code over again. And if you want to do this multiple times, this gets old pretty fast, and you think you might as well use a calculator.
This is where functions come in. Functions allow you to define a set of ActionScript statements in a neat little package that can be accessed and used from anywhere, anytime in your code, as many times as you need it. This is a big breakthrough in modern programming languages, and makes it infinitely easier to write complex applications.
A good way to think of a function is as a little machine — you put something into it, and something comes out the other end.
Functions have four parts:
- The function name
- The parameters (this is what goes “in”)
- The return value (this is what comes out)
- The function body (this is what the “machine” does with the input)
Function syntax looks like this:
function functionName(parameter1:datatype, parameter2:datatype):returntype {
function body
}
To call, or invoke, a function, you use the function name, followed by the parameters (also called arguments) enclosed by parentheses:
functionName(parameter1_value,
parameter2_value);
Functions have the ability to take and return values. These values can be of any datatype. If a function does not take any values, simply leave the parentheses empty. If a function does not return any values, the the return type must be specified as :Void. This is a function that does not take or return any values:
function basic():Void{
trace("This function doesn't do much.");
}
To call this function anywhere later in the code:
basic();
This function takes two numbers and returns a number:
function addMe(var x:Number, var y:Number):Number {
z = x + y;
return z;
}
When this function is called, you must pass it two numbers:
addMe (4,5);
This function call will add 4+5 and return 9.
Building the Interface
Now that we’ve got ActionScript that can perform the basic operations we need, we can start hooking it up to the interface elements. First we’ll look at the buttons.
Adding Actions to Buttons
Any MovieClip or Button symbol on the stage can be a “button”, which means to us that something happens when you click or hover over it. In Actionscript 2.0 you were able to add this directly to an object, in AS 3.0 you have to set up an Event Listener / Event Handler that targets the instance of the button.
An Event is either a user action like clicking the mouse or some kind of automatic happening like the movie entering a new frame or a certain span of time passing. In order to react to an event you must write two pieces of code:
Event Listener - This code keeps watch for a certain event to happen. When you set up a listener, you provide it with two things, the type of event you are listening for and the function that you to call when that event occurs. This is the syntax for an event listener:
yourObject.addEventListener(event_type, listener_method);
The event type includes Mouse and Keyboard inputs, frame events, and the loading of external data, among others. In the case of a button, we are talking about Mouse Events.
These are the AS 3.0 Mouse Events that you can set up a listener for:
- CLICK
- DOUBLE_CLICK
- MOUSE_DOWN
- MOUSE_MOVE
- MOUSE_OUT
- MOUSE_OVER
- MOUSE_UP
- MOUSE_WHEEL
- ROLL_OUT
- ROLL_OVER
So if we want to set up an event listener for a click event on a button called btn_equals, it would look like this:
btn_equals.addEventListener (MouseEvent.CLICK, onEqualsBtnClick);
In the code above, onEqualsBtnClick is the function that is called when the button gets clicked, called the Event Handler.
Event Handlers
The Event Handler is the function you call when the event happens. This function takes a single parameter, specifying the type of event being listened for. Generally these will either be “Event” or “MouseEvent”. The return type for listener methods is always “void”. The method will look something like this:
private function methodName(event:EventClass):void {
// this code will execute when the event is dispatched
}
Working with Text Fields
Dynamic and Input Text Fields have a property called text that contains the current value of the field. You can access this property of any named Text Field instance on the stage like so:
textFieldName.text;
It’s important to note that the data stored in the text property is automatically a String, so if you need to perform math on it, like we are doing with our adding machine, we have to convert it into a Number first:
Number(txt_x.text);
Once we’ve done that, we can assign it to a Number variable and do math on it.
But if we want to send the results back to a TextField, we have to convert it back into a String like this:
String(x);
Then we can set that as the text of the output field:
txt_z.text = String(x);
Creating feedback / error messaging
When you are creating a user interface, you want to make sure that you are giving good feedback to the user as things happen, and if something goes wrong, you let them know, and figure out how to handle it. This is called error handling. In the case of the adding machine, it is possible for the user to input something other than a number into the input boxes. If the script tries to add this together, the return value will be something calle NaN, or “Not a Number”. Now if the output box just says “NaN”, the user isn’t going to know what that means, or where they went wrong, so we need to react to this situation in a more friendly way.
Before the script even tries to add the number, we should make sure the inputs are numbers. If they are not, we need to tell the user. Notice the use of the work “if” in the previous statement. Anytime you find yourself with an “if” it’s time for another programming fundamental, the conditional statement.
Conditional Statements
A conditional statement will look familiar if you ever had to take a class on logic. What it says is if a certain condition is true, do something, if that condition is not true, do something else. The way we do this with ActionScript looks like this:
if (testExpression) {
codeBlock1
} else {
codeBlock2
}
When we work with conditional statements we need two new sets of operators, comparison operators and logical operators. These should also be familiar, even if the way we represent them in code is not.
Comparison Operators:
- < Less than
- > Greater than
- <= Less than or equal to
- >= Greater than or equal to
- == Equality
- != Inequality
- === Strict equality
- !== Strict inequality
The operators are used to compare the values of the expressions to the left and right of them. Take note of the difference between the assignment operator (=) and the equality operator (==). = is used to assign the value of the expression on the right to the left. == is used to compare the equality of two values. When you are comparing two things, never use =
Logical Operators
- && – the conditions on both the left AND right side are true
- || – the conditions of the left OR right side are true
- ! – the condition is NOT true
In Class Exercise –> Homework
- Using what we learned today design an interface and create Actionscript for the classic “Guess a Number” game.Create Actionscript that will play the “guess a number between one and X game”. Tell the user whether the number they input is too high, too low, or correct, and then allow them to guess until they get it right!(Hint: Use conditional statements!)

Week 2 assignment link:
http://www.kclarke.net/guess/
Week two assigment URL: http://www.happychinesenewyears.com/guess.htm