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

Slides:



Advertisements
Similar presentations
Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
Advertisements

COM311H Zheng, School of C&M, UUJ1 Dynamic Web Authoring JavaScript Basics (Array and Function)
Introduction to Computing Science and Programming I
Control Structures Corresponds with Chapters 3 and 4.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
ITC 240: Web Application Programming
Computer Science 1620 Loops.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
SM1205 Interactivity Topic 03: Flow Control Spring 2010SCM-CityU1.
Loops – While, Do, For Repetition Statements Introduction to Arrays
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
SM1205 Interactivity Topic 09: Motion Tracking Part I Spring 2010SCM-CityU1.
SM1205 Interactivity Topic 02: ActionScript 3.0 Fundamentals - Part I Hongbo Fu Spring 2011SCM-CityU1.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Introduction to C Programming
 Pearson Education, Inc. All rights reserved Arrays.
SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2010SCM-CityU1.
Chapter 3 Planning Your Solution
CS0007: Introduction to Computer Programming Introduction to Arrays.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Chapter 9 Introduction to ActionScript 3.0. Chapter 9 Lessons 1.Understand ActionScript Work with instances of movie clip symbols 3.Use code snippets.
JS Arrays, Functions, Events Week 5 INFM 603. Agenda Arrays Functions Event-Driven Programming.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
Chapter 12: How Long Can This Go On?
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
Getting a handle on ActionScript A basic primer for non-programmers.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
PHP Logic. Review: Variables Variables: a symbol or name that stands for a value – Data types ( Similar to C++ or Java): Int, Float, Boolean, String,
1 Workshop Topics - Outline Workshop 1 - Introduction Workshop 2 - module instantiation Workshop 3 - Lexical conventions Workshop 4 - Value Logic System.
Tutorial 51 Programming Structures Sequence - program instructions are processed, one after another, in the order in which they appear in the program Selection.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
CISC 110 Day 5 OOP Part 2. 2 Outline The Display List Display List Classes Adding and Removing Objects Adding Symbol Instances Managing Object Depths.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 5A Repetition (Concepts)
JavaScript, Fourth Edition
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
ActionScript: For Loops, While Loops, Concatenation and Arrays MMP 220 Multimedia Programming This material was prepared for students in MMP220 Multimedia.
© 2011 Delmar, Cengage Learning Chapter 10 Using ActionScript to Enhance User Experience.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Getting started with the turtle Find the latest version of this document at
Decision Making and Branching (cont.)
Iterations (aka Loops). 2 Loops Loops (iterations) are segments of code that may be executed several times. Fixed-count (definite) loops repeat a fixed.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
Controlling Program Flow with Decision Structures.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
1 Fall 2009ACS-1903 Ch 4 Loops and Files while loop do-while loop for loop Other topics later on …
Iterations (aka Loops). 2 Loops Loops (iterations) are segments of code (loop body) that may be executed several times. Fixed-count (definite) loops repeat.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 6 Arrays.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Repetition Looping. Types for while do..while for The for loop allows you to iterate through a variable for a specific range of values. You must supply.
AD 305 Electronic Visualization I : School of Art and Design : University of Illinois at Chicago : Spring 2007 Intro to Action Script "The games of a people.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
SM1205 Interactivity Topic 09: Motion Tracking Part I Spring 2012SCM-CityU1.
 Movieclip symbols are reusable pieces of flash animation  consisting usually of one or more graphic/button symbols  thus they are flash movies within.
Topic 02: Introduction to ActionScript 3.0
REPETITION CONTROL STRUCTURE
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Organizing Memory in Java
T. Jumana Abu Shmais – AOU - Riyadh
Presentation transcript:

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

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

SM1205 Interactivity Iteration and for Loop Spring 2012SCM-CityU3

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

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

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

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

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

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

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

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

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

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

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 }

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

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

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

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

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

SM1205 Interactivity Array Spring 2012SCM-CityU20

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

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-CityU Variable name: a

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

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

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

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

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

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

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

SM1205 Interactivity Examples Spring 2012SCM-CityU30

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Spring 2012SCM-CityU45

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

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

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