1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1....

45
1 Flash Actionscript Organising Your Code
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    218
  • download

    0

Transcript of 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1....

Page 1: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

1

Flash ActionscriptOrganising Your Code

Page 2: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

2

Options for Organizing your Code

Two options:

1. Storing code in frames in a Flash timeline

2. Storing code in ActionScript files

Page 3: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

3

Storing Code in Frames in the Flash Timeline

You can add ActionScript code to any frame in a timeline. This code will be executed while the movie is playing back, when the playhead enters that frame.

You can add code to any frame in the main timeline or to any frame in the timeline of any MovieClip symbol.

This provides a simple way to add behaviours to applications built in the Flash authoring tool. However, this flexibility comes with a cost. When you build larger applications, it becomes easy to lose track of which frames contain which scripts. This can make the application more difficult to maintain over time.

Page 4: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

4

Storing Code in Frames in the Flash Timeline

Many developers simplify the organization of their ActionScript code in the Flash authoring tool by placing code only in the first frame of a timeline, or on a specific layer in the Flash document. This makes it easier to locate and maintain the code in your Flash FLA files. However, in order to use the same code in another Flash project, you must copy and paste the code into the new file.

If you want to be able to use your ActionScript code in other Flash projects in the future, you will want to store your code in external ActionScript files (text files with the .as extension).

Page 5: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

5

Storing Code in Actionscript Files

If your project involves significant ActionScript code, the best way to organize your code is in separate ActionScript source files (text files with the .as extension).

An ActionScript file can be structured in one of two ways, depending on how you intend to use it in your application.1. Unstructured ActionScript code2. ActionScript class definition

Page 6: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

6

Script Window Overview

The Script window lets you create external script files that you import into your application.

If you have more than one external file open, filenames are displayed on tabs across the top of the Script window.

Page 7: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

7

Script Window Overview

In the Script window, you can use the following features: the Add (+) menu (which is like the Actions toolbox), find and replace, syntax checking, syntax colouring, auto format, code hinting, code commenting, code collapse, debug options, and word wrap. The Script window also lets you display line numbers and hidden characters.

The Script window does not include code-assistance features such as the Script navigator, Script Assist mode, and behaviours.

Page 8: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

8

Creating an External File in the Script Window

1. Select File > New.

2. Select ActionScript file. The Script window will open.

Page 9: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

9

Editing an Existing File in the Script Window

To open an existing script, select File > Open, and then open an existing AS file.

To edit a script that is already open, click the document tab that shows the script’s name.

Page 10: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

10

Unstructured Actionscript Code

Lines of ActionScript code, including statements or function definitions, written as though they were entered directly in a timeline script.

ActionScript written in this way can be accessed using the include statement in ActionScript.

The ActionScript include statement causes the contents of an external ActionScript file to be inserted at a specific location and within a given scope in a script, as if it were entered there directly.

include "[path]filename.as"

Page 11: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

11

Include Example

1. Select File > New.

2. Select ActionScript file. The Script window will open.

3. Type the following code into the script window:

4. Save the file as include.as

trace (“testing”);

Page 12: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

12

Include Example

5. Open a new flash file and save it in the same folder as include.as as include.fla.

6. Add the following code to frame 1 of the main timeline:

7. Test your movie.

include “include.as"

Page 13: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

13

What is a Class?

In the real world, you'll often find many individual objects all of the same kind.

There may be thousands of other bicycles in existence, all of the same make and model.

Each bicycle was built from the same set of blueprints and therefore contains the same components.

In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.

Page 14: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

14

What is a Class?

A class is an abstract representation of an object.

A class stores information about the types of data that an object can hold (properties) and the behaviours that an object can exhibit (methods).

Page 15: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

15

Actionscript Class Definition

When you define a class, you can access the ActionScript code in the class by creating an instance of the class and using its properties and methods, just as you would with any of the built-in ActionScript classes. This requires two parts:

1. Use the import statement to specify the full name of the class, so the ActionScript compiler knows where to find it.

