actionscript for flash object oriented programming oop

127
ActionScript For Flash Object Oriented Programming OOP

Upload: derrick-ramsey

Post on 26-Dec-2015

241 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: ActionScript For Flash Object Oriented Programming OOP

ActionScript For Flash

Object Oriented ProgrammingOOP

Page 2: ActionScript For Flash Object Oriented Programming OOP

Game Programmer

• Using programming languages such as C++ and Java, a programmer writes the code that allows a game’s text and graphics to be displayed, develops the control systems that allow a player to interact with the game, creates the camera system that allows the player to view the game world, programs the physics system that affects the player and game world, writes the AI system that controls enemies and object scripting… you get the idea.

Page 3: ActionScript For Flash Object Oriented Programming OOP

Game Programmer• One programmer may work exclusively on

tools to help team members build the game more efficiently. Another programmer may write code to simulate real-world physics making water look realistic or develop inverse kinetics for characters. Inverse kinematics is the process of determining the parameters of a jointed flexible object (a kinematic chain) in order to achieve a desired pose. Inverse kinematics is a type of motion planning. Inverse kinematics are also relevant to game programming and 3D animation, where a common use is making sure game characters connect physically to the world, such as feet landing firmly on top of terrain.

Page 4: ActionScript For Flash Object Oriented Programming OOP

Game Programmer• Like many of the jobs in the game industry

programming jobs are becoming more specialized. Regardless of the position, a programmer needs to have an excellent understanding of mathematics, 2-D and 3-D graphics, physics, particle systems, user interface, artificial intelligence, input devices, and computer networking. These skills are always in high demand and some programmers make a good living as contractors, moving from project to project as “hired guns”, writing code and providing temporary solutions to beleaguered teams.

Page 5: ActionScript For Flash Object Oriented Programming OOP

Fundamentals

• trace• variables• comparisons and conditions• loops• functions• relative paths and objects

Page 6: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Trace

• In Flash development environment, we can make good use of the trace function. With trace, we can display any text we want in the output window. The output window is simply an empty window that appears when we run a movie from within the development environment. This means that if we want to determine whether or not flash is actually executing a certain section of code, we could say something like:– trace (“I am executing this section now”);

Page 7: ActionScript For Flash Object Oriented Programming OOP

Fundamentals

• When we ran the movie, Flash would display “I am executing this section now” in the output window as soon as it reached that line of code. The trace statement is also very useful for showing the value of variables at any given time, with something like this:

trace (i);

or trace (“The value of i is “ + i);

Page 8: ActionScript For Flash Object Oriented Programming OOP

Fundamentals

• In the first case, you should see undefined, this happens because we have not defined the variable i. In the second case, “The value of i is undefined” will appear in the output window.

Page 9: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Variables

• Variables– In ActionScript, we can create and

manipulate variables much as in any other compatible programming language. By default, if you refer to a variable before it has been defined, it will return the value undefined.

Page 10: ActionScript For Flash Object Oriented Programming OOP

Fundamentals

• Numbers– At the core, variables are defined by simply

setting a value to a variable name, like so:j = 5;trace (“The value of j is “ +j);

– This would place the number value 5 in the variable j, and then display “the value of j is 5: in the output window. In this case, j is a number, and it can be adjusted with code as any number variable can be adjusted.

Page 11: ActionScript For Flash Object Oriented Programming OOP

Fundamentals

• For example:j=5;trace (“The next value of j is “ + (j + 1));

This would display the output “The next value of j is 6”, because we’re outputting (j + 1) and not merely j.

Page 12: ActionScript For Flash Object Oriented Programming OOP

Fundamentals

• In most programming languages, numbers are specified as either integer or decimal. In ActionScript, you don’t have to specify, Simply setting the variable will do the required work. So you can say:

j = 5;and that’s just as valid as sayingj = 5.1;

• In both cases, j will be a number, but in the second case, it will contain the decimal number 5.1 (also called a floating point number).

• Numbers can be manipulated in many ways. We can perform all of the basic arithmetic operations on them.

• As seen by the next two tables:

Page 13: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Basic Arithmetic Operations

Addition k = j + 1; Value 6

Subtraction k = j – 1;Value 4

Multiplication k = j * 2;Value 10

Division k = j / 2; Value 2.5As well, we can modify a number by simply adjusting its value with the increment and decrement operators, as seen in the next table:

Assume j = 5

Page 14: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Use of Increment and Decrement Operators

Increment by 1 j ++; Value 6

Increment by anything k = 5; Value 10j += k;

Decrement by 1 j --; Value 4

Decrement by anything k = 5; Value 0j -=k;

Assume j =5

Page 15: ActionScript For Flash Object Oriented Programming OOP

Fundamentals

• It’s important to know that incrementing with j ++ is faster and more optimized than incrementing with:

j = j + 1;

and decrementing with j – is more optimized than decrementing with:j = j - 1;

Page 16: ActionScript For Flash Object Oriented Programming OOP

Just for fun

Page 17: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Strings

• Strings– Strings are how we store words, letters

and sentences. Yes, we can also store numbers as a string if we wanted to. The default way to create a string is very much like creating a number variable, except we use quotes, like so:

s = “Hello World”;trace (s);

Page 18: ActionScript For Flash Object Oriented Programming OOP

Fundamentals

• When you run, this code would display the text “Hello World” in the output window. Unlike a number, we cannot perform any arithmetic on a string, but we can “add” strings together, like so:

