48
M1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012 SCM-CityU 1

SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Embed Size (px)

Citation preview

Page 1: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

SM1205 Interactivity

Topic 06: Iteration and Multiple Objects

Spring 2012 SCM-CityU 1

Page 2: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Overview

• Technologies – for loop and iteration – Array data type

• Examples

Spring 2012 SCM-CityU 2

Page 3: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

SM1205 Interactivity

Iteration and for Loop

Spring 2012 SCM-CityU 3

Page 4: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Control Multiple Objects

• How to control multiple objects with similar behaviors?

Spring 2012 SCM-CityU 4

Page 5: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Control Multiple Objects

• Straightforward solution– Manually assign different names to each object– Duplicate same code for all objects

SCM-CityU 5

s1

s2

s3

s4

s5

s6s7

Spring 2012 SCM-CityU 5

Page 6: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Control Multiple Objects

• But how about too many objects?– E.g., 100 circles with random position and size

Spring 2012 SCM-CityU 6

Page 7: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

SCM-CityU 7Spring 2012 SCM-CityU 7

Page 8: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Iteration

• Example – output text from 1 to 10

SCM-CityU 8

• Simple … right?

trace(1);trace(2);trace(3);trace(4);trace(5);trace(6);trace(7);trace(8);trace(9);trace(10);

trace(1);trace(2);trace(3);trace(4);trace(5);trace(6);trace(7);trace(8);trace(9);trace(10);

Spring 2012 SCM-CityU 8

Page 9: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Iteration

• How about printing numbers from 1 to 100?

• Copy and paste?– Not a good idea– Long code– Hard to debug

SCM-CityU 9

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);

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

Page 10: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Iteration

• Can we only use fewer lines of code?• Yes we can!

Spring 2012 SCM-CityU 10

• Let’s try it out

for (var i:int = 1; i <= 100; i++) { trace(i);}

for (var i:int = 1; i <= 100; i++) { trace(i);}

SCM-CityU 10

Page 11: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

• Syntax– Starting with for keyword

• Typically counter is related to numberof current iterations and condition is related to number of total iterations

– Example

for Looping Structure

Spring 2012 SCM-CityU 11

for (declare counter; condition; update counter) { // statement(s) to execute repeatedly // as long as condition is true

}

for (declare counter; condition; update counter) { // statement(s) to execute repeatedly // as long as condition is true

}

for (var i:int = 1; i <= 100; i++) { trace(i);}

for (var i:int = 1; i <= 100; i++) { trace(i);} SCM-CityU 11

Page 12: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

for Looping Structure

1. Declare counter 2. Condition checking– If condition is true

a. First run statements within blockb. Then update counter c. Go to the beginning of Step 2

(starting another iteration)

– Otherwise, exit for looping and continue running the program

Spring 2012 SCM-CityU 12

Running order

Page 13: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Running Order Example

Spring 2012 SCM-CityU 13

for (var i:int = 1; i<=3; i++) {trace(i);

}

for (var i:int = 1; i<=3; i++) {trace(i);

}

var i:int = 1; // declare counter

// iteration 1if (i <= 3) { // condition checking

trace(i); // looping body i++; // update counter

}

// iteration 2if (i <= 3) { // condition checking

trace(i); // looping body i++; // update counter

}

// iteration 3if (i <= 3) { // condition checking

trace(i); // looping body i++; // update counter

}

// i <=3 is false, exit looping

var i:int = 1; // declare counter

// iteration 1if (i <= 3) { // condition checking

trace(i); // looping body i++; // update counter

}

// iteration 2if (i <= 3) { // condition checking

trace(i); // looping body i++; // update counter

}

// iteration 3if (i <= 3) { // condition checking

trace(i); // looping body i++; // update counter

}

// i <=3 is false, exit looping

Page 14: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

• 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

2012 SCM-CityU 14

for (declare counter; condition; update counter) { // statement(s) to execute repeatedly // as long as condition is true

}

for (declare counter; condition; update counter) { // statement(s) to execute repeatedly // as long as condition is true

}

for (var i:int = 1; i<=3; i++) {trace(i);

}

for (var i:int = 1; i<=3; i++) {trace(i);

}

var i:int = 1; // init counter externally for (; i <= 3; i++) {

trace(i);}

var i:int = 1; // init counter externally for (; i <= 3; i++) {

trace(i);}

var i:int; for (i = 1; i <= 3; i++) {

trace(i); } Spring

var i:int; for (i = 1; i <= 3; i++) {

trace(i); } Spring

for (var i:int = 1; i <= 3;) {trace(i); i++; // update counter internally

}

for (var i:int = 1; i <= 3;) {trace(i); i++; // update counter internally

}

Page 15: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

More for Looping Examples

Spring 2012 SCM-CityU 15

// example of incrementing counter by 2// print all even numbers in [0, 20)for (var i:int = 0; i < 20; i += 2) {

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);}

// example of decreasing counter for (var i:int = 3; i >= 1; i--) {

trace(i);}

// example of decreasing counter for (var i:int = 3; i >= 1; i--) {

trace(i);}

// counter can be used by multiple for loopsvar i:int;

// 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); }

// counter can be used by multiple for loopsvar i:int;

// 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); }

Page 16: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Page 17: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Nested for Structure

• Syntax– Usually need individual counters

Spring 2012 SCM-CityU 17

// 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 ...

}

// 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 ...

}

