Slides - SCM Sweb

Download Report

Transcript Slides - SCM Sweb

SM1205 Interactivity
Topic 06:
Iteration and Multiple Objects
Spring 2012
SCM-CityU
1
Overview
• Technologies
– for loop and iteration
– Array data type
• Examples
Spring 2012
SCM-CityU
2
SM1205 Interactivity
Iteration and for Loop
Spring 2012
SCM-CityU
3
Control Multiple Objects
• How to control multiple objects with similar
behaviors?
Spring 2012
SCM-CityU
4
Control Multiple Objects
• Straightforward solution
– Manually assign different names to each object
– Duplicate same code for all objects
s1
s5
s4
s2
s3
Spring 2012
SCM-CityU
s6
s7
5
Control Multiple Objects
• But how about too many objects?
– E.g., 100 circles with random position and size
Spring 2012
SCM-CityU
6
Control Multiple Objects
• Iteration is a better solution
– Loop and operate on multiple objects
– Code once run many!
– No need to assign different names to all objects
• Today’s focus: to understand iteration (looping)
in AS 3.0
Spring 2012
SCM-CityU
7
Iteration
• Example – output text from 1 to 10
• Simple … right?
Spring 2012
SCM-CityU
trace(1);
trace(2);
trace(3);
trace(4);
trace(5);
trace(6);
trace(7);
trace(8);
trace(9);
trace(10);
8
Iteration
• How about printing numbers from 1 to 100?
• Copy and paste?
– Not a good idea
– Long code
– Hard to debug
trace(1);
trace(2);
trace(3);
trace(4);
trace(5);
trace(6);
trace(7);
trace(8);
trace(9);
trace(10);
trace(11);
…
trace(99);
trace(100);
Spring 2012
SCM-CityU
9
Iteration
• Can we only use fewer lines of code?
• Yes we can!
for (var i:int = 1; i <= 100; i++) {
trace(i);
}
• Let’s try it out
Spring 2012
SCM-CityU
10
for Looping Structure
• Syntax
– Starting with for keyword
for (declare counter; condition; update counter) {
// statement(s) to execute repeatedly
// as long as condition is true
}
• Typically counter is related to number
of current iterations and condition is
related to number of total iterations
– Example
for (var i:int = 1; i <= 100; i++) {
trace(i);
}Spring 2012
SCM-CityU
11
for Looping Structure
Running order
1. Declare counter
2. Condition checking
–
If condition is true
a.
b.
c.
–
Spring 2012
First run statements within block
Then update counter
Go to the beginning of Step 2
(starting another iteration)
Otherwise, exit for looping and
continue running the program
SCM-CityU
12
Running Order Example
var i:int = 1;
for (var i:int = 1; i<=3; i++) {
trace(i);
}
// declare counter
// iteration 1
if (i <= 3) {
// condition checking
trace(i); // looping body
i++;
// update counter
}
// iteration 2
if (i <= 3) {
// condition checking
trace(i); // looping body
i++;
// update counter
}
// iteration 3
if (i <= 3) {
// condition checking
trace(i); // looping body
i++;
// update counter
}
Spring 2012
// SCM-CityU
i <=3 is false, exit looping
13
for (declare counter; condition; update counter) {
// statement(s) to execute repeatedly
// as long as condition is true
}
• declare counter, condition, update counter are all optional in
syntax
– But two semicolons ; are always needed
• The first to separate counter declaration from condition
and second to separate condition from counter updating
• The following examples are equivalent
for (var i:int = 1; i<=3; i++) {
trace(i);
}
var i:int;
for (i = 1; i <= 3; i++) {
trace(i);
} Spring
2012
var i:int = 1; // init counter externally
for (; i <= 3; i++) {
trace(i);
}
for (var i:int = 1; i <= 3;) {
trace(i);
i++; // update counter internally
}
SCM-CityU
14
More for Looping Examples
// example of decreasing counter
for (var i:int = 3; i >= 1; i--) {
trace(i);
}
// example of incrementing counter by 2
// print all even numbers in [0, 20)
for (var i:int = 0; i < 20; i += 2) {
trace(i);
}
// counter can be used by multiple for loops
var i:int;
Spring 2012
// will 0 and 5 be printed?
for (i = 0; i < 5; i++) {
trace(i);
}
// will 0 and 5 be printed?
for (i = 5; i >= 0; i--) {
trace(i);
}
SCM-CityU
15
Class Exercise
• Print all odd numbers within a given range
– E.g., range = [1, 20]
– E.g., range = [50, 100]
• Hint: i % 2 == 1 if a number i is an odd number
– Remember: % operator gives you the remainder of
i/2
Spring 2012
SCM-CityU
16
Nested for Structure
• Syntax
– Usually need individual counters
// outer loop
for (declare counter1; condition1; update counter1) {
// optional statement(s) before inner loop
...
// inner loop
for (declare counter2; condition2; update counter2) {
// statement(s)
}
// optional statement(s) after inner loop
...
}
Spring 2012
SCM-CityU
17
Example: Printing Prime Numbers
• 2, 3, 5, 7, …
var range_start:int = 10;
var range_end:int = 50;
for (var i:int = range_start; i <= range_end; i++)
{
var isPrime:Boolean = true;
starting from 2 to i-1
if i can be divided by
j, i is not prime
for (var j:int = 2; j<i; j++) {
// if i can be represented by j*some_num
// then i is not a prime number
if (i % j == 0) {
isPrime = false;
}
}
if (isPrime) {
trace(i);
}
Spring 2012
}
SCM-CityU
18
Other Looping Structures in AS
• while and do-while looping structures
– We won’t cover details for those structures
while (condition) {
// statement(s) to execute repeatedly
// as long as condition is true
}
do {
// statement(s) to execute repeatedly
// as long as condition is true
} while (condition);
Spring 2012
SCM-CityU
19
SM1205 Interactivity
Array
Spring 2012
SCM-CityU
20
Store/Process Multiple Objects
• We already know how to create a lot of
objects/numbers using for loops
– E.g., a series of prime numbers, odd numbers
• How to store those objects or numbers?
– Store them into individual variables?
• How to name those variables?
• How to access those variables easily?
• Not convenient!
Spring 2012
SCM-CityU
21
Solution: Using Array
•
Array can store multiple data with one
variable name
– Can hold any type of data
– Each element can be individually read or written
•
Example
// create an Array variable with size = 3
var a:Array = new Array(3);
// set values for individual elements
a[0] = 1;
a[1] = 2;
a[2] = 3;
1 2 3
trace(a);
Spring 2012
Variable name: a
SCM-CityU
22
Create Array Variables
• Array is a complex data type
– Use keyword new to create Array variables
• If you know desired number of elements, say 10
var a:Array = new Array(10);
a
• Otherwise, create 0-size (empty) array first
var a:Array = new Array();
– Insert new elements using push method later on
Spring 2012
SCM-CityU
23
Create Array Variables
• If you even know elements values, use
var a:Array = new Array(val1, val2, val3);
– Or
var a:Array = [val1, val2, val3];
• Examples
var gender:Array = ["female", "male"]; // square brackets
trace(gender);
var grades:Array = new Array("A+", "A", "A-", "B+"); // parentheses
trace(grades);
Spring 2012
SCM-CityU
24
Review: Brackets (wiki)
• Parentheses: ()
– Function parameter list
– Precedence ordering
trace(para1, para2, para3, …, paraN);
trace((2 + 3) * 4); // 20
• Braces: {}
– Define a block, which
groups a set of statements
if (female) {
trace("female");
trace("hobby: shopping");
}
• Box/square brackets: []
– Array
Spring 2012
var a:Array = [val1, val2, val3];
SCM-CityU
25
Access Array Elements
• Each element in an array has a unique index
• Use ArrayName[elementIndex] to access element
with index=elementIndex
– E.g., first element of a: a[0]
• Index is 0-based and always integer
• Second element is a[1]
– E.g., last element of a: a[a.length-1]
• Array’s property length tells the length of an array
• a[a.length] is illegal. Why?
Spring 2012
SCM-CityU
26
Access Array Elements
• Array elements are readable and writable
– Individual array elements behave like ordinary
variables
• Though they have no names
var a:Array = [1, 3, 5, 7];
1 3 5 7
var sum:Number = a[1] + a[2]; // add two elements
trace(sum);
a[2] = 10; // change 3rd element's value
trace(a);
1 3 10 7
Spring 2012
SCM-CityU
27
Access Array Elements
• for loops are often used to process data
represented by arrays
var a:Array = [1, 3, 5, 7];
// sum up all array elements
// from a[0] to a[a.length-1]
// not including a[a.length]
var sum:Number = 0;
for (var i:int = 0; i < a.length; i++) {
sum += a[i];
}
trace(sum);
Spring 2012
SCM-CityU
28
Insert/Removing Elements
• Use push method to add a new element to the end of
the array
• Use pop method to remove the last element from the
array
var a:Array = [1, 3, 5, 7];
a.pop(); // remove last element
trace(a);
// insert two new elements
a.push(10);
a.push(20);
trace(a);
Note: there are other methods to insert/remove elements. Check out online reference
Spring 2012
SCM-CityU
29
SM1205 Interactivity
Examples
Spring 2012
SCM-CityU
30
Example: Swimming Ducks
• We will learn
– How to dynamically create objects (ducks!)
– How to store/access objects with Array and for
looping structure
Spring 2012
SCM-CityU
31
Dynamically Creating Display Objects
in AS
• Why not just using authoring tool?
– Reason: AS allows us to create multiple display
objects very easily
• How?
– Idea: use for loop
– For each iteration,
• Create a new display object (e.g., a duck)
– Syntax: var a:SomeDataType = new SomeDataType();
• Add it to stage
Spring 2012
SCM-CityU
32
Dynamically Creating Display Objects
in AS
But what’s associated
data type we can use
in AS?
Spring 2012
SCM-CityU
33
Defining Data Type for Symbol
• Define a data type for a symbol when you create it
Spring 2012
SCM-CityU
34
Defining Data Type for Symbol
• You can simply ignore this warping by hitting OK
Spring 2012
SCM-CityU
35
Instance Name vs Class Name
• Instance name: like variable name in AS
– If your AS wants to directly assess some existing symbol instance on
stage, assign instance name
• Class name: like data type in AS
– If your AS wants to dynamically create new symbol instances, create
class name for your symbol!
• Class naming style is the same as
variable/instance naming style
This name has
no special usage
Spring 2012
SCM-CityU
36
Adding Visual Obj to Stage
• AS uses display list to organize all display objects
on stage (ref)
– A hierarchical list of all visual objects
Spring 2012
SCM-CityU
37
Adding Visual Obj to Stage
• Use addChild method to add display objects to stage
• Use removeChild method to remove display objects
from stage
var s:MySymbol = new MySymbol ();
s.x = 50;
s.y = 100;
addChild(s);
//removeChild(s);
Spring 2012
SCM-CityU
38
Class Exercise
• Add two symbol instances to stage using AS
Spring 2012
SCM-CityU
39
Duck Example
1. File > Import > Import to Library
–
Import a duck image
2. Give a class name: SymbolDuck
–
Spring 2012
Make sure symbol type is Movie Clip
SCM-CityU
40
Task 1
• Enable options
– Export for ActionScript
– Export in frame 1
• This creates a data type,
called SymbolDuck in
AS, for Symbol Duck
– var duck:SymbolDuck
= new SymbolDuck();
Spring 2012
SCM-CityU
41
Class Exercise
• Create a duck and add it to stage using AS
Spring 2012
SCM-CityU
42
Class Exercise
• Create 5 ducks using for loop and store them into an
array (var ducks:Array)
– Set ducks’ positions like those in the figure below
Spring 2012
SCM-CityU
43
Make Ducks Swimming
• Let’s add a ENTER_FRAME event to animate ducks
– Move them from right to left
• Constant moving speed is boring
• So how about having some random moving speed?
– Math.random() generates a random number in-between 0
and 1
Spring 2012
SCM-CityU
44
Spring 2012
SCM-CityU
45
Class Exercise
• Task 1
– Make the ducks enter the stage from right side when they go
outside of the stage
• Hint: borrow idea from our previous ping-pong example
Spring 2012
SCM-CityU
46
Class Exercise
• Task 2
– Dynamically add ducks at mouse-clicked positions
• Add event listener for MouseEvent.CLICK
• Use Array.push method to add newly created duck to array
– Similar to what we did
for creating first 5 ducks
Spring 2012
SCM-CityU
47
Class Exercise
• Task 1: dynamically create a large number of shapes
(e.g., circles) with random
– Size
– Position
– Alpha
• Task 2: remove
clicked shape from
stage
– Use removeChild
Spring 2012
SCM-CityU
48