s = “Hello”;t = “World”;trace (s + t);

• This code would display the text “HelloWorld” (with no space between the two words.)

Page 19: ActionScript For Flash Object Oriented Programming OOP

Fundamentals

• To place a space, we’d have to modify the code like so:

s = “Hello”;t = “World”;trace (s + “ “ + t);

or, we could have included the space character in the string, like so:

s = “Hello “;t = “World”;trace (s + t);

Page 20: ActionScript For Flash Object Oriented Programming OOP

Fundamentals

• When we use the + operator between two strings, then what we’re doing is known as concatenation. We’re concatenating the strings together into one long string. If we add a string and a number, we get a concatenation only, as shown:

k = “Hello”;g = “3”;trace (k + g);

This will send the text “Hello3” to the output window, even though g is a number and not a string. In fact, if we declare two variables that are both strings that contain numbers, the concatenation will still take place:

k = “5”;g = “3”;trace (k + g);

This would trace 53 to the output window, not 8, because the 5 and 3 are both strings, as they are defined with quotes, so they are simply placed next to each other, concatenated.

Page 21: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Booleans• Booleans

– A Boolean variable is a variable that has one of two values, true or false. A Boolean variable is used to keep track of states of thing, for example, has the player collected the magic ring? we might have a Boolean variable called hasRing, and it will be false until the player collects the ring, at which point hasRing will be set to true. Booleans are assigned and created like so:

hasRing = true;

orhasRing = false;

• There are no quotes placed around the true or false, as they’re not strings. They’re treated specially by flash. Generally, we can safely think of a Boolean as either zero or non-zero, where zero always evaluates to false, and anything non-zero evaluates to true. The result of any comparison always returns a Boolean value, but we’ll be looking at this shortly.

Page 22: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Comments• Any time you want to put text in your code

that you do not want to execute, you can convert it into a comment. These are readable only by the developer, and they’re ignored by the compiler. To place a comment, simply precede the line in the code with two forward slashes (//).

k = 4;// this is a commentk ++;

The line “this is a comment” has no bearing on the execution of the other two lines of code. It’s there strictly to make the code clearer to the reader. One of the useful applications of comments is to “comment out” a line of code if you temporarily don’t want it to execute.

Page 23: ActionScript For Flash Object Oriented Programming OOP

Fundamentals• You could take the aforementioned code and do this:

k = 4;// this is a comment// k ++;

Now k will not be incremented, because the line of code k++ will be ignored and skipped.

You can also comment out larger blocks of code by using a comment block. A comment block contains an opener /* and a closer */. Anything between the opener and closer will not run. For example:

k = 5;/*j = 4;k += j;*/

trace (k);While k would have been incremented by j, which was 4, it will

not now because we have commented out the two middle lines of code. All that will happen now is that k will trace out as 5.

Page 24: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Comparisons and Conditions• In ActionScript, we have all of the standard

comparisons and conditions that are in other programming languages. By using the if statement, we can perform any logic, which will, in turn, affect the flow of our program. At its core, the if statement works on the Boolean principle. It’s structured like this:

if (true){

//this code will execute}if (false){

//this code will not execute}

Page 25: ActionScript For Flash Object Oriented Programming OOP

Fundamentals• In cases in which you have only one single

line of code running based on the if, then you don’t need curly braces:

if (condition)trace (“My single line of output”);

Now, we don’t normally put the straight values true and false inside an if statement. we normally put conditions in the if statement, which in turn evaluate to Boolean true or false. For example, we could say this:

k = 5;if (k == 5){

trace (“k is indeed 5”);}

Page 26: ActionScript For Flash Object Oriented Programming OOP

Fundamentals• the condition is k == 5, which

means, “k must be equal to 5”. If it is (and it will be because we’ve set k to 5 just the line before), then the text “k is indeed 5” will trace to the output window. Remember, a condition results in a Boolean: true or false. So, if we do the following:

k = 5;trace ( k == 5);What will happen?

Page 27: ActionScript For Flash Object Oriented Programming OOP

Just for fun

Page 28: ActionScript For Flash Object Oriented Programming OOP

Fundamentals

• The word “true” will appear in the output window. We don’t need an if statement to evaluate a condition. On the other hand, we can say:

k = 5;trace (k == 6);

This will trace the word “false” to the output window, because the condition is false; k does not equal 6.

Page 29: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditionsa == b equalsa != b Not equal

a = 4;

b = 4;if (a == b){

trace (true)}if (a!=b){

trace (false)}

Page 30: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditionsa < b less thana <= b less than or equal toa > b Greater thana >= b Greater than or equal to

a = 4;b = 5;if (a <= b){

trace (true)}if (a >=b){

trace (false)}

Page 31: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditions

• All of these comparisons can be performed with either numbers or strings. For example:

s = “Hello”;t = “Hello”;if (s == t){

trace (“They’re Equal Hellos”);}

Page 32: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditions• We can also combine conditions by

using the AND and OR operators. The AND operator is specified like so:

if (condition 1 && condition 2){}

• The OR operator is specified like so:if (condition 1 || condition 2){}

Page 33: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditions• For example, “if you finish your homework

AND you are good for the sub you can go watch a movie.” It is clear that both of these conditions must be satisfied in order for the movie trip to occur. In code, this could be written like so:

homeWorkFinished = true;goodForSub = true;if (homeWorkFinished && goodForSub){

trace ("Let's watch the movie");}else{

trace ("No movie for you");}

Page 34: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditions• On the other hand, imagine this

statement. “if you get an A+ or you are good for the sub you will get to watch a movie.

grade = “A+”;goodForSub = false;

if (grade == “A+ “|| goodForSub){

trace (“You can watch a movie”);}else{

trace (“No movie for you”);}

Page 35: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditional Operation Results

• Condition 1 Operator Condition 2 Result

true && true truetrue && false falsefalse && false falsetrue || true truetrue || false truefalse || false false

Page 36: ActionScript For Flash Object Oriented Programming OOP

Just for fun

Page 37: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditional• The use of the NOT operator

becomes more applicable when we want to use a Boolean variable like so:

paidTicket = false;If (!paidTicket){

trace (“you haven’t paid your ticket”);}else{

trace (“It’s about time”);}

Page 38: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditional

• In the previous example, the text “You haven’t paid your ticket” would be traced to the output window, because paidTicket is false, meaning that NOT paidTicket is true, because NOT false is true. (When is a false not a false? When it’s a true.)

Page 39: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditional

• Along with the if statement, we have the else statement. When we say else, it’s as if we’re saying “otherwise.” Imagine this statement. “If you start the fire, you will be warm. Otherwise, you will be cold.” See if you can write this in code now.

Page 40: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditional

fire = false;if (fire){

trace (“you are warm”);}else{

trace (“You are cold”);}

Page 41: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditional

• We can, if we want, have more than two conditions, by using the else if statement. Imagine this statement. “if you have a chicken you will have chicken eggs, otherwise if you have a goose you will have goose eggs, otherwise you will have nothing.”

Page 42: ActionScript For Flash Object Oriented Programming OOP

Fundamentals ConditionalhaveChicken = false;haveGoose = false;

if (haveChicken){

trace (“You have a chicken, and chicken eggs.”);}else if (haveGoose){

trace (“you don’t have a chicken, but you do have” + “ a goose and its eggs”);

}else{

trace (“You have neither chicken nor goose eggs”);}

Page 43: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Conditional

• The nature of “if / else / else if “ is that it will move on to the next condition only if the previous condition is not satisfied. If we wanted to handle a case in which we wanted to allow for having both chicken and goose eggs, or just chicken eggs, or just goose eggs, or nothing. What would we have to do? Code it now.

Page 44: ActionScript For Flash Object Oriented Programming OOP

Fundamentals ConditionalhaveChicken = true;haveGoose = true;

if (haveChicken && haveGoose){

trace (“You have chicken and goose eggs.”);}else if (haveChicken){

trace (“You have a chicken, and chicken eggs”);}else if (haveGoose){

trace (“You don’t have a chicken, but you do have” + “ a goose and its eggs”);

}else{

trace (“you have neither chicken nor goose eggs”);}

Page 45: ActionScript For Flash Object Oriented Programming OOP

Just for fun

Page 46: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Loops

• The purpose of a loop in ActionScript is to provide us with a mechanism for repeating an action as many times as we want, without needing to re-write that action in code over and over. There are two types of loops that we’re interested in for this:– for loops and while loops

Page 47: ActionScript For Flash Object Oriented Programming OOP

Fundamentals For Loops• In a for loop, we’re essentially telling Flash to do

something “for” a certain number of time, just as we would say to someone “walk forward for 15 steps.” We could represent this action with code like so:

step = 0;trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));trace (“Taking step number ” + (step++));