E.g., if you want to use the MovieClip class in ActionScript, you first need to import that class using its full name, including package and class:

import flash.display.MovieClip;

Page 16: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

16

Actionscript Class Definition

2. Write code which specifically refers to the class name (usually declaring a variable with that class as its data type, and creating an instance of the class to store in the variable).

By referring to another class name in ActionScript code, you tell the compiler to load the definition of that class.

E.g., given an external class called Box, this statement causes a new instance of the Box class to be created:

When the compiler comes across the reference to the Box class for the first time, it searches the loaded source code to locate the Box class definition.

var smallBox:Box = new Box(10,20);

Page 17: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

17

Strategies for Designing a Class

Think about the role that the instances of this class will play in the application. Generally, objects serve one of these three roles:

1. Value object: These objects serve primarily as containers of data--that is, they likely have several properties and fewer methods. They are generally code representations of clearly defined items, such as a Song class (representing a single real-world song) or Playlist class (representing a conceptual group of songs) in a music player application.

2. Display object: These are objects that actually appear on the screen. E.g. user-interface elements like a drop-down list or status readout, graphical elements like creatures in a video game, etc..

Page 18: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

18

Strategies for Designing a Class

3. Application structure: These objects play a broad range of supporting roles in the logic or processing performed by applications. E.g. an object that performs certain calculations in a biology simulation; one that is responsible for synchronizing values between a dial control and a volume readout in a music player application; one that manages the rules in a video game; or one that loads a saved picture in a drawing application.

Page 19: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

19

Strategies for Designing a Class

Decide the specific functionality that the class will need. The different types of functionality often become the methods of the class.

If the class is intended to serve as a value object, decide the data that the instances will include. These items are good candidates for properties.

Page 20: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

20

Strategies for Designing a Class

Since your class is being designed specifically for your project, what's most important is that you provide the functionality that your application needs. It might help to answer these questions for yourself:

1. What pieces of information will your application be storing, tracking, and manipulating? Deciding this helps you identify any value objects and properties you may want.

2. What sets of actions will need to be performed--for example, when the application first loads, when a particular button is clicked, when a movie stops playing, and so forth? These are good candidates for methods (or properties, if the "actions" just involve changing individual values).

Page 21: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

21

Strategies for Designing a Class

3. For any given action, what information will the class need to know in order to perform that action? Those pieces of information become the parameters of the method.

4. As the application proceeds to do its work, what things will change in your class that other parts of your application will need to know about? These are good candidates for events.

Once you have a design plan for your class, or at least some idea of what information it will need to keep track of and what actions it will need to carry out, the actual syntax of writing a class is fairly straightforward.

Page 22: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

22

Writing the Code for a Class

Here are the minimum steps to create your own class:

1. Open the Script window

2. Enter a class statement to define the name of the class. To do this, enter the words public class, and then the class's name, followed by opening and closing curly braces that will surround the contents of the class (the method and property definitions). E.g.:

The word public indicates that the class can be accessed from any other code.

public class MyClass { }

Page 23: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

23

Writing the Code for a Class

3. Type a package statement to indicate the name of the package in which your class will be found.

The syntax is the word package, followed by the full package name, followed by opening and closing curly braces (which will surround the class statement block). E.g., we'd change the code in the previous step to this:

package mypackage {

public class MyClass { }

}

Page 24: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

24

Writing the Code for a Class

4. Define each property in the class using the var statement within the class body; the syntax is the same as you use to declare any variable (with the addition of the public modifier).

E.g., adding these lines between the opening and closing curly braces of the class definition will create properties named textVariable, numericVariable, and dateVariable:

public var textVariable:String = "some default value"; public var numericVariable:Number = 17; public var dateVariable:Date;

Page 25: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

25

Writing the Code for a Class

5. Define each method in the class using the same syntax that's used to define a function. E.g. To create a myMethod() method, enter:

To create a constructor (the special method that is called as part of the process of creating an instance of a class), create a method whose name matches exactly the name of the class:

