Flash Actionscript Organising Your Code - PowerPoint PPT Presentation

1 / 45
About This Presentation
Title:

Flash Actionscript Organising Your Code

Description:

Test your movie. include 'include.as' 13. What is a Class? ... world song) or Playlist class (representing a conceptual group of songs) in a ... – PowerPoint PPT presentation

Number of Views:130
Avg rating:3.0/5.0
Slides: 46
Provided by: Nina76
Category:

less

Transcript and Presenter's Notes

Title: Flash Actionscript Organising Your Code


1
Flash Actionscript Organising Your Code
2
Options for Organizing your Code
  • Two options
  • Storing code in frames in a Flash timeline
  • Storing code in ActionScript files

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.

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

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.
  • Unstructured ActionScript code
  • ActionScript class definition

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.

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.

8
Creating an External File in the Script Window
  • Select File gt New.
  • Select ActionScript file. The Script window will
    open.

9
Editing an Existing File in the Script Window
  • To open an existing script, select File gt Open,
    and then open an existing AS file.
  • To edit a script that is already open, click the
    document tab that shows the scripts name.

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 "pathfilename.as"
11
Include Example
  • Select File gt New.
  • Select ActionScript file. The Script window will
    open.
  • Type the following code into the script window
  • Save the file as include.as

trace (testing)
12
Include Example
  • Open a new flash file and save it in the same
    folder as include.as as include.fla.
  • Add the following code to frame 1 of the main
    timeline
  • Test your movie.

include include.as"
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.

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

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
  • 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
16
Actionscript Class Definition
  • 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 smallBoxBox new Box(10,20)
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
  • 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.
  • 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..

18
Strategies for Designing a Class
  • 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.

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.

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

21
Strategies for Designing a Class
  • 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.
  • 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.

22
Writing the Code for a Class
  • Here are the minimum steps to create your own
    class
  • Open the Script window
  • 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
23
Writing the Code for a Class
  • 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

24
Writing the Code for a Class
  • 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 textVariableString "some default
value" public var numericVariableNumber 17
public var dateVariableDate
25
Writing the Code for a Class
  • 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(param1String,
param2Number)void // do something with
parameters
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)

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.

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.

29
Creating a Basic Application
  • Creating the HelloWorld project and the Greeter
    class
  • In the Flash authoring tool, select File gt New.
  • In the New Document dialog box, select
    ActionScript file, and click OK. A new
    ActionScript editing window is displayed.
  • Select File gt Save. Select a folder to contain
    your application, name the ActionScript file
    Greeter.as, and then click OK.

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
greetingString greeting "Hello World!"
return greeting
31
Creating a Basic Application
  • The Greeter class includes a single sayHello()
    method, which returns a string that says "Hello
    World".
  • Select File gt Save to save this ActionScript
    file.

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.

33
Creating a Basic Application
  • Select File gt New. In the New Document dialog
    box, select Flash Document, and click OK. A new
    Flash window is displayed.
  • Select File gt Save. Select the same folder that
    contains the Greeter.as class file, name the
    Flash document HelloWorld.fla, and click OK.
  • 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.

34
Creating a Basic Application
  • In the Properties window, with the text field
    still selected on the Stage, type mainText as the
    instance name of the text field.
  • Click the first frame of the main timeline.
  • In the Actions panel, type the following script

var myGreeterGreeter new Greeter()
mainText.text myGreeter.sayHello()
35
Creating a Basic Application
  • Publishing and testing your application
  • Publish your application and watch for
    compilation errors. In the Flash authoring tool,
    select Control gt Test Movie to compile your
    ActionScript code and run the HelloWorld
    application.
  • 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.
  • 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.

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

37
package public class Greeter /
Defines the names that should receive a
proper greeting. / public static var
validNamesArray "Sammy", "Frank", "Dean"
/ Builds a greeting string using the
given name. / public function
sayHello(userNameString "")String var
greetingString 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(inputNameString "")Boolean
if (validNames.indexOf(inputName) gt -1)
return true else
return false
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."

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.

40
Creating a Basic Application
  • To modify the application
  • Open the HelloWorld.fla file.
  • Modify the script in Frame 1 so that an empty
    string ("") is passed to the Greeter class's
    sayHello() method
  • 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 myGreeterGreeter new Greeter()
mainText.text myGreeter.sayHello("")
41
Creating a Basic Application
  • In the first new text field, type the text User
    Name to serve as a label.
  • 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.
  • Click the first frame of the main timeline.

42
Creating a Basic Application
  • In the Actions panel, add the following lines to
    the end of the existing script

mainText.border true textIn.border true
function keyPressed(eventKeyboardEvent)void
if (event.keyCode Keyboard.ENTER)
mainText.text myGreeter.sayHello(textIn.text)
textIn.addEventListener(KeyboardEvent.KEY_
DOWN, keyPressed)
43
Creating a Basic Application
  • The new code adds the following functionality
  • The first two lines simply define borders for two
    text fields.
  • 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.
  • 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.

44
Creating a Basic Application
  • The complete script for Frame 1 is the
    following

mainText.border true textIn.border true
var myGreeterGreeter new Greeter()
mainText.text myGreeter.sayHello("")
function keyPressed(eventKeyboardEvent)void
if (event.keyCode Keyboard.ENTER)
mainText.text myGreeter.sayHello(textIn.text)
textIn.addEventListener(KeyboardEvent.KEY
_DOWN, keyPressed)
45
Creating a Basic Application
  • Save the file.
  • Select Control gt 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.
Write a Comment
User Comments (0)
About PowerShow.com