Page 48: ActionScript For Flash Object Oriented Programming OOP

Fundamentals For Loops• That code would produce

Taking step number 0Taking step number 1Taking step number 2Taking step number 3Taking step number 4Taking step number 5Taking step number 6Taking step number 7Taking step number 8Taking step number 9Taking step number 10Taking step number 11Taking step number 12Taking step number 13Taking step number 14

Page 49: ActionScript For Flash Object Oriented Programming OOP

Fundamentals For Loops• Notice that we’ve repeated the same line of

code 15 times, and that we’ve also embedded the ++ increment within the line of code itself. We’re allowed to do this; the value of step will be incremented after it is used in the trace statement. If we wanted the value of step to be increased and then used in the trace statement we could say:

trace (“Taking step number “ + (++step));

It’s important to notice that it’s doing the code 15 times, even though the last step is number 14. This is because the first step is step 0, so it’s 15 steps total, starting with step 0, and ending with step 14.

Page 50: ActionScript For Flash Object Oriented Programming OOP

Fundamentals For Loops• So it’s pretty clear that there has to be a

better way of doing this. What if we wanted to take 150 steps or 1500 steps? Would we write the code 1500 times? No. We tell ActionScript to do something repeatedly, like so:

for (step = 0; step < 15; step++){

trace (“Taking step number “ +step);}

this will produce the exact same results as the previous example, except it has three lines of code rather than 15. The format of the for statement is as follows:

for (run this once; this must evaluate to true; do this every loop iteration)

Page 51: ActionScript For Flash Object Oriented Programming OOP

Fundamentals For Loops

• So, in our example, the first thing (before the first semicolon) is to set the value of step to 0. Then, before the second semicolon, we perform a check that must evaluate to true in order to proceed with the loop. Our check is simply the condition step < 15. This will only evaluate as true as long as step is less than 15 ( from 0 to 14 are true). Finally, the last part, after the second semicolon, is the code we want the loop to run each time it iterates. This usually revolves around incrementing, or in some way changing the loop variable. In our example, we’re incrementing step.