public function myMethod(param1:String, param2:Number):void {

// do something with parameters }

Page 26: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

26

Writing the Code for a Class

If you don't include a constructor method in your class, the compiler will automatically create an empty constructor (one with no parameters and no statements) in your class.

public function MyClass() {

// do stuff to set initial values for properties // and otherwise set up the object textVariable = "Hello there!"; dateVariable = new Date(2001, 5, 11);

}

Page 27: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

27

Suggestions for Organizing your Classes

Using ActionScript 3.0, you can save the source code for more than one class in a single .as file. In some cases, it might seem more convenient to pack multiple classes into a single source file, but in general, this is considered a bad programming practice, for a couple of reasons: It is difficult to reuse individual classes if they are

packed together into a single large file. It is difficult to locate the source code for a specific

class when its filename does not correspond to the class name.

For these reasons, it is recommended that you always save the source code for each individual class in its own file, and give the file the same name as the class.

Page 28: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

28

Creating a Basic Application

Designing your application: Our first example of an application will be a standard

"Hello World" application, so its design is very simple: The application will be called HelloWorld. It will display a single text field containing the words

"Hello World!" In order to be easily reused, it will use a single

object-oriented class, named Greeter, which can be used from within a Flash document.

After you create a basic version of the application, you will add new functionality to have the user enter a user name and have the application check the name against a list of known users.

Page 29: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

29

Creating a Basic Application

Creating the HelloWorld project and the Greeter class:

In the Flash authoring tool, select File > New.

In the New Document dialog box, select ActionScript file, and click OK. A new ActionScript editing window is displayed.

Select File > Save. Select a folder to contain your application, name the ActionScript file Greeter.as, and then click OK.

Page 30: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

30

Creating a Basic Application

Adding Code to the Greeter class: Type the following code into the new file:

package {

public class Greeter {

public function sayHello():String {var greeting:String; greeting = "Hello World!"; return greeting; }

} }

Page 31: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

31

Creating a Basic Application

The Greeter class includes a single sayHello() method, which returns a string that says "Hello World".

Select File > Save to save this ActionScript file.

Page 32: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

32

Creating a Basic Application

Creating an application that uses your code:

The Greeter class that you have built defines a self-contained set of software functions, but it does not represent a complete application. To use the class, you need to create a Flash document.

The HelloWorld application creates an new instance of the Greeter class. Here's how to attach the Greeter class to your application.

Page 33: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

33

Creating a Basic Application

1. Select File > New. In the New Document dialog box, select Flash Document, and click OK. A new Flash window is displayed.

2. Select File > Save. Select the same folder that contains the Greeter.as class file, name the Flash document HelloWorld.fla, and click OK.

3. In the Flash Tools palette, select the Text tool, and drag across the Stage to define a new text field, approximately 300 pixels wide and 100 pixels high.

Page 34: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

34

Creating a Basic Application

4. In the Properties window, with the text field still selected on the Stage, type mainText as the instance name of the text field.

5. Click the first frame of the main timeline.

6. In the Actions panel, type the following script:

var myGreeter:Greeter = new Greeter(); mainText.text = myGreeter.sayHello();

Page 35: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

35

Creating a Basic Application

Publishing and testing your application:1. Publish your application and watch for compilation

errors. In the Flash authoring tool, select Control > Test Movie to compile your ActionScript code and run the HelloWorld application.

2. If any errors or warnings are displayed in the Output window when you test your application, fix the causes of these errors in the HelloWorld.fla or HelloWorld.as files, and then try testing the application again.

3. If there are no compilation errors, you will see a Flash Player window showing the Hello World application. The "Hello World" text is displayed.

You have just created a simple but complete object-oriented application that uses ActionScript 3.0.

Page 36: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

36

Creating a Basic Application

Enhancing the HelloWorld application

To make the application a little more interesting, you'll now make it ask for and validate a user name against a predefined list of names.

First, you will update the Greeter class to add new functionality. Then you will update the Flash application to use the new functionality.

Open the Greeter.as file. Change the contents of the file to the following:

Page 37: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

37

package { public class Greeter {

/** * Defines the names that should receive a proper greeting. */ public static var validNames:Array = ["Sammy", "Frank", "Dean"]; /** * Builds a greeting string using the given name. */ public function sayHello(userName:String = ""):String {

var greeting:String; if (userName == "") {

greeting = "Hello. Please type your user name, and then press the Enter key.";

} else if (validName(userName)) {

greeting = "Hello, " + userName + "."; } else {

greeting = "Sorry, " + userName + ", you are not on the list."; } return greeting;

} /** * Checks whether a name is in the validNames list. */ public static function validName(inputName:String = ""):Boolean {

if (validNames.indexOf(inputName) > -1) {

return true; } else {

return false; }

} } }

Page 38: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

38

Creating a Basic Application

The Greeter class now has a number of new features:

The validNames array lists valid user names. The array is initialized to a list of three names when the Greeter class is loaded.

The sayHello() method now accepts a user name and changes the greeting based on some conditions. If the userName is an empty string (""), the greeting property is set to prompt the user for a name. If the user name is valid, the greeting becomes "Hello, userName." Finally, if either of those two conditions are not met, the greeting variable is set to "Sorry, userName, you are not on the list."

Page 39: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

39

Creating a Basic Application

The validName() method returns true if the inputName is found in the validNames array, and false if it is not found.

The statement validNames.indexOf(inputName) checks each of the strings in the validNames array against the inputName string. The Array.indexOf() method returns the index position of the first instance of an object in an array, or the value -1 if the object is not found in the array.

The static keyword specifies that a property belongs to the class, as opposed to instances of the class.

Page 40: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

40

Creating a Basic Application

To modify the application :1. Open the HelloWorld.fla file.

2. Modify the script in Frame 1 so that an empty string ("") is passed to the Greeter class's sayHello() method:

3. Select the Text tool in the Tools palette, and then create two new text fields on the Stage, side-by-side and directly under the existing mainText text field.

var myGreeter:Greeter = new Greeter(); mainText.text = myGreeter.sayHello("");

Page 41: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

41

Creating a Basic Application

4. In the first new text field, type the text User Name: to serve as a label.

5. Select the other new text field, and in the Property inspector, select InputText as the type of text field. Select Single line as the Line type. Type textIn as the instance name.

6. Click the first frame of the main timeline.

Page 42: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

42

Creating a Basic Application

7. In the Actions panel, add the following lines to the end of the existing script:

mainText.border = true; textIn.border = true;

function keyPressed(event:KeyboardEvent):void {

if (event.keyCode == Keyboard.ENTER) { mainText.text = myGreeter.sayHello(textIn.text); }

}textIn.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);

