Presentation is loading. Please wait.

Presentation is loading. Please wait.

Flash Actionscript Control Structures Arrays

Similar presentations


Presentation on theme: "Flash Actionscript Control Structures Arrays"— Presentation transcript:

1 Flash Actionscript Control Structures Arrays

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

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

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

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

6 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

7 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 < < 11 x >= y x = = y

8 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

9 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) ?

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

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

12 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:

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

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

15 Selection Let’s draw a picture ...

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

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

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

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

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

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

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

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

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

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

26 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

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

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

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

30 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).

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

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

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

34 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).

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

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

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

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

39 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 %

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

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

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

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

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

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

46 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 …

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

48 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) …

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

50 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

51 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


Download ppt "Flash Actionscript Control Structures Arrays"

Similar presentations


Ads by Google