Page 52: ActionScript For Flash Object Oriented Programming OOP

Fundamentals For Loops

for (k = 0; k < 10; k++)for (k =0; k <= 10; k++)for (k = 9; k >= 0; k--)for (k =20; k >= 0; k-=2)

for (k = 0; k < 100; k+=2)

for (k = 10; k <= 100; k+=10)

for (k = 100; k > 2; k/= 2)

k will count up from 0 to 9.

k will count up from 0 to 10.

k will count down from 9 to 0.

k will count down from 20 to 0, in steps of 2

k will count from 0 to 98, incrementing by 2 each time. (0,2,4,6,8, and so on.

k will begin at 10, and will increment by 10 until it reaches 100.

k will begin at 100, and will divide in half until k is less than 2. this will cause k to be 100, 50, 25, 12.5, 6.25, 3.125.

Page 53: ActionScript For Flash Object Oriented Programming OOP

Fundamentals while Loops• The other type of loop is known as

the while loop. It’s analogous to saying, “Walk east while the sun is still shining.” We would write this like so:

minutesOfSunRemaining = 12;while (minutesOfSunRemaining > 0){

trace (“The sun is still shining”);minutesOfSunRemaining --;

}

Page 54: ActionScript For Flash Object Oriented Programming OOP

Fundamentals while Loops

• Write code using a while loop that steps down (in a trace output) the time remaining in class. Be creative.

Page 55: ActionScript For Flash Object Oriented Programming OOP

Fundamentals while Loops

• The while loop very simply evaluates a condition:

while (true){

trace (“doing this code forever and forever”)}orwhile (false){

trace (“will never see this trace”);}

Page 56: ActionScript For Flash Object Oriented Programming OOP

Fundamentals while Loops• If you were to run the previous example, while

(true), we would be stuck in what’s known as an infinite loop. There’s no way that condition, simply true, would ever, ever evaluate to false in order to end the loop. The Flash player would keep this up for about 15 seconds before presenting a dialog box, that says :A script in this movie is causing the Flash Player to run slowly. If it continues to run, your computer may become unresponsive. Do you want to abort the script?

• This warning message appears when Flash has been executing code, without proceeding to a new frame, for at least 15 seconds. This is to allow the users of their movies a way to prevent their computers from locking up. During this code execution (our infinite loop, for example), Flash will be consuming 100% of the user CPU time.

Page 57: ActionScript For Flash Object Oriented Programming OOP

Just for fun

Page 58: ActionScript For Flash Object Oriented Programming OOP

Fundamentals while Loops• However, this can sometimes become an

annoyance when you have legitimate code that is long and complex, and genuinely needs more than 15 seconds to compute. Flash will dutifully present the error message, and the user will be given the incorrect impression that your code has crashed.

• Even if you had text on screen that said something like, “Please wait, this will take 60 seconds to compute,” Flash will still intercede. It seems that the only way around this is to ensure that your code is able to run in 15 seconds or less. Or, you can also spread your code over multiple frames. Either way, this can be a challenge, but the error message generally appears only because programmers have accidentally caused Flash to enter an infinite loop within a frame.

Page 59: ActionScript For Flash Object Oriented Programming OOP

Fundamentals while Loops• The while loop is best used in situations in which we just

don't know how long we’re going to be doing something, and therefore need to constantly be evaluating the condition. For example, let’s say we have a series of variables called ball0, ball1, ball2, ball3, ball4, and so on. We could have four variables, or we could have 400. Let’s say that the variables were passed in from a server script in some way, so we just don’t know how many there are. We could do something like this:

k = 0;ball0=1;ball1=1;ball2=1;ball3=1;

while (this[“ball” + k] != undefined){

trace (“ball” + k + “ is valid”);k++;

}

Page 60: ActionScript For Flash Object Oriented Programming OOP

Fundamentals while Loops

• Don’t worry about what this means; we’ll be looking at that in the next section. What we’re doing here, starting with ball0, is checking to see if the variable indeed exists. We keep going while the variables exist, tracing out the message. This means that we successfully determined how many ball variables there were, and in fact, that number will now be stored in k, upon completion of the while loop.

Page 61: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Functions• So far, all the code we’ve looked at has

been placed directly on frame 1 of the main timeline, and when we run the movie, the code executes in linear order, from top to bottom. Because our movie has been one frame in length, Flash does not loop the code, and instead only executes it once, and then everything finishes up nicely. If we want, we can “package” code into a discrete container known as a function. For example:

k=0;trace (“k is “ +k);

Page 62: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Functions• We know what this code does. It sets the

value of k to 0, and then traces “k is 0” to the output window. But, what if we wanted to be able to run that code many times throughout our program? What if we wanted to almost think of it as a task of “zeroing k”? We could place it inside a function, like so:

function zeroK(){

k=0;trace (“k is “ + k);

}

Page 63: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Functions• That’s known as a function definition. now,

anywhere we want in our code (in the same timeline block—we’ll be looking at this next), we can simply “call” that function by saying;

zeroK();That’s known as a function call. Wrapping code

in a function allows us to call it as many times as we want, while not forcing us to rewrite the actual code contents of the function more than once. We have a two-line function with zerok, but we could also create a 2000-line function that would be called in the same manner.

The zerok function performs a specific task, and then ends. One of the other things we can do with a function is have it perform a specific task, and then return a value back to the code that called it. For example:

Page 64: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Functionsfunction double(n){

return n * 2;}k = double (10);trace(“10 doubled is “ +k);

What we’re seeing here is a function called double that takes one parameter. The parameter is specified in the brackets during the function definition, and in there we specify the variable name (n) to use inside the function for the value (10) that is passed in when the function is called.

When we call the double function, we’re passing in a value of 10, which is seen inside the brackets of the function call itself. With this, the function will be called, and n will be set to 10 for the duration of the call. By returning n * 2, we’re doubling the result, and then passing it back out into k.

Page 65: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Functions

• It’s also possible for a function to take more than one parameter. For example:

function addThemUp(a,b){

return (a + b);}k= addThemUp(15, 5);trace(k);

Page 66: ActionScript For Flash Object Oriented Programming OOP

Fundamentals FunctionsWe can create a function that returns a true or a

false Boolean value, like so:function hasMoney(balance){

if (balance > 0)return (true);

else return (false);

}myMoney = 43;if (hasMoney(myMoney)){

trace ("you have money!");}else{

trace ("You're broke.");}

Page 67: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Functions

All we need to do is check to see if the balance is greater than zero, and since that’s a condition, we can return the result of the condition directly. If balance is indeed greater than zero, then balance > 0 will return true. Otherwise, balance > 0 will return false; there’s no need for the if statement inside the function. By passing in myMoney, which is assigned 43, we are replacing balance with myMoney it passes 43 into the function hasMoney and evaluates true and returns it to the if statement which called it and traces out “You have money”.

Page 68: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Functions

• Write your own function definition. Give it two parameters. Have it perform a specific task, and then return a value back to the code that called it. (You can have it return either the result of a condition or a “true else false” Boolean value). Call it inside a trace so we can see the results.

Page 69: ActionScript For Flash Object Oriented Programming OOP

Just for fun

Page 70: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects

• One of the first questions that should come to mind is: What constitutes or defines an object in an OOP environment? What are the “characteristics” you can control, and how do you control them?

Page 71: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects• Simply put, most objects have three

primary things in common: methods (prebuilt functions specific to them, properties, and event handlers, each of which is defined by something called a class. The class is the primary structure that defines everything about an object: the object’s methods (things the object can do), the object’s properties (the characteristics or attributes of the object), and the object’s event handlers (things the object can react to).

Page 72: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects

• As a basic example, in general terms you could create a class named dog. Within that class, you could define methods for the dog, such as bark(); and wagtail();. You could create characteristics for the dog, such as name, breed, height, and weight (properties). You could also define events to which the dog would respond, such as on seeCat().

Page 73: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects

• Once you define a class for dogs, you could then create an instance of your dog and make it do something by calling one of the methods you set up for the dog. Although his example may seem simple, it is important to understand that classes define objects by establishing methods, properties, and event handlers for the object.

Page 74: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects• So far, we’ve looked at creating variables,

conditions, loops, and functions all within Frame 1 of the main timeline. This means that all of this code will be attached to what is known as the _root timeline. It’s important to understand that everything in ActionScript is “contained” within something else. Everything has a “parent,” and we refer to objects via their paths using a method known as dot notation. For example, if we have this code in Frame 1 of the timeline: k=0; That’s also the same as saying: _root.k=0;

Page 75: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects• The original line is being written in the

_root timeline. Think of it as the address of the variable. We can place variables inside of ActionScript objects, which are coincidentally enough, known as Objects. The _root timeline is essentially an object, but we can also create our own, and place variables inside of them, like so:

myObj = new Object();myObj.k = 0;myObj.s = “Hello”;

Page 76: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects

• Now, the Object called myObj, contains two variables, k and s. When a variable is attached to an object, it is usually referred to as a property. If we placed that code on the main timeline, Frame 1, then that myObj could also be referred to as _root.myObj.

• The reason for referring to _root becomes more obvious in a little while when we get into MovieClips, which contain their own timelines.

Page 77: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects

• We can also place functions inside of objects, like so:myObj = new Object();myObj.addThemUp = function (a, b){return (a + b);}trace (myObj.addThemUp(3, 5));

Page 78: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects• this would display the number “8” in the

output window. When a function is attached to an object, it is usually referred to as a method. We can make an object refer to its own properties with the use of the this keyword:

myObj = new Object();myObj.k=5;myObj.displayMyK =function(){

trace (this.k);}myObj.displayMyK();

Page 79: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects

• We’ve created myObj and inside it set the property k to 5, and then created a displayMyK method. Then, when we called myObj.displayMyK, it will trace the number 5 to the output window. When the word this is used within an object, it means, “referring to myself.” In fact, consider this situation:

Page 80: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objectsk=9;myObj = new Object();myObj.k =5;myObj.displayMyK = function(){

trace (k);}myObj.displayMyK();What will be displayed here?

Page 81: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects• The answer is, 9. When we don’t specify this

inside an object method, we’re telling Actionscript to refer to the k on the timeline that contains the function definition itself. We can fix the code:

k=9;myObj = new Object();myObj.k =5;myObj.displayMyK = function(){

trace (k);trace (this.k);}myObj.displayMyK();

This code will first trace 9, and then below that it will trace 5. Even though the variable is called k in both cases, the two k’s have different containers. The k that is 9 has _root as its container. The k that is 5 has myObj as its container.

Page 82: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects

• Due to the nested nature of ActionScript objects, it’s possible to create objects within objects, like so:myObj = new Object();myObj.innerObj = new Object();myObj.innerObj.k=5;

Now, one of the properties of myObj is another object, called innerObj. This hierarchy is an important concept to understand.

Page 83: ActionScript For Flash Object Oriented Programming OOP

Just for fun

Page 84: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects

• Think of it like this:myCountry = new Object();myCountry.name =“United States”;myCountry.myCity = new Object();myCountry.myCity.name =“Phelan”;myCountry.myCity.myStreet= new Object();myCountry.myCity.myStreet.name=“Tim

Buck Two”;trace (myCountry.name);trace (myCountry.myCity.name);trace (myCountry.myCity.myStreet.name);

Page 85: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects

• The objects are arranged hierarchically so that the street is inside of the city, and the city is inside of the country. This is a logical arrangement that mimics the way we would think of this real life situation. We could also create a generic function that handles the printout of the name, like so:

Page 86: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects

function printMyName(){

trace (this.name);}myCountry=new Object();myCountry.name = "United States";myCountry.printName=printMyName;

myCountry.myCity=new Object();myCountry.myCity.name = "Phelan";myCountry.myCity.printName=printMyName;

myCountry.myCity.myStreet =new Object();myCountry.myCity.myStreet.name = "Tim Buck Two";myCountry.myCity.myStreet.printName = printMyName;

myCountry.printName();myCountry.myCity.printName();myCountry.myCity.myStreet.printName();

Page 87: ActionScript For Flash Object Oriented Programming OOP

Fundamentals Relative Paths and Objects

• We’re creating a generic function called printMyName, which simply traces out this.name. We can then create methods inside of the objects, and set those methods to be the printMyName function. Yes, that’s right, we’re using a single function as the template for methods in three different places. When we assign one function to a variable name like this, we don’t need to use the brackets. We don’t say printName = printMyName(); because we’re not calling the function, we’re simply assigning a reference to it. Since we’re using the this operator, every time the method is called it will logically refer to the name property of the object who’s method is being called. So, myCountry.printName() will display “United States”, while myCountry.myCity.myStreet.printName() will display “Tim Buck Two”.

Page 88: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

• One of the most important concepts for us to understand when programming games in ActionScript is the concept of the array, and the intricacies of the Array class. Through the array we’re able to associate data in logical groups, almost like a list. In real life we might say, “the names of our gerbils are Herbie, Gordie, Lemmie, Sammie, and Kimmie.” With out the use of arrays , we might write this as:

Page 89: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

gerbilName1="Herbie";gerbilName2="Gordie";gerbilName3="Lemmie";gerbilName4="Sammie";gerbilName5="Gummie";gerbilName6="Kimmie";Now, let’s imagine that we want to add

the word “Gerbil” to the beginning of each of the gerbilName variables. So, we say this:

Page 90: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array ClassgerbilName1="Herbie";gerbilName2="Gordie";gerbilName3="Lemmie";gerbilName4="Sammie";gerbilName5="Gummie";gerbilName6="Kimmie";

gerbilName1 = "Gerbil " + gerbilName1;gerbilName2 = "Gerbil " + gerbilName2;gerbilName3 = "Gerbil " + gerbilName3;gerbilName4 = "Gerbil " + gerbilName4;gerbilName5 = "Gerbil " + gerbilName5;gerbilName6 = "Gerbil " + gerbilName6;

trace (gerbilName1);trace (gerbilName2);trace (gerbilName3);trace (gerbilName4);trace (gerbilName5);trace (gerbilName6);

Page 91: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

• Now, each variable will contain the values shown in the trace. That was somewhat easy but what would happen if we didn’t have six gerbils, but instead we had 600 gerbils? How could we organize this kind of data, without creating 600 individual string variables? We can use an array. With the array, we can assign our gerbil names like so:

Page 92: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

gerbilName = new Array("Herbie", "Gordie", "Lemmie", "Sammie", "Gummie", "Kimmie");trace (gerbilName[0]);

Now, there’s only one variable, gerbilName, that contains every single one of the gerbil names. How do we access a particular gerbil’s name? We use something called an index. This traces out Herbie, since the first index in our array is index 0; that is, index 0 refers to the first gerbil in the list. If we wanted to see the last gerbil in this list, that would be index 5.

Page 93: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

gerbilName = new Array("Herbie", "Gordie", "Lemmie", "Sammie", "Gummie", "Kimmie");for (k = 0; k < gerbilName.length; k++){

trace ("Gerbil number " + k + " is named " + gerbilName[k]);}

Page 94: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

• And, if we wanted to do our original task of adding “Gerbil” to the name, we’d go like this:

gerbilName = new Array("Herbie", "Gordie", "Lemmie", "Sammie", "Gummie", "Kimmie");for (k = 0; k < gerbilName.length; k++){

gerbilName[k] = "Gerbil " + gerbilName[k];

trace ("Gerbil number " + k + " is named " + gerbilName[k]);}

Page 95: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class• Each item in the array is known as an

element. Notice that we’re not specifying an exact number of elements, but rather we’re using gerbilName.length. The length property returns the number of elements in an array. In the case of our gerbilName array, that will be 6. By using gerbilName. length, it’s as if we said:

gerbilName = new Array("Herbie", "Gordie", "Lemmie", "Sammie", "Gummie", "Kimmie");

for (k=0; k<6; k++){

gerbilName[k] ="Gerbil " + gerbilName[k];trace ("Gerbil number " + k + " is named " + gerbilName [k]);

}

Page 96: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

• It’s also possible to create an array in steps, rather than in one line like the gerbil names were. If you wanted to create an array with 5000 random numbers, you could do this:

randomNums = new Array();for (k=0; k < 5000; k++){

randomNums[k] = Math.random() * 100;}

trace ("The element number 400 in our array is: " + randomNums[399]);

Page 97: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class• This would fill randomNums array with 5000

numbers. Besides strings and numbers, an array can also contain objects and can even contain other arrays. We could create an array of 200 objects like so:

objectArray = new Array();for (k=0; k < 200; k++){objectArray[k] = new Object();objectArray[k].owner ="Human";objectArray[k].height =Math.random() *7;objectArray[k].age=Math.random() * 99;}trace (objectArray[140].owner);trace (objectArray[140].height);trace (objectArray[140].age);

Page 98: ActionScript For Flash Object Oriented Programming OOP

Just for fun

Page 99: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

• That would have created an array of 200 objects called objectArray, and each object itself will contain a string, owner, and two random numbers, height and age. On the other hand, you could do this: (Do not code this)

objectArray = new Array();for (k=0; k < 200; k++){objectArray[k] = new Array();}

Page 100: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

• This would create an array of arrays, and any element could be referred to as:

objectArray[j][k];

this is also what we call a multidimensional array. Rather than just one row of data, like just the gerbil names, you can create a grid of data. So, imagine we have gerbil ages, and the names of gerbils that are that age. From the standpoint of a multidimensional array (in this case, a two-dimensional array), we would represent the data like so:

Page 101: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

• Age 0 Age 1 Age 2 Age 3 Roy Pickle Ham Jumper Dave Fuzzers Cheese Bob Twitch

Page 102: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array ClassgerbilName = new Array();for (k=0; k<4; k++){

gerbilName[k]= new Array();}gerbilName[0][0] ="Roy";gerbilName[0][1] ="Dave";gerbilName[0][2] ="Bob";

gerbilName[1][0] ="Pickle";gerbilName[1][1] ="Fuzzers";

gerbilName[2][0] ="Ham";gerbilName[2][1] ="Cheese";gerbilName[2][2] ="Twitch";

gerbilName[3][0] ="Jumper";trace ("Gerbil " + gerbilName[3][0] + " is 3 years of age.");

Page 103: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

• The first element in the array is the year (the first square brackets), and the second element is the gerbil number (the second square brackets). In games, two-dimensional arrays are often used to represent game grids. Imagine the following 3 x 3 game grid, where each position of the grid either contains a 0 or a 1, for solid or hollow:

Page 104: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array ClassgameGrid = new Array();for (k=0; k<3; k++)

{ gameGrid[k] = new Array(); for (j=0; j< 3; j++) {

gameGrid[k][j] =Math.floor(Math.random() * 2); }

} trace ("Box number 1 in row 1 has " + gameGrid[0][0]); trace ("Box number 2 in row 1 has " + gameGrid[0][1]); trace ("Box number 3 in row 1 has " + gameGrid[0][2]); trace ("Box number 1 in row 2 has " + gameGrid[1][0]); trace ("Box number 2 in row 2 has " + gameGrid[1][1]); trace ("Box number 3 in row 2 has " + gameGrid[1][2]); trace ("Box number 1 in row 3 has " + gameGrid[2][0]); trace ("Box number 2 in row 3 has " + gameGrid[2][1]); trace ("Box number 3 in row 3 has " + gameGrid[2][2]);

Page 105: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class• It’s also possible to use non-numbers

as the elements in arrays. You can use a string, for example:

colorList =new Array();colorList["red"] = 0xFF0000;colorList["green"] = 0x00FF00;colorList["blue"] = 0x0000FF;myColorToUse =colorList["red"];trace (myColorToUse);

This would set the variable myColorToUse to 0xFF0000, which is the hexadecimal value for the RGB color red.

Page 106: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class• There are several methods used to

modify arrays in various ways. We can use these methods to join arrays, split them, add and remove elements, and sort them. Some of them are as follows:Array.concat()The Array.concat method takes any number

of parameters and combines them into an array. You can use it to combine arrays of numbers, strings or arrays.

Page 107: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

array1 = new Array("hi", "bye");array2 = new Array(1, 2, 3);array3 = new Array(9, 8, 7);

newArray = array1.concat(array2, array3);

trace (newArray);

Page 108: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array ClassArray.join()Array.join() takes all of the elements in an

array and joins them into one string, each element being separated by the parameter passed into the join method. So for example:

myArray =new Array("One", "Two", "Three");joined =myArray.join("*");trace (joined);

Page 109: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class

Array.reverse()Array.reverse reverses the direction of an

array. So, 6,7,8,9 would be 9,8,7,6.myArray =new Array("One", "Two", "Three");joined =myArray.reverse();trace (joined);

Array.sortmyArray =new Array("One", "Two", "Three");joined =myArray.sort();trace (joined);

Page 110: ActionScript For Flash Object Oriented Programming OOP

Just for fun

Page 111: ActionScript For Flash Object Oriented Programming OOP

Fundamentals The Array Class• All that we’ve talked about here

represents but a small portion of ActionScript. This has been meant to get you up to speed with what you’ll basically need to know in order to program the games you will be choosing.

• To truly get deep into the ActionScript language, you should consult the ActionScript reference and dictionary that come with the Macromedia Flash MX 2004 development environment. It’s thorough, and cross referenced in so many ways that it’s highly usable.

Page 112: ActionScript For Flash Object Oriented Programming OOP

Math and Science in Games

• When you're playing a computer game, have you ever wondered how come, when your characters move around their virtual world, they interact realistically with their environment? If you think about it, you'll quickly realize that there is no way games developers could have predicted the exact sequence of events that occurred in that precise game session. Something more general must be happening - there must be some physics in the game's virtual world.

Page 113: ActionScript For Flash Object Oriented Programming OOP

Game Theory

Game theory is a branch of mathematics concerned with decision-making in social interactions. It applies to situations (games) where there are two or more people (called players) each attempting to choose between two more ways of acting (called strategies). The possible outcomes of a game depend on the choices made by all players, and can be ranked in order of preference by each player.

Page 114: ActionScript For Flash Object Oriented Programming OOP

How math is used in Games

• If you've got an object moving on the screen, it has a position, which can be described as (x, y) (Cartesian coordinate system)

Page 115: ActionScript For Flash Object Oriented Programming OOP

Just for fun

Page 116: ActionScript For Flash Object Oriented Programming OOP

Kathie Flood, Program Manager

• My mathematics background is instrumental for me in two ways. First, I have a strong understanding of the higher-level mathematics required to provide realistic physics and next-generation 3-D graphics in today's games. This enables me to work effectively with the programmers and artists responsible for these features, anticipating and understanding their challenges. Second, the problem-solving skills I learned while studying mathematics and as a programmer are absolutely invaluable. Much of my ability to break complex issues into solvable pieces, find creative solutions, and execute methodically, I credit to my mathematical education.

Kathie FloodBA Mathematics/Computer Science, Central CollegeMA Journalism/Mass Communications,Drake University

Program Manager,Microsoft Games Studios

Page 117: ActionScript For Flash Object Oriented Programming OOP

Cartesian Coordinate

• Cartesian coordinates are the foundation of analytic geometry, and provide enlightening geometric interpretations for many other branches of mathematics, such as linear algebra, complex analysis, differential geometry, multivariate calculus, group theory, and more. A familiar example is the concept of the graph of a function. Cartesian coordinates are also essential tools for most applied disciplines that deal with geometry, including astronomy, physics, engineering, and many more. They are the most common coordinate system used in computer graphics, computer-aided geometric design, and other geometry-related data processing.

Page 118: ActionScript For Flash Object Oriented Programming OOP

How it Works

A student will want it to move smoothly, but computers work in discrete time fragments at discrete distances. Fortunately, if a student makes the time intervals short enough, it looks to the user like continuous motion (this is the fundamental idea behind calculus.)

Page 119: ActionScript For Flash Object Oriented Programming OOP

The Calculus Word

•Calculus is the study of change, in the same way that geometry is the study of shape and algebra is the study of operations and their application to solving equations.

Page 120: ActionScript For Flash Object Oriented Programming OOP

The Calculus Word AgainBut how does a student make the object move in a certain direction? They need to have new variables to determine how much the object should move:x = x + dxy = y + dythus (dx, dy) is a new pair which describes the motion of an object in the current frame. (dx, dy) is also considered a motion vector. If you remember dx from calculus class, yep, it's the same dx. (although used slightly differently in game development than pure calculus)

Page 121: ActionScript For Flash Object Oriented Programming OOP

OMG Trig

• Trigonometry (called "trig" for short) (from Greek trigōnon "triangle" + metron "measure")[1] is a branch of mathematics that deals with triangles, particularly those plane triangles in which one angle has 90 degrees (right triangles). Trigonometry deals with relationships between the sides and the angles of triangles and with the trigonometric functions, which describe those relationships.

Back

Page 122: ActionScript For Flash Object Oriented Programming OOP

OMG Its TrigBut what if a student knows the angle and speed they want their object to go, but not the dx and dy values they need to make it go there?Trig is used here:dx = speed * cos(angle)dy = speed * sin(angle)Game programmers LOVE these formulas. We think of them as old friends, because they help us solve otherwise challenging problems. Say a student wants to build a space game with realistic orbits. Orbits seem hard, because they behave in very specific ways:

Page 123: ActionScript For Flash Object Oriented Programming OOP

Your Going to Love Math

The good news is, they won't hate math anymore. Students won't think of math as a bunch of problems, but as beautiful and elegant solutions. If they are going to be a 3D animator or level designer, they won't need quite as much math as the hard-core programmers, but they'll still be using quite a bit. 3D animation and level-design are still mathematical disciplines.

Page 124: ActionScript For Flash Object Oriented Programming OOP

Math and OMG Physics

They are elliptical paths, the planet is one focus, the satellite travels faster near the planet, and thrust in the direction of orbit to raise the other side of the orbit.Imagine writing a program that can make orbits act realistically. It sounds very difficult, but if a student understands the math and physics, it's no big deal.

Page 125: ActionScript For Flash Object Oriented Programming OOP

Your Friend NewtonThey just have to understand that gravity is a force, and it's calculated by a formula derived by Newton: f = (m1 * m2)*G / d^2. When a student learns how to apply that formula, they can make all kinds of great gravity-based games. It's certainly possible to write applications without a lot of math, but games are different. Start to write games. It won't take long before a student realizes you can't do much without math.

Page 126: ActionScript For Flash Object Oriented Programming OOP

Just for fun

Page 127: ActionScript For Flash Object Oriented Programming OOP

Just for fun