Page 43: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

43

Creating a Basic Application

The new code adds the following functionality:

8. The first two lines simply define borders for two text fields.

9. An input text field, such as the textIn field, has a set of events that it can dispatch. The addEventListener() method lets you define a function that runs when a type of event occurs. In this case, that event is the pressing of the Enter key on the keyboard.

10. The keyPressed() custom function calls the sayHello() method of the Greeter object, passing the text from the textIn text field as a parameter. That method returns a string greeting based on the value passed in. The returned string is then assigned to the text property of the mainText text field.

Page 44: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

44

Creating a Basic Application

The complete script for Frame 1 is the following:

mainText.border = true; textIn.border = true;

var myGreeter:Greeter = new Greeter(); mainText.text = myGreeter.sayHello("");

function keyPressed(event:KeyboardEvent):void {

if (event.keyCode == Keyboard.ENTER) { mainText.text = myGreeter.sayHello(textIn.text); }

} textIn.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);

Page 45: 1 Flash Actionscript Organising Your Code. 2 Options for Organizing your Code Two options: 1. Storing code in frames in a Flash timeline 2. Storing code.

45

Creating a Basic Application

11. Save the file.

12. Select Control > Test Movie to run the application. When you run the application, you will be prompted to enter a user name. If it is valid (Sammy, Frank, or Dean), the application displays the "hello" confirmation message.