Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1."— Presentation transcript:

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

2 Overview Technologies – for loop and iteration – Array data type Examples Spring 2012SCM-CityU2

3 SM1205 Interactivity Iteration and for Loop Spring 2012SCM-CityU3

4 Control Multiple Objects How to control multiple objects with similar behaviors? Spring 2012SCM-CityU4

5 Control Multiple Objects Straightforward solution – Manually assign different names to each object – Duplicate same code for all objects SCM-CityU5 s1 s2 s3 s4 s5 s6 s7 Spring 2012SCM-CityU5

6 Control Multiple Objects But how about too many objects? – E.g., 100 circles with random position and size Spring 2012SCM-CityU6

7 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-CityU7Spring 2012SCM-CityU7

8 Iteration Example – output text from 1 to 10 SCM-CityU8 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 2012SCM-CityU8

9 Iteration How about printing numbers from 1 to 100? Copy and paste? – Not a good idea – Long code – Hard to debug SCM-CityU9 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 2012SCM-CityU9

10 Iteration Can we only use fewer lines of code? Yes we can! Spring 2012SCM-CityU10 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-CityU10

11 Syntax – Starting with for keyword Typically counter is related to number of current iterations and condition is related to number of total iterations – Example for Looping Structure Spring 2012SCM-CityU11 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-CityU11

12 for Looping Structure 1.Declare counter 2.Condition checking – If condition is true a.First run statements within block b.Then update counter c.Go to the beginning of Step 2 (starting another iteration) – Otherwise, exit for looping and continue running the program Spring 2012SCM-CityU12 Running order

13 Running Order Example Spring 2012SCM-CityU13 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 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 } // i <=3 is false, exit looping var i:int = 1; // 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 } // i <=3 is false, exit looping

14 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 2012SCM-CityU14 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 }

15 More for Looping Examples Spring 2012SCM-CityU15 // 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 loops var 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 loops var 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); }

16 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 2012SCM-CityU16

17 Nested for Structure Syntax – Usually need individual counters Spring 2012SCM-CityU17 // 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... }

18 Example: Printing Prime Numbers 2, 3, 5, 7, … Spring 2012SCM-CityU18 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-1 if i can be divided by j, i is not prime

19 Other Looping Structures in AS while and do-while looping structures – We won’t cover details for those structures Spring 2012SCM-CityU19 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);

20 SM1205 Interactivity Array Spring 2012SCM-CityU20

21 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 2012SCM-CityU21

22 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 2012SCM-CityU22 // 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; trace(a); // 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; trace(a); SCM-CityU22 12 3 Variable name: a

23 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 2012SCM-CityU23 var a:Array = new Array(10); var a:Array = new Array(); a

24 Create Array Variables If you even know elements values, use – Or Examples Spring 2012SCM-CityU24 var a:Array = new Array(val1, val2, val3); var a:Array = [val1, val2, val3]; var gender:Array = ["female", "male"]; // square brackets trace(gender); var grades:Array = new Array("A+", "A", "A-", "B+"); // parentheses trace(grades); var gender:Array = ["female", "male"]; // square brackets trace(gender); var grades:Array = new Array("A+", "A", "A-", "B+"); // parentheses trace(grades);

25 Review: Brackets (wiki)wiki Parentheses: () – Function parameter list – Precedence ordering Braces: {} – Define a block, which groups a set of statements Box/square brackets: [] – Array Spring 2012SCM-CityU25 trace(para1, para2, para3, …, paraN); trace((2 + 3) * 4); // 20 if (female) { trace("female"); trace("hobby: shopping"); } if (female) { trace("female"); trace("hobby: shopping"); } var a:Array = [val1, val2, val3];

26 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 2012SCM-CityU26

27 Access Array Elements Array elements are readable and writable – Individual array elements behave like ordinary variables Though they have no names Spring 2012SCM-CityU27 var a:Array = [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); var a:Array = [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); 13 57 13 10 7

28 Access Array Elements for loops are often used to process data represented by arrays Spring 2012SCM-CityU28 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);

29 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 2012SCM-CityU29 Note: there are other methods to insert/remove elements. Check out online referenceonline 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);

30 SM1205 Interactivity Examples Spring 2012SCM-CityU30

31 Example: Swimming Ducks We will learn – How to dynamically create objects (ducks!) – How to store/access objects with Array and for looping structure Spring 2012SCM-CityU31

32 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 2012SCM-CityU32

33 Dynamically Creating Display Objects in AS Spring 2012SCM-CityU33 But what’s associated data type we can use in AS?

34 Defining Data Type for Symbol Define a data type for a symbol when you create it Spring 2012SCM-CityU34

35 Defining Data Type for Symbol You can simply ignore this warping by hitting OK Spring 2012SCM-CityU35

36 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 2012SCM-CityU36 This name has no special usage

37 Adding Visual Obj to Stage AS uses display list to organize all display objects on stage (ref)ref – A hierarchical list of all visual objects Spring 2012SCM-CityU37

38 Adding Visual Obj to Stage Use addChild method to add display objects to stage Use removeChild method to remove display objects from stage Spring 2012SCM-CityU38 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);

39 Class Exercise Add two symbol instances to stage using AS Spring 2012SCM-CityU39

40 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 2012SCM-CityU40

41 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-CityU41Spring 2012SCM-CityU41

42 Class Exercise Create a duck and add it to stage using AS Spring 2012SCM-CityU42

43 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 2012SCM-CityU43

44 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 2012SCM-CityU44

45 Spring 2012SCM-CityU45

46 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 2012SCM-CityU46

47 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 2012SCM-CityU47

48 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 2012SCM-CityU48


Download ppt "SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2012SCM-CityU1."

Similar presentations


Ads by Google