Flash Actionscript Control Structures Arrays

Slides:



Advertisements
Similar presentations
Create a Simple Game in Scratch
Advertisements

Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Create a Simple Game in Scratch
1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
© 2010 Delmar, Cengage Learning Chapter 9: Using ActionScript.
Advanced Microsoft Word Hosted by Jared Hoffman Topics Keyboard Shortcuts Customizing Toolbars and Menus Auto Format & Auto Correct Tabs Inserting Pictures.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 18 – Macromedia Flash MX 2004: Building an Interactive Game Outline 18.1 Introduction 18.2 Object-Oriented.
1 Flash Actionscript Animation. 2 Introduction to Sprites We will now look at implementing Sprites in Flash. We should know enough after this to create.
Program Design and Development
1 Flash Actionscript Adding Interactive Actions Variables.
1 Flash Actionscript Actionscript and Objects Control Structures.
1 Flash Programming Introduction Script Assist. 2 Course Description This course concentrates on the teaching of Actionscript, the programming language.
SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2010SCM-CityU1.
© 2010 Delmar, Cengage Learning Chapter 4: Creating Animation.
© 2011 Delmar, Cengage Learning Chapter 8 Building Complex Animations.
Chapter 17 Putting It All Together. Viewing the Preloader To view the preloader, 1.CTRL-Enter to test the movie. 2.View > Simulate Download.
Chapter 9 Introduction to ActionScript 3.0. Chapter 9 Lessons 1.Understand ActionScript Work with instances of movie clip symbols 3.Use code snippets.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Chapter 3 Working with Symbols and Interactivity.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
XP Tutorial 5 Buttons, Behaviors, and Sounds. XP New Perspectives on Macromedia Flash MX Buttons Interactive means that the user has some level.
Introduction to Flash FYS100 Creative Discovery in Digital Art Forms Spring 2007 Burg.
Chapter 11 Adding Sound and Video. Chapter 11 Lessons 1.Work with sound 2.Specify synchronization options 3.Modify sounds 4.Use ActionScript with sound.
© 2011 Delmar, Cengage Learning Chapter 9 Introduction to ActionScript 3.0.
© 2011 Delmar, Cengage Learning Chapter 3 Working with Symbols and Interactivity.
© 2012 Adobe Systems Incorporated. All Rights Reserved. Copyright 2012 Adobe Systems Incorporated. All rights reserved. ® INTRODUCTION TO FLASH ANIMATION.
® Copyright 2010 Adobe Systems Incorporated. All rights reserved. ® ® 1 INTRODUCTION TO ADOBE FLASH PROFESSIONAL CS5.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
Getting a handle on ActionScript A basic primer for non-programmers.
Programming games Flash drawing trick(s). Past due: Your completion of rock-paper-scissors) Classwork: Bouncing ball: read tutorial. Start coding.
XP Tutorial 4 Special Animations. XP New Perspectives on Macromedia Flash MX Special Layers for Animation Animation Using a Motion Guide Layer.
AD 206 Intermediate CG : School of Art and Design : University of Illinois at Chicago : Spring 2009 Intro to Action Script "The games of a people reveal.
2006 Adobe Systems Incorporated. All Rights Reserved. 1 INTRODUCTION TO ADOBE FLASH CS3.
Introduction to Flash Animation CS 318. Topics Introduction to Flash and animation The Flash development environment Creating Flash animations  Layers.
1 ball, 2 ball, red ball, blue ball By Melissa Dalis Professor Susan Rodger Duke University June 2011.
Mathematical Expressions, Conditional Statements, Control Structures
Introduction to Flash CSC361/661 Digital Media Spring 2007 Burg.
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.
Advanced Multimedia Development (AMMD) ::: Review – past few weeks Flash ActionScript Conditional Statements Loops Variable Type Conversion Logical.
Computer Game Design ActionScript is… Object-oriented programming Everything you do in ActionScript does something to some object* Some objects.
Computer Programming Modeling a Passive Solar Home.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
SCRIPT PROGRAMMING WITH FLASH Introductory Level 1.
Video in Macromedia Flash (Optional) – Lesson 121 Video in Macromedia Flash (Optional) Lesson 12.
Open a new Flash File Action Script 2.0. Create a button like you did last lesson and name it Click to Play.
© 2011 Delmar, Cengage Learning Chapter 11 Adding Sound and Video.
Introduction to Computer Programming - Project 2 Intro to Digital Technology.
Unit 6 Repetition Processing Instructor: Brent Presley.
Debugging tools in Flash CIS 126. Debugging Flash provides several tools for testing ActionScript in your SWF files. –The Debugger, lets you find errors.
XP Tutorial 3 Creating Animations. XP New Perspectives on Macromedia Flash MX Elements of Animation Layers are used to organize the content of.
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.
Creating a Simple Game in Scratch Barb Ericson Georgia Tech May 2009.
 Movieclip symbols are reusable pieces of flash animation  consisting usually of one or more graphic/button symbols  thus they are flash movies within.
