Академический Документы
Профессиональный Документы
Культура Документы
speaking actionscript
programming languages are used to send information to and
receive information from computers
programming languages have vocabulary and grammar used
to communicate, just like human languages
using a programming language we tell a computer what to
do or ask it for information
expressing logic
the art of programming lies in the formulation of logical
steps
think of programming a computer like talking to a child:
be explicit in every detail
list every single step that's necessary to complete a task
say hi to flash
select frame 1
type the following into the right side of the Actions panel:
var message = "Hi there Flash!";
that line of code constitutes a complete instruction, known
as a statement
now create three more statements:
var firstName = "your name here";
trace(message); trace("Hi
there, " + firstName + ", nice to meet you.");
the code doesn't do anything until we export a .swf file and
play the movie
select Control>>Test Movie
storing information
take another look at our first line of code
var message = "Hi there Flash!";
a literal translation for that code is:
Flash, please remember a piece of information for me...
...specifically, remember the phrase 'Hi there Flash!'
...please label the information message so that i can ask you for
it later
...whenever i ask you for message, give me back the text 'Hi
there Flash!
storing information is one of the foundations of programming
you can label stored information so that it can be used later
variables
look at our second line of code again:
var firstName = "your name here";
it asks Flash to remember our first name and label it firstName
Flash can remember any information that is considered a
valid type of data, such as numbers and text
in programming terms a piece of "text" is also known as
string
an individual piece of data is known as a datum
a datum (e.g., "Hi there Flash!") and the label that identifies it
(e.g., message) are together known as a variable
variable terminology
a variable's label ("message") is called its name
a variable's datum ("hi there Flash!") is called its value
a variable is said to "store" or "contain" its value
specifying a variable's value is called "assigning" or "setting"
the variable
to assign a variable a value, use the equals sign: =
creating a variable is called declaring it
to declare a variable, use the keyword var
example sentence: "declare a new variable named message,
and assign it the value "Hi there Flash!"
the interpreter
recall our third statement
trace(message);
it issues a command, trace, that causes data to appear in the
Output window
how does that work?
when you create a variable or issue a command, you're
actually addressing the ActionScript interpreter
the interpreter is the part of Flash that executes ActionScript
code
the interpreter does the following:
runs your programs
manages your code
listens for instructions
performs any ActionScript commands
stores your data
sends you information
calculates values
if the interpreter understands your commands, it sends them
to the computer's processor for execution
if a command generates a result, the interpreter provides
that response to you
if the interpreter can't understand the command, it sends
you an error message
for example, try running this code:
= "test";
the interpreter outputs an error. it doesn't expect the =
without a variable name
remember that the interpreter has to read your code, letter
by letter, and try to understand it
error messages are GOOD! because they help you fix your
code
arguments
commands usually require supplementary information to run
for example, the trace() command requires the text to display
the data sent to a command is called an argument
to supply an argument to a command, enclose the argument
in parentheses, like this:
command(argument);
to supply multiple arguments to a command, separate them
with commas, like this:
command(argument1, argument2, argument3);
supplying an argument to a command is known as passing
the argument
for example, in the code gotoAndPlay(5):
gotoAndPlay is the name of the command
5 is the argument being passed (the frame number)
some commands, (e.g., stop()) require parentheses but can
not be passed arguments. we'll learn why later
operators
take another look at our fourth line of code:
trace("Hi there, " + firstName + ", nice to
meet you.");
the + signs join (concatenate) our text together
+ is one example of a programming tool called an operator
operators are like conjunctions ("and," "or," "but," etc.) in
human languages
all operators link phrases of code together
most operators transform data in some way
example operators:
arithmetic: -, +, *, /
comparison: < (less than), > (greater than)
logic in a program
we make millions of basic decisions in our daily lives
for example, when crossing the road we decide:
if a car is coming, we wait for it to pass
if a car is not coming, we cross the road
a program must make similar decisions based on the state of
its environment
for example:
if the user has seen the website's introduction already, don't show it again
if the user specifies the wrong password to a restricted zone, don't show the restricted content
a "decision" in a program means choosing whether or not to
execute a section of code
conditional statements
to let a program decide whether to execute code, we use a
conditional statement (a.k.a., a "conditional")
generic conditional structure:
if (this condition is met) { then execute
these lines of code
}
for example:
if (username == "James Bond") {
trace ("Welcome to my website, 007."); }
the equality operator, ==, tests if two data values are equal
don't mistake the equality operator (two equal signs ==) with
the assignment operator (one equal sign =)!
to execute an alternative section of code when a condition is
not met, use an else statement
if (userName == "James Bond") {
trace ("Welcome to my website, 007."); } else
{ trace
("Sorry, only James Bond can use this site.");
}
to execute one of many possible sections of code, use else if:
if (userName == "James Bond") {
trace ("Welcome to my website, 007."); } else
if
(userName == "Moock") { trace("Welcome to my
website, Colin."); } else { trace ("Sorry,
only James Bond or Colin can use this
site."); }
repetitive tasks
suppose you want to display a five-number sequence in the
Output window, starting at any number
you could display the sequence like this:
trace(10); trace(11); trace(12); trace(13);
trace(14);
if you want to start the sequence at 513, you have to retype
all the numbers
trace(513); trace(514); trace(515);
trace(516);
trace(517);
to avoid this retyping, we use a variable:
var x = 1; trace (x); x = x + 1; trace (x); x
= x + 1; trace
(x); x = x + 1; trace (x); x = x + 1; trace
(x);
to change the sequence starting number, just change the
initial value of x
but what if we want to count to 500?
even with the variable, it's too much typing
loops
to perform repetitive tasks, we use a loop
a loop is type of statement that causes a block of code to be
repeated
here's what the counting example looks like as a while loop:
var x = 1; while (x <= 5) { trace (x); x = x +
1; }
the statements to repeat are listed between the brackets: { }
the keyword while starts the loop
the comparison (x <= 5) indicates when to quit repeating the
loop
the loop stops repeating when x is less than or equal to 5
to make the loop count to 500, simply change 5 to 500
functions
a function is a group of statements packaged together to
form a single, reusable command
functions let us write code once, but use it many times
throughout a program
repetition is bad
suppose we use this code to display the area of a rectangle:
var height = 10; var width = 20; trace(width *
height);
later we decide we want to display the area of five different
rectangles
our code gets 5 times longer:
var height1 = 10; var width1 = 20;
trace(width1 * height1);
var height2 = 234; var width2 = 59;
trace(width2 * height2); var height3 = 40;
var width3 = 99; trace(width3 * height3); var
height4 = 39; var width4 = 875;
trace(width * height); var height5 = 3; var
width5 = 2; trace(width5 *
height5);
notice that the same three statements are used for each
rectangle
repeating statements is error-prone and time-consuming
instead of repeating statements, create functions that
contain the repeated code
an example function
here's a function that displays the area of a rectangle
function displayArea (width, height)
{ trace(width * height);
}
the function keyword starts the function declaration
next comes the name of the function: displayArea
next comes a list of arguments used by the function, in
parentheses: (width, height)
finally, we list the statements of the function, within
brackets: { }
the statements contain the code that would otherwise have
been repeated
running a function
to run a function use same format as trace() command earlier
first, specify the function name:
displayArea
then provide any required arguments:
displayArea(10, 20);
the statements inside the function then run with width set to
10 and height set to 20
code comments
to add even more descriptive information to our code, we
use comments
a comment is a note in code that is meant to be read by
programmers
any line of code that starts with // is a comment:
// This is a comment...
comments help programmers understand how code works
you should always narrate your code with comments
for example...
// Displays the area of a rectangle in
Flash's Output window function displayArea
(width, height) { trace(width
* height); } // Display the area of five
rectangles
displayArea(10, 20); displayArea(234, 59);
displayArea(40, 99); displayArea(39,
875); displayArea(3, 2);
built-in functions
take another look at the command gotoAndPlay() from the
previous example:
gotoAndPlay("intro");
is a built-in function, provided by ActionScript
gotoAndPlay()
there are lots of built-in functions, and they are used just
like any other function
objects
let's review a couple of concepts:
a statement instructs Flash to do something
a function groups multiple statements into a convenient command
an "object" takes the next logical step: it packages related
functions and variables into a single code module
each object is like a self-contained, miniature program
multiple objects can be used together like building blocks to
form complex functionality
object-oriented programming
object-oriented programming (oop) means structuring your
code with objects
some languages require that all code be contained by some
object (e.g., Java)
in flash, you can put all your code in objects if you want, but
it's not mandatory
quiz overview
two questions; each with three multiple-choice answers
users submit their answers by clicking answer buttons
user answers are recorded in a variable
answer variables are used to calculate the user's score
at the end of the quiz, the score is displayed
event broadcast
every event in flash is triggered by some object
for example:
the Stage object tells you when the movie is resized
the Key object tells you when a key is pressed
a Button object tells you when a button is clicked
event-handler functions
to respond to a "button clicked" event from a button...
...define an event handler function on that button
theButton.onRelease = eventHandlerFunction;
theButton is the button instance that was clicked
onRelease is the name of the event
eventHandlerFunction is the function that should run when the button is clicked
the eventHandlerFunction can be defined inline or somewhere else
// Define the event hanlder function
inline... theButton.onRelease = function ()
{ // Store the user's answer
}
// Or define the event handler function
separately... theButton.onRelease =
storeAnswer; function storeAnswer ()
{ // Store the user's answer }
here's the general format for event handler functions:
eventBroadcastingObject.nameOfEvent =
eventHandlerFunction;
a little fun
break time! let's make a mouse toy
see mouseTrailer-01.swf through mouseTrailer-04.swf in /examples/visuals
folder
experimentation is key
build something simple, then play with it (change values,
parameters, etc)
centralizing code
our quiz has two problems:
the code is spread over three frames (hard to find, understand)
the button handler code is very repetitious (prone to error)
to fix these problems, we'll:
move all code to frame 1
introduce two functions: answer() and gradeUser()
subcontracting labour
notice that the answer() function calls a separate function,
gradeUser()
the code in gradeUser() could have been contained within
answer()
but its wiser to do one-task-per-function
following the one-task-per-function rule makes code:
easier to debug
more reusable (each function can be independently)
array elements
each item stored in an array is called an element
each element's position in the array is its index
indices start at 0
for example, here are the indices for shoppingList:
0: "oranges" 1: 5 2: "apples" 3: 2
the number of elements in an array is called its length
for example, the shoppingList's length is 4
array methods
an array is an object with methods to manage its elements
the push() method adds one or more elements to the end of
an array
for example:
// Create an array with 2 elements var
menuItems = ["home",
"quit"]; // Add an element // menuItems
becomes ["home", "quit", "products"]
menuItems.push("products"); // Add two more
elements // menuItems becomes
["home", "quit", "products", "services",
"contact"] menuItems.push("services",
"contact");
the pop() method removes the last element of an array
for example:
var numbers = [56, 57, 58]; numbers.pop(); //
numbers is now
56, 57 trace(numbers)
the unshift() method adds one or more elements to the
beginning of the array
for example:
// Create an empty array (notice the use of
the Array
constructor) var flashVersions = new
Array(); // Add an element flashVersions[0]
= 5; // Add another element, bumping the
previous 0 element up
flashVersions.unshift(4); // flashVersions is
now [4, 5] // Add two elements at
once flashVersions.unshift(2,3); //
flashVersions is now [2, 3, 4, 5]
the shift() method removes an element from the beginning of
an array
for example:
var sports = ["hackey sack", "snowboarding",
"inline
skating"]; sports.shift(); // Now
["snowboarding", "inline skating"]
sports.shift(); // Now ["inline skating"]
other methods perform various array manipulations:
sort and reverse reorder the elements in an array
splice() removes or adds elements from any part of an array
slice() and concat() create new arrays based on existing arrays
toString() and join() convert arrays to strings
building blocks
for our last bit of fun, we'll combine our earlier mouse
follower and random pattern experiments
remember that complex programs are just like lots of little
simple programs combined
see moveAway-01.swf through moveAway-07.swf in /examples/visuals
summary
code is fun, even when you only know a little!
you can learn a lot quite quickly
best way to improve: play and experiment