Page 18: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Example: Printing Prime Numbers

• 2, 3, 5, 7, …

Spring 2012 SCM-CityU 18

var range_start:int = 10;var range_end:int = 50;for (var i:int = range_start; i <= range_end; i++){

var isPrime:Boolean = true;

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);

}}

var range_start:int = 10;var range_end:int = 50;for (var i:int = range_start; i <= range_end; i++){

var isPrime:Boolean = true;

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);

}}

starting from 2 to i-1if i can be divided by

j, i is not prime

Page 19: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Other Looping Structures in AS

• while and do-while looping structures – We won’t cover details for those structures

Spring 2012 SCM-CityU 19

while (condition) {// statement(s) to execute repeatedly // as long as condition is true

}

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);

do {// statement(s) to execute repeatedly // as long as condition is true

} while (condition);

Page 20: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

SM1205 Interactivity

Array

Spring 2012 SCM-CityU 20

Page 21: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Page 22: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Spring 2012 SCM-CityU 22

// create an Array variable with size = 3var a:Array = new Array(3);

// set values for individual elements a[0] = 1;a[1] = 2;a[2] = 3;

trace(a);

// create an Array variable with size = 3var a:Array = new Array(3);

// set values for individual elements a[0] = 1;a[1] = 2;a[2] = 3;

trace(a);

SCM-CityU 22

1 2 3Variable name: a

Page 23: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

• Otherwise, create 0-size (empty) array first

– Insert new elements using push method later on Spring 2012 SCM-CityU 23

Page 24: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Create Array Variables

• If you even know elements values, use

– Or

• Examples

Spring 2012 SCM-CityU 24

var a:Array = new Array(val1, val2, val3);

var gender:Array = ["female", "male"]; // square brackets trace(gender);

var grades:Array = new Array("A+", "A", "A-", "B+"); // parenthesestrace(grades);

var gender:Array = ["female", "male"]; // square brackets trace(gender);

var grades:Array = new Array("A+", "A", "A-", "B+"); // parenthesestrace(grades);

Page 25: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Review: Brackets (wiki)

• Parentheses: ()– Function parameter list – Precedence ordering

• Braces: {}– Define a block, which

groups a set of statements

• Box/square brackets: []– Array

Spring 2012 SCM-CityU 25

trace(para1, para2, para3, …, paraN);trace(para1, para2, para3, …, paraN);

trace((2 + 3) * 4); // 20trace((2 + 3) * 4); // 20

if (female) {trace("female");trace("hobby: shopping");

}

if (female) {trace("female");trace("hobby: shopping");

}

Page 26: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Page 27: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Access Array Elements

• Array elements are readable and writable – Individual array elements behave like ordinary

variables• Though they have no names

Spring 2012 SCM-CityU 27

var a:Array = [1, 3, 5, 7];

var sum:Number = a[1] + a[2]; // add two elementstrace(sum);

a[2] = 10; // change 3rd element's value trace(a);

var a:Array = [1, 3, 5, 7];

var sum:Number = a[1] + a[2]; // add two elementstrace(sum);

a[2] = 10; // change 3rd element's value trace(a);

1 3 5 7

1 3 1010 7

Page 28: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Access Array Elements

• for loops are often used to process data represented by arrays

Spring 2012 SCM-CityU 28

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);

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);

Page 29: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Spring 2012 SCM-CityU 29

Note: there are other methods to insert/remove elements. Check out online reference

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);

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);

Page 30: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

SM1205 Interactivity

Examples

Spring 2012 SCM-CityU 30

Page 31: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Page 32: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Page 33: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Dynamically Creating Display Objects in AS

Spring 2012 SCM-CityU 33

But what’s associated data type we can use

in AS?

Page 34: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Defining Data Type for Symbol• Define a data type for a symbol when you create it

Spring 2012 SCM-CityU 34

Page 35: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Defining Data Type for Symbol

• You can simply ignore this warping by hitting OK

Spring 2012 SCM-CityU 35

Page 36: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Spring 2012 SCM-CityU 36

This name has no special usageThis name has

no special usage

Page 37: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Page 38: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Adding Visual Obj to Stage• Use addChild method to add display objects to stage

• Use removeChild method to remove display objects from stage

Spring 2012 SCM-CityU 38

var s:MySymbol = new MySymbol ();s.x = 50;s.y = 100;addChild(s);//removeChild(s);

var s:MySymbol = new MySymbol ();s.x = 50;s.y = 100;addChild(s);//removeChild(s);

Page 39: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Class Exercise

• Add two symbol instances to stage using AS

Spring 2012 SCM-CityU 39

Page 40: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Duck Example 1. File > Import > Import to Library

– Import a duck image

2. Give a class name: SymbolDuck – Make sure symbol type is Movie Clip

Spring 2012 SCM-CityU 40

Page 41: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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();

SCM-CityU 41Spring 2012 SCM-CityU 41

Page 42: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Class Exercise

• Create a duck and add it to stage using AS

Spring 2012 SCM-CityU 42

Page 43: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Page 44: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Page 45: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Spring 2012 SCM-CityU 45

Page 46: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Page 47: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

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

Page 48: SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1

Class Exercise • Task 1: dynamically create a large number of shapes

(e.g., circles) with random – Size – Position – Alpha

• Task 2: remove clicked shape fromstage – Use removeChild

Spring 2012 SCM-CityU 48