Game Maker Tutorials Introduction Clickball IntroductionClickball Where is it? Shooting Where is it?Shooting.
11 Making Decisions in a Program Session 2.3. Session Overview  Introduce the idea of an algorithm  Show how a program can make logical decisions based.
Topic 02: Introduction to ActionScript 3.0
var variableName:datatype;
Scratch for Interactivity
Loops BIS1523 – Lecture 10.
Flash Interface, Commands and Functions
T. Jumana Abu Shmais – AOU - Riyadh
Items, Group Boxes, Check Boxes & Radio Buttons
INTRODUCTION TO FLASH ANIMATION
Creating a Simple Game in Scratch
Web Programming and Design
Presentation transcript:

Flash Actionscript Control Structures Arrays

ActionScript Control Structures Three basic control structures for programming languages: sequence selection iteration These structures are necessary and sufficient to implement any algorithm.

Sequence Sequence simply means the ability to execute a set of statements in order. This is done by writing them in the order in which you wish them to be executed and separating them by semicolons e.g. S1;S2;S3; Usually these are placed on separate lines e.g. S1; S2; S3;

Sequence For example: ball.x = 20; ball.y = 30; ball.x = ball.x +1; ball.y = ball.y +1;

Selection Selection means the ability to choose between two (or more) different statements depending on the value of some condition. It takes the general form if (condition){ //statements; } It is worth looking briefly at how ActionScript handles conditions.

Selection Conditions are formed by the use of a set of conditional operators. These are: < less than > greater than <= less than or equal to >= greater than or equal to = = equal to != not equal to

Selection These operators can be used to compare the values of variables and/or literals. The result is that a Boolean value, true or false, is returned. E.g.: x < 10 10 < 11 x >= y x = = y

Selection These conditions could be used in selection (IF) statements as follows: if (x < 10){ x++; } else{ x--; // and so on ! } Compound conditions can be formed by combining conditions using the logical operators. These are: ! Logical NOT && Logical AND || Logical OR

Selection (x<10) && (y>0) false Logical NOT inverts the value of a condition. So if x<y is true then !(x<y) will be false. A condition formed by the use of && will be true if and only if both of its constituent conditions are true. A condition formed by the use of || will be true if one of its constituent conditions is true. So suppose x has the value 5 and y has the value 0 then …. (x<10) && (y>0) false (x<10) && (y>=0) true !(x<10) || (y<=0) ?

Selection If statements can be formed without the else and they can also contain else if clauses also: if (x<10){ x++; } else if (x<20){ x = x + 2; } else { x = 30; }

Selection There are three general forms of the if selection structure. They are: if (condition) { // statements; } if (condition1){ // statements; }else if (condition2){ } . . else{ } if (condition){ // statements; }else }

Selection Switch The switch statement is useful if you have several execution paths that depend on the same condition expression. It provides functionality similar to a long series of if…else if statements, but is somewhat easier to read. Blocks of code begin with a case statement and end with a break statement. For example, the following switch statement prints the day of the week, based on the day number returned by the Date.getDay() method:

var someDate:Date = new Date(); var dayNum:uint = someDate.getDay(); switch(dayNum) { case 0: trace("Sunday"); break; case 1: trace("Monday"); case 2: trace("Tuesday"); case 3: trace("Wednesday"); case 4: trace("Thursday"); case 5: trace("Friday"); case 6: trace("Saturday"); default: trace("Out of range"); }

Selection Let’s look at some examples of the use of selection statements. Example 1: Space Invaders I have a game of space invaders. The player’s ship is allowed to fire bullets at the aliens. Suppose the bullet has just been fired and this is signified by the Boolean variable bulletFired = true. Also the bullet is moving up the screen at a speed signified by the variable bulletSpeed. I want to move it further up the screen if it hasn’t already reached the top. If it’s at the top I want to stop moving the bullet and remove it from the screen. In this case I also want to set bulletFired to false , which Flash will see as a sign that the player is allowed to fire again.

Selection Let’s draw a picture ...

Selection Player’s ship is at the bottom and our bullet is at some point moving upwards. In Flash the top-left hand corner of the screen is (0,0) so as we increase the x coordinate of an object it moves to the right and as we increase the y coordinate it moves down. The bullet moves up in a straight line so only its y-coordinate decreases as it moves upwards eventually reaching a value of 0 at the top.

Selection Suppose the instance of the ship on the screen is called ship, then its x coordinate is ship.x and its y coordinate is ship.y. Similarly if the bullet is called bullet then its coordinates are bullet.x and bullet.y. So bullet.y is positive as it is moving up the screen but if it is <=0 then it has moved off the top of the screen.

Selection So as long as bullet.y is positive we want to keep subtracting from it which will move it upwards. As soon as bullet.y is less than zero we no longer need to animate the bullet, although we need it to disappear. Easiest way to do this is to place it off the screen, say by setting bullet.y = -100.

Selection When the bullet is off the screen, the player would be allowed to fire another bullet, so we need to tell Flash this by making bulletFired = false. (This would have been set to true after the bullet was fired). So the decision becomes If (the bullet is being fired) and (its y position is greater than or equal to 0) move the bullet If (the bullet is being fired) and (its y position is less than or equal to 0) hide the bullet and let the user fire another.

Selection This becomes … if ((bulletFired=true) && (bullet.y>=0)) { bullet.y = bullet.y - speed; } else if (bulletFired=true && (bullet.y<0)) bulletFired = false; bullet.y = -100;

Selection We need a bit more ActionScript to start thinking about coding this fully so instead lets look at a password screen. Example 2: Password Field Suppose we want to password protect our Flash website. We could do this by dividing it into two scenes. Scene 1 is a screen which puts up a text field and invites the user to enter a password. If this password is correct then the movie jumps to scene 2. If not it doesn’t.

Selection So this requires a simple if statement to implement (along with the textfields we have already seen). We need two elements. 1. A textfield. 2. A button (execute). The idea is that when the user hits the execute button the system reads what is in the textfield and if it matches the password jumps to scene 2.

Selection Create an Input textfield and a simple execute button Name the textfield instance to be password and the button instance to be enterButton.

Selection We need to attach the following action to frame one of our actions layer in scene 1. stop(); function checkPassword(event:MouseEvent):void { if (password.text=="mypassword") gotoAndPlay(1,"Scene 2"); } enterButton.addEventListener(MouseEvent.MOUSE_UP,checkPassword);

Selection And the following to frame one of the actions layer in scene 2. stop();

Selection 50 25 Example 3: Galaxians Imagine we are writing a piece of code which controls how a diving space invader attacks the player as it advances down the screen. It should do different things depending on how close it gets to the player’s ship. 50 25

Selection We might write the decision like this: Remember it will only try the first else if branch if the if branch is false. It will only try the second else if branch if the if and the first else if are false. if (ship.y - alien.y > 50) { make alien stay in formation } else if (ship.y – alien.y > 25) { make alien start to fire on the ship and dive in a random manner } else if (ship.y – alien.y > 10) { execute kamikaze tactics }

Selection What would happen if we changed the password code to the following? stop(); function checkPassword(event:MouseEvent):void { if (password.text=="user1") gotoAndPlay(1,"Scene 2"); } else if (password.text=="user2") gotoAndPlay(1,"Scene 3"); enterButton.addEventListener(MouseEvent.MOUSE_UP,checkPassword);

Looping In any programming language you essentially have two different situations when employing a loop. Either (a) you know how many times the loop has to be executed in advance or (b) you don’t.

Looping An example of (a) would be adding up all the elements of an array. We know how many times we have to loop because we know how many elements there are in the array. An example of (b) would be a situation where we want to keep repeating some action until the user presses a key indicating that we should stop. We tend to use while loops for (b) and for loops for (a).

Looping Let’s start with the while loop. Its general form is: The condition is tested. If it is true then the statements are executed. The condition is tested again. If true, the statements are executed. This sequence continues until the condition is found to be false. while (condition){ statement(s); }

Looping In Flash these loops are used to obtain repetitive behaviour within a single frame. This is different to the loops between frames which we have already seen by the use of the gotoAndPlay() action. Let’s look at a substantial example of the use of while loops in Flash.

Looping Example: Brownian Motion We are going to build a brownian motion simulator. Gases are made up of lots of little particles that bounce around in a random motion. This is called brownian motion and is caused by the particles constantly hitting each other and shooting off in random directions after each collision. The effect we want to achieve is ...

Looping 1. Open a new movie and give it a black background. Create a graphic symbol called plasma that consists of a white circle with a radial gradient that fades to black at the edges. 2. Now create a new movie clip called randomplasma. This should be blank at present!. Drag the plasma graphic symbol onto the centre of the stage and use the Properties panel to centre it at 0.0, 0.0. Create a new layer called Actions. 3. In frame 1 of the Actions layer (of the movie clip random plasma) add the following code in the Frame Actions window: this.x = this.x + (Math.random()*4)-2; this.y = this.y + (Math.random()*4)-2; 4. Add a keyframe in frame 2 of the Actions layer and add a gotoAndPlay(1) action. 5. Return to Scene 1 and drag three instances of the random plasma movie clip onto the stage. Test the movie (Plasma01.fla).

Looping 6. Delete two of the instances. Bring up the properties panel and give the movieclip an instance name, particle. 7. Go to the root timeline (e.g. Scene 1). Add a new layer called Actions. In this new layer we are going to clone our particle so we have lots of them in order to form a gas cloud. In other words we are going to create new particle objects - we are going to use the new keyword to do this.

Loading Symbols Dynamically In order for this to work you must turn on the Export for ActionScript option in the Linkage properties for the target symbol. Right click on the symbol in the Library and choose Linkage. Check ‘Export for Actionscript’. Because you can no longer add an identifier, you have to handle everything instead using the class name. If you don't have a custom class for the symbol you want to attach, use the symbol name as inserted by default. In this case, Flash creates a skeleton class for you using the name of the symbol.

Loading Symbols Dynamically This is the general form of the code: var myInstance = new MyClassName(); addChild(myInstance);

Looping 8. In frame 1 of the new layer actions add the following code: var counter:int = 10 while (counter>0) { var newParticle = new randomPlasma(); addChild(newParticle); newParticle.x = particle.x; newParticle.y = particle.y; counter--; } stop();

Looping Something wrong with this … We were supposed to make the movie clip symbol transparent to some degree ... This works a bit better. Try it out with 100 instances instead …. 9. Edit the symbol plasma. Using the color mixer set it so the radial gradient goes from white/alpha 100% to white/alpha 0 %

Looping For Loops The for loop allows you to iterate through a variable for a specific range of values. The general form of a for loop is The initialisation is done once at the start. Then the condition is tested. If it’s true it executes the statements. It then does the increment. It then tests the condition again and so on …. for (initialisation; condition; increment) { statement(s); }

Looping You must supply three expressions to a ‘for’ statement: A variable that is set to an initial value. A conditional statement that determines when the looping ends. An expression that changes the value of the variable with each loop. E.g., the following code loops five times. The value of the variable i starts at 0 and ends at 4, and the output are the numbers 0 through 4, each on its own line. var i:int; for (i = 0; i < 5; i++) { trace(i); }

Arrays An array is an object whose properties are identified by numbers representing their positions in the structure. Essentially, an array is a list of items. Or you could think of it as a file drawer for variables. It's important to remember that each element in an array doesn't have to be the same data type. You can mix numbers, dates, strings, and objects and even add a nested array at each array index.

Arrays Important concepts and terms: Array: An object that serves as a container to group multiple objects together. Element: A single item in an array. Index: The numeric "address" used to identify a single element in an indexed array. (starts from 0) Indexed array: The standard type of array that stores each element in a numbered element, and uses the number (index) to identify individual elements. Multidimensional array: An array containing items that are arrays rather than single values.

Arrays The following example is a simple array of month names. This can also be rewritten as follows: Or, you can use shorthand syntax, as follows: var myArr:Array = new Array(); myArr[0] = "January"; myArr[1] = "February"; myArr[2] = "March"; myArr[3] = "April"; var myArr:Array = new Array("January", "February", "March", "April"); var myArr:Array = ["January", "February", "March", "April"];

Arrays So Arrays are exactly the same as they are in Javascript. They can be declared as follows: This simply states that we want to use something called ninaArray and it’s an array. You don’t even need to tell it how many entries the array will have though you can if you want. This says I want an array called ninaarray which has 20 elements. var ninaArray:Array = new Array(); var ninaarray:Array = new Array(20);

Arrays There are several different ways you can use arrays in your work. E.g.: You can use them to store lists of objects, such as a bunch of returned items. If you load data from remote web servers, you might even receive data as an array of nested objects. Often, arrays contain data in a similar format. E.g., if you build an audio application in Flash, you might have a user's playlist stored as an array of song information, stored in objects. Each object contains the song name, artist name, song duration, location of a sound file …

Arrays The location of an item in an array is called the index. All arrays are zero-based, which means that the first element in the array is [0], the second element is [1], and so on.

Arrays So will create an array called ninaArray which has three elements set to cat, dog, and banana. We then refer to individual array elements in the usual manner e.g. var ninaArray:Array = new Array (“cat”,“dog”,“banana”); ninaArray[0] = “cat”; if (ninaArray[i] < 12) …

Arrays Create a new Flash document, and save it as basicArrays.fla. Add the following ActionScript to Frame 1 of the Timeline: // define a new array var myArr:Array = new Array(); // define values at two indexes myArr[1] = "value1"; myArr[0] = "value0"; // iterate over the items in the array var i:String; for (i in myArr) { // trace the key/value pairs trace("key: " + i + ", value: " + myArr[i]); }

Arrays In the first line of ActionScript, you define a new array to hold the values. Then, you define data (value0 and value1) at two indexes of the array. You use a for…in loop to iterate over each of the items in that array and display the key/value pairs in the Output panel using a trace statement. Select Control > Test Movie to test your code. The following text is displayed in the Output panel: key: 0, value: value0 key: 1, value: value1

for… in Loop The for…in loop iterates through the elements of an array. For example: var myArray:Array = ["one", "two", "three"]; for (var i:String in myArray) { trace(myArray[i]); } // output: // one // two // three