You are on page 1of 237

1

SWiSH CliMax
Your best companion for learning SWiSH MAX
Advanced Scripting with PHP and ASP
That enables you to enhance your web applications meeting international market standards

By
Ali Imran
(2004)
2

Table of Contents
Chapter 1 Introduction
Focus
SWiSH MAX – An Introduction
SWiSHScript History
SWiSHScript Vs ActionScript
Understanding SWiSH MAX IDE
Design tools Overview
Understanding Menus and Toolbars
Applying built-in effects on objects
Adding comments in Code

Chapter 2 Getting Started


Movie Physical Objects
Data types and Variables
Type Casting or Type Juggling
SWiSHScript Basics
Mathematical and Comparison Operators
Taking decisions in SWiSHScript using ‘if’
Logical Operators
Ternary If-else structure
Loop Structures
Breaking loops Unconditionally
Skipping the code in loops, Unconditionally
Tuning up code with ‘switch’ set statement
Working with Functions
String manipulation
Button and Sprite Object properties and event handlers
My first SWiSHScript application
Understanding Levels
_root, _parent, this, and _global
Use of ‘tellTarget’
Use of and ‘with’
Dragging the objects at runtime

Chapter 3 TEXT/JPEG File Management with SWiSH MAX


Loading data from Text Files, loading external JPEG files
Creating static Address Book with images (without PHP)

Chapter 4 Interaction with PHP


Sending data to PHP script
Receiving data from PHP script
My first text echo application
Creating E-Mail Contact Form, mail in PHP
Writing Text Files
3

Reading Text Files


Introducing loadVars Object and its reliability
Sprite Duplication and accessing duplicated sprite’s properties
Arrays in SWiSHScript, more flexible and powerful than in ActionScript

Chapter 5 Advanced Events Handling and other Scripting Objects


Evaluation/Access of Dynamic Objects/Variables
Advanced Techniques of Events Handling (an Introduction)
How to implement existing event handlers within functions
Deleting Event Handlers when job is done
Defining/Attaching new events handlers to Sprite object, and using them
Creating Events to accept variables as Arguments
Connecting Objects through events
Defining Global functions to use anywhere without reference
Creating Sprite pointers
Collision detection for games creation
Encoding special characters before sending to SWiSH Movie

Chapter 6 Using UI Collection Objects


Introduction to UI Collection Objects
UI CheckBox
UI Radio Button
UI Menus
UI Combo Box
UI Toolbars
UI Spreadsheet
UI Form Dialogue
UI Pie Charts
UI Bar Graphs
UI Line Graphs
Connecting UI Spreadsheet with UI Pie Charts, UI Line Graphs, and UI Bar Graphs

Chapter 7 Preloaders, Scrollers, Dynamic Drawing, an External MP3


Additional utility functions for creating Preloaders
Scroller for Dynamic and Input text objects
Creating new Sprites at runtime
Direct Drawing Methods in SWiSHScript
Scripted Preloaders
Loading external mp3 sounds & Audio Streaming

Chapter 8 Core Practice / Source Code / Details


Study of MySQL with PHP
Creating Interactive Polling System using UI Collection Objects
Online Resources / Help
4

Chapter 9 SWiSHMax integration with ASP and MS-Access

What is Microsoft Access?


Creating Database and Tables with Microsoft Access
What is ASP?
Adding comments in ASP code
Tracking variables obtained through GET and POST method in ASP
Sending back Response to SWiSHMax movie
Sample SWiSHMax application with ASP

Color Codes and File names


BLUE SWiSHScript
RED PHP
GREEN Chapter Names/Notes and ASP Code
GRAY Comments
PINK MySQL
BROWN Text
Chapter 1

Introduction

ƒ Focus
ƒ SWiSH MAX – An Introduction
ƒ SWiSHScript History
ƒ SWiSHScript Vs ActionScript
ƒ Understanding SWiSH MAX IDE
ƒ Design tools Overview
ƒ Understanding Menus and Toolbars
ƒ Applying built-in effects on objects
ƒ Adding comments in Code
6

Focus

This book focuses on salient features of SWiSHScript as well as throws light


on designing. There is no prior knowledge of SWiSHMax required to read this book. If
you already have some know-how of SWiSH 2 or SWiSHMax environment, that is a
plus. Major focus of the book is on implementation of all level SWiSHScript
applications alongwith implementation of User Interface Objects and standard
reusable components.

SWiSH MAX – An Introduction

SWiSHMax is a complete Integrated Development Environment, and product


of SWiSHZone PTY. Ltd. Using SWiSHMax, you can create from simple to most
complex animations and standard web applications. SWiSH renders your final
animations or applications to SWF (swiff pronounced) file format. Macromedia Inc
introduced SWF file format, for the very first time. Commonly SWF is taken as
abbreviation of Shock-Wave-Flash, where ShockWave is another software product of
Macromedia Inc. The most widely used software tool of Macromedia, is Flash, which
renders the application to final version SWF. An SWF file is the final publishable
version of your Rich Media Contents on the World Wide Web. So, what we meant to
say is, that SWiSHMax also renders/exports your final application/animation to SWF
format, which is recognized by almost all the browsers via Installable FlashPlayer
plugin (ActiveX) for OS.

SWiSHScript History, SWiSHScript Vs ActionScript

SWiSHScript is a scripting language, derived from Flash ActionScript. What is


Flash ActionScript? Flash ActionScript is a scripting language used in Macromedia
Flash 4/5/MX. It enables the developer to control events and write runtime flow of
the application. It uses almost same syntax for control structures as is used in C /
C++ / Java / JavaScript / PHP etc. It also provides some Object Oriented techniques
and some built-in scripting objects to work with. So SWiSHScript cannot be said
completely same to Flash ActionScript but 95% same. So the SWiSHMax provides a
complete set of language syntax to write inter-structure code of the web application.
7

Understanding SWiSH MAX IDE

SWiSHMax has its own Integrated Development Environment with almost all the
required tools, nuts and bolts. Parts of SWiSHMax IDE are shown in the following
figure:

It provides many tools for drawing, shading, coloring, reshaping, rotating, text tool
as well as a sophisticated Outline Panel, that contains the hierarchical view of the
objects in your SWiSHMax project, which is not available in Flash MX.

The properties windows contain properties of the entire movie (global settings) and
properties of specific type of object currently selected.
8

Design tools Overview

Design tools/Drawing tools are part of Layout window/Design window. As shown


below. These tools contain

Select tool is simply used to select any object, drag and reposition it, and resize it
as well.

Reshape tool is used to reshape a pure and solid object (Rectangle, Ellipse, Bezier,
Shape created with Pencil, Line). If this is selected, the edges of the shape become
9

visible, where you can easily click and replace them. As the following rectangle is
reshaped using this tool, stretched from bottom-right corner (edge).

Example:
Before After

Fill Transform is the tool used to manipulate the gradient if a shape, or a


tiled/clipped image in a shape.

Using Line tool you can draw a straight line in any direction.
Note: straight line not curved

Example:

Pencil tool works almost same as in MS-Paint. But it may be said an


enhanced version of that. Any object created with this tool becomes a shape as
matrix of pixels. So that, the drawn shape holds all the properties of a usual shape.
Its big feature is, it automatically fills the drawn shape if it drawn shape’s starting
and ending points are same.

Example:
Auto Filled Unfilled
10

Bezier or Pen tool. It is different from Pencil tool. You may have noticed that Pencil
tool draws shaped until mouse click is not released. But this tool continues drawing
shape until it starting point and ending point, do not match. You may create curvy
shapes as well. For doing this you just need to drag while you click.

Example:

Note: It is automatically filled when said points are matched. If you want to
draw a Bezier without fill, then you will have to terminate the Bezier drawing session
by forcing it. How to do that? If edges are not yet matched and Bezier shape is not
filled, just click the “Select” tool (Simple mouse icon, “Select” tool is defined in
previous pages). It will automatically terminate the session and create Bezier shape
without fill.

Example:

Text Tool allows you to draw a text object of custom colors, size, font, and direction
in your SWiSHMax movie. Further discussion on text object in available in upcoming
chapters.

Rectangle is used to draw rectangle of desired width and height. Just click and
stretch it to desired size and release the mouse key. You can even draw rounded
corner rectangle using same tool. For drawing normal rectangle you use one mouse
click and release. But for creating rounder corner rectangle you will have to use two
clicks, and release click two times. Follow the procedure. Click once where you want
the rectangles top-left corner and release the mouse key. Notice that an auto
resizing rectangle line is following your mouse current position. Now bring your
mouse to the position, where you want your rectangle’s bottom-right corner be and
click it. Don’t release the click for now. Drag clicked mouse into the center of the
rectangle. You will see the corners are being rounded. Now this is up to you, release
the mouse key when position is on your desired rounded corner rectangle.
11

Example:
Simple Round corner

Ellipse drawing tool is used to draw elliptic shapes. You ellipse can be of any style.
You can stretch/screw resize and customize it fully as other shapes.

Example:
Simple Stretched & Rotated

Zoom tools are used only to zoom (zoom the design area), zoom in and out

When Pan is selected you can select objects via Outline window but not from
Layout/Design window. It is used to drag the entire movie area within the Layout. It
is useful especially when you have placed some object out of design area. It is
automatically unselected when you release the mouse button after dragging the
design area to a specific position.

AutoShape tool provides variety of premade shapes available within SWiSHMax. To


select desired shape, click in the icon and hold the moue button down for a while,
then a set of tools appear to select from, as shown here:
12

Stretch and Screw tool defined within SWiSHMax as,

This is the ToolTip which appears when you keep mouse over this icon. This tool is
used to stretch any type of object by resizing all of its sub-components to specific
area.

This is another Resize tool which allows designer to resize the outer border of an
object. If the object being resized is a text object, the text size is not suffered using
this tool.

Rotate tool allows designer to rotate an object within design window (Layout Panel).

Distort transformation tool allows to apply a distort transformation to selected


shape, if it is a rectangle, this tool will act almost same as reshape tool, but if it is an
ellipse of a shape drawn using Bezier it will result differently. You may try it yourself.
13

After clicking this tool some gray lines do appear over the Layout Window. These
lines are called guides, which guide the designer to draw in a specific area. After it
has been clicked the design area looks like this:

Snap to Grid tool is used to drag and place the objects on the edges of the logical
grid. When this tool is clicked the dragging of the objects become jerky, because the
objects are dragged over the grid. You may try this tool by clicking it, then draw a
rectangle and drag it using mouse.
14

Toolbars and Menus

In sub topics of ‘Toolbars and Menus’ we will be discussing the important tools (not
all of them).

Toolbars

Before defining the menus and toolbars it is assumed that you have turned all
toolbars visible. The procedure for doing so is under. Select Menu “View” from main
menus, then Click submenu Toolbars, and then Check all available toolbars (e.g.
Export Toolbar). See below:

After turning them visible they must look almost like this:

If not then arrange them as shown above, because in almost all chapters, we will be
using the same style. Now we get started with Standard Toolbar.

Standard Toolbar

Contains shortcut icons for saving source file, loading (open) source file, creating
new file.

These are the traditional shortcut icons, which are available in almost every
application of windows. Cut, Copy, Paste, and Delete work the same way as in other
windows applications, but in SWiSHMax these are used to perform equivalent
operation upon objects and/or script.
15

Bring Forward, Send Backward; These shortcut icons are used to change the
depth of objects. For example, you have two objects in your movie. Both are
rectangles. One is colored blue and the other one is red. The red on is over the blue
one (means some area o blue is under the red one). Now you want to bring the blue
rectangle Forward. You will select the blue rectangle and click the “up black arrow”.
Similarly, for sending an object backward, do same by clicking the “down black
arrow”.

Bring to Front, Send to Back; Bring to Front is completely different from Bringing
object Forward. Bring to Front is used to bring desired object on Top (on front of all
objects). For example, you have 5 rectangles in your source move, and you want to
bring the last one on top of all, you will click “up red arrow with black line over it”.
Similarly, when you need to send some object behind all the objects, you will click
“down red arrow with black line under it”.

Undo and Redo; Undo is used to restore the last operation you performed in your
movie. For example, if you have deleted a rectangle by pressing delete button from
keyboard, and you want to restore it. You will click undo icon (blue curvy arrow to
left) or press key Ctrl+Z from keyboard. Similarly, blue curvy arrow to right is used
to repeat the last operation (Redo).

Grouping Toolbar

These tools are used to Group, Ungroup objects and Convert several type of objects
to other types. The first icon from left is used to combine one or more objects into
one group, and name it default as “Group”. Further more, groups can be combined
into single group as well (you can group by using Ctrl+G from keyboard as well). The
second one from left is used to combine one or more selected objects as a button.
The third one from left is used to combine one or more object into a sub movie
(Sprite), by default it is named as Sprite (sub movie or movie within movie which
has its own timeline). We will discuss Sprite in upcoming chapters. The 4th icon is
used to merge many shapes into single shape. By default an emerged shape is
named as “Merged shape” or “Shape”. But if you combine more shapes with same
color, the connecting area will become transparent automatically. This can be
considered as a feature. The last icon from left, is used to ungroup any type of
grouped objects. Whether they were grouped as “Sprite” or simple “Group”.
16

Conversion toolbar (part of Grouping Toolbar)

These tools are used for conversion. For example you have a rectangle and you want
to convert it to Button (Button will be defined in detail in upcoming chapters). What
will you do? You just select the rectangle by single click and click the left most button
shown above. It will automatically convert your rectangle to button (if more than one
objects are selected, this command will convert each to button individually). Next,
second one from left is used to convert single or multiple selected objects to
separate “Sprites”. For single object it works same as “Group as Sprite”. The third
one from left is used to break single or multiple selected objects among sub shapes
and group then into separate “Groups”. In case of text, when you select a text object
and click this icon, all the text characters will be converted to shapes and grouped in
simple “Group”. It is an advantage when you are using different fonts, than the
default fonts used by operating system. The 4th icon (convert to letters) is used with
text object only. It is useful when you need to ungroup a text object in separate
character objects. Select you text object and click “convert to letters” icon, all the
text will be separated in letters and will be grouped automatically. The last icon is
used to break a shape or a text object among custom style and number of pieces.
After you click this icon a dialogue appears with more options (shown below) with
break style and number of shapes.
17

Insert toolbar

This is a multipurpose toolbar. You may have noticed, when you create new movie
(or start SWiSHMax, there is a new empty movie by default), there is only one scene
in it, named as “Scene_1”. You may insert as many scenes as you want in your
single movie. It is a modular approach to divide major parts of your movie among
different scenes (further detailed discussion can be found in upcoming chapters). The
first icon on left side of toolbar is used to insert new empty scene. Second one from
left the “T” shaped is used to insert text object in your movie. It will insert new text
object by using fonts, colors, direction etc used last time movie edited. The third icon
from left, green icon is used to insert a BITMAP image into your movie (for now
supported image formats are BMP, JPEG, GIF, PNG, DIB). The fourth one “Insert
Content” or “Import” is used to import WMF (Windows Metafile), EMF (Enhanced
Metafile), sound files MP3 and WAV, SWF file, text file, extract SWF from EXE
projector, or even SWI files priorly created with SWiSH 2 or SWiSHMax. The fifth
one/second last icon (similar to “Convert to button” icon) is used to insert an empty
button with light blue color, which is by default 26 pixels wide and 26 pixels tall.
Where you can draw desired shapes and text in it.

Movie Control toolbar

Shortcut Icons in this toolbar are used to control your playing movie (within
SWiSHMax). When you play the movie within SWiSH 2 or SWiSHMax interface, these
buttons are used to control the playing SWF. First two are Stop and Play (no need to
define them I hope). Third one is Play current Scene. Fourth one is used to Play
currently selected effect. Next five icons are used to move within timeline frames.
The Fifth icon (two left arrows with vertical line) is used to bring your playing movie
to first frame (frame 1 in SWiSHMax and frame 0 SWiSH 2). Sixth one (two arrows
left) is used to go to one frame back. Seventh icon is used for “Preview Frame”.
When you turn it on, you will see a red line over the movie timeline. By using this
tool you can view your movie frame by frame. Just click it and drag it over the effect
in timeline. Eighth one/second last icon is used to set your movie one frame forward
(if playing). The last icon is used to go to the last frame of your movie.

Export toolbar

Tools in this toolbar are used to finalize your movie project (Export to or test the
movie). First four icons are easy as they are shown. Export to Flash Format SWF file,
HTML page alongwith SWF, Create deliverable EXE projector, export to Microsoft
video file AVI. The fifth icon “Export HTML to Clipboard” is used to copy the html
code of the movie to system’s clipboard, which may be then pasted anywhere using
Ctrl+V. Next two icons are used for testing your movie. You have two options, either
18

to test in Browser or in FlashPlayer. The third last icon is used to test your movie in
Browser (latest version of FlashPlayer PLUGIN must be installed on your system). Or
if you test it in FlashPlayer by clicking on last icon, there must be Flashplayer EXE
available on your disk and SWF files must be associated with it. The last icon is
‘Report Generator’ which generates report of your final SWF to be published with
complete information of each and every part of the movie and objects holding
specific number of bytes, see the preview of a normal report:

Menus

File

Menus contain most of the functions, which are used by shortcut icons available in
toolbars (which have already been defined). Starting from First menu ‘File’. Five new
items/sub-menus in “File” menu, which are not present in toolbars, are “New from
Template…”, “Save as Template…”, “New Window”, “Samples”, and “Close” (shown
below).

Command “New from Template” is used to create new SWiSHMax movie from
predefined sized movie templates.

Command menu “Save as Template” allows you to save your movie template
as ‘SWI’ in SWiSHMax’s own templates folder.
19

Menu “New Window” is used when you want to have one more copy of SWiSH 2 or
SWiSHMax running at the same time.

“Samples” menu contains premade samples (by SWiSHZone official designers). You
can directly open modify and export any sample. Menu shown below:

“Close” menu is used to close current source file and create new empty file in design
window (Layout Panel).

Edit

Some new things in “Edit” menu, which were not found while we discussed toolbars.
They are “Make Instance”, “Show”, “Hide”, “Show All States”, “Select All”, and
“Properties”.

An Instance is the copy of any “Sprite”. An instance cannot work on its own because
it is not just a copy of any sprite but use to contain all of the peculiarities of the
sprite from which it is copied. So “Make Instance” is used to make further Instances
of an existing instance (best way in movie optimization, especially when using same
type of Sprites more than once; further discussion can be found in upcoming
chapters).

“Hide” menu is used to hide currently selected object(s) in design window. “Show”
menu is used to unhide the hidden object(s). Both functions can be applied on multi-
selected objects as well.

“Select All” as clear from its name, used to select all the objects in current movie
scene. And “Deselect All” is used to selected any selected item(s).
20

“Properties” menu has multiple functions. It brings specific Property Tab in focus for
specific type of object.

For example you have selected a Rectangle. If you click on “Properties” menu, it will
show you Tab or Shape in Properties window, as shown below:

View

Discussible functions in the “View” menu. First one the sub menu to Toolbars menus
is “Customize”, which will be discussed later.

“Status Bar”, which is checked (turned on) by default. It works same, as in other
windows applications. It shows short description of menus and other operations,
while you select menus or objects. And if it is unchecked (turned off) design window
is expanded, so design area is increased.
21

“Rulers” menu, which is unchecked by default. It is used to show rulers in design


window, when checked. The design window looks like below, when it is

selected/checked/turned on:

“Zoom In” and “Zoom Out” menus. If you movie is zoomed 100% and you click on
“Zoom In” menu, it will increase 50%. On next “Zoom In” clicks the percentage (of
Zooming in) will increase gradually e.g. on second click it will increase movie size
with 75% and so on. It is useful especially when you need to design small shapes.
Scrollbars are automatically added to design window when movie size is greater than
default design window size. “Zoom Out” has opposite functioning than “Zoom In”. It
decreases current movie size to last corresponding size. But remember these do not
increase or decrease the actual size of movie or objects.

“View at 100%” menu brings your movie to its actual size either it fits in the Layout
Panel or not.

Menu “Fit Scene in Window” fits your movie to design windows, either the actual
movie is larger or smaller than design window.

Example to clear it:


Before Fit (100 or 108%) After Fit (36%)
22

“Fit Objects in Window”, has entirely different functionality. It fits only the area
occupied by objects.

Example:

“Show Grid” menu enhances your design window. The design window just turns to a
scientific/calculated CAD. Then it becomes very easy to manage objects on right
place.

Example: After “Show Grid”


23

“Snap to Grid” menu turns your SWiSHMax design window to a sophisticated, and
manageable IDE. Like the one used in VB. After turning it on, when you drag the
objects, they are not dragged smoothly, but move on the grid lines.

“Snap to Object Handles” menu works almost same as “Snap to Grid”. But difference
is when you drag some object it moves probably on the edges of other objects and
grid lines as well.

“Show All images” menu, which is turned on by default. If you turn it off it effects
when you insert images. If it is turned off/unchecked and your image object is not
selected, design window will show that images as shape with red color filled in it
(just like a normal shape). And if you select an image, design window will show
actual image and all other images (which are not currently selected) will be shown as
red filled shapes.

“Smooth Edges and Images” menu, turned on/checked by default. If you uncheck it,
design window will show you all the objects with sharp edges. But keep in mind, it is
just to change the view, there will be no effect on exported movie.

Example: Turned on / by default Turned off / unchecked


24

Insert

“Insert Frame” menu is used to insert frame in between existing filled frames or
inserting new empty frame.

Example Before Inserting frame After Inserting frame

“Delete Frame” menu works opposite to “Insert Frame”. It deletes currently selected
frame. After deleting frame the timeline becomes like this

Example After Deleting frame

Note: Hot keys for “Insert Frame” and “Delete Frame” are same as in Flash.

Modify

This main menu contains four new menus, which have further sub menus. Let us
define them one by one.
25

“Transform” menu is used for rotating, flipping, and resetting (bring to original
position and angle) the selected object. “Reset” submenu is used to reset the
selected object to its actual size and position. What is actual size and position? For
example you have created a rectangle, and you have stretched / resized or replaced
it. Now you want to bring it to the position where it was drawn. You will just use
“Reset” menu to do so.

“Justification” menu is used to justify any text object. You may have used
common word processors like Word Pad or MS-Word. Which allow you to Align
your text on the page. A text object in SWiSH is different from the one in
Flash. These features are useful when you have multiline text. “Align Left”
bring text in text object to left and so on.

“Appearance” menu allows you to give new directions to your text in the text object.
This feature is not found in any word processor. I hope you already know about Bold
and Italic. All of these functions are specific to the text objects. First one in last four
is “LR-TB Flow”, which is selected by default. You can select only one direction at a
time. The default one is normal direction as the English styled text uses. “TB-RL
Flow” is same to one of the functions used for rotating object. If you rotate any
object on 90 it will work same as said menu function. “RL-TB Flow” menu writes your
text object in Arabic/Urdu/Persian writing format (right to left). If you use this
function with single line text, then it has no same effect as “TB-RL Flow”. But if you
select it with multiline text, it rearranges all the text line. Means, The text flow goes
from bottom to top.
26

Tools

When “Customize…” menu is clicked it displays a dialog like this:

This dialog contains about six tabs; we will be discussing only two important tabs,
“Keyboard” and “Options”.

“Keyboard” tab contains all information of hot keys being used by SWiSH interface.
You can remove hot key from any menu, you can add new hot key to any menu, and
you can change hot key for any menu. I will example for each function.

1. Removing hot key from “File” -> “AVI” menu.


2. Select “File” from the Category combo
3. Select “AVI” from Commands listbox
4. Click in “Current Key” listbox
5. Last click on Remove button, and press close button

Hot key / shortcut key is removed for AVI export menu.


Now we re-assign a new hot key to it. Follow the above mentioned four steps.

Then click on “Press New Shortcut Key” textbox. And press any key. If “Assign”
button is enabled then click the “Assign” button to assign it otherwise press another
key.

New hot key has been assigned to “AVI” export menu. Now we try to change it.

Do same as we done to assign new key, and press some key, other than the one you
have assigned before. Click “Assign” and then close. New key has been assigned.
27

You can assign more than one key to one many. For doing this just skip the step
No.4.

“Options” tab has four functions. First one is “Show ScreenTips on toolbars”, which is
set on, in case when you want each component of the interface to show ToolTip
(when mouse cursor is over it). “Show Large Icons”, is clearing its meanings from its
name. If “Look 2000” is checked, it displays flat buttons on interface, otherwise the
buttons are shown using traditional win32 button style. This is turned on / checked
by default.

“Keyboard Map…” menu shows all the shortcut keys assigned and one line
description of each function of any menu. When you click it, it shows you a dialog
like this one:
28

“File” menu is selected by default. You may select any menu from the Category
combo and view descriptions of its items (in the form of table). You can click on any
item and copy it to clipboard as text. You can even select multiple lines or entire
table and press the icon (on the left of Category label) to copy.

Panels

Menu item “Reset to Defaults” is used to set your SWiSH interface to standard view.
It opens most important panels and tabs required and keep the rest of panels closed.

Important panels of SWiSHMax to start working with are “Layout”, “Timeline”,


“Outline”, and “Script; and basic property tabs “Object”, “Debug”, and “Export”.

“Layout”, which I have been calling design window. If this is unchecked/unselected,


you won’t be able to draw anything. Because when layout is not present you cannot
use design tools.

“Timeline”: What is timeline? Timeline is the place that contains effects and frame by
frame animation of your movie.
29

“Outline”: If this is not turned on/checked, you cannot see the hierarchy of the
objects. And even not able to select desired object easily. A big disadvantage of
closing it is, you cannot understand the structure of the movie objects.

Even outline itself contains a drop down menu named ‘Insert” with an arrow, which
has almost all core Objects + new Scene contained in (but not functions).

Applying built-in effects on objects

In this topic we will learn how to insert a normal effect to a text object and a
rectangle. Create new SWiSHMax file, insert a text object and enter desired text in it.
Now select the text object, go to the timeline window, where you will notice that the
text object is selected. Now right click on the first frame of the timeline (in front of
the text object), and select custom effect, as shown in the following image:
30

After the effect has been placed, the timeline looks like this:

3D Spin (20) means the effect name is ‘3D Spin’ and consists of 20 frames. Since
there are hundreds of built-in effects in SWiSHMax, you can test them yourself. You
can apply more than one effects on single object, by putting effects in the same
timeline one after each.
31

Scripting Modes

As we already mentioned that, SWiSHMax has its own complete language


syntax dictionary for writing SWiSHScript, as well as a sophisticated Script Editor.
The built-in Script Editor provides you a big ease by allowing you to work in two
different modes.

1.Guided
2.Expert

As Shown in following Screenshot.

Guided Mode Expert Mode

Using Guided Mode you are bound to use the given script syntax, which is
useful for the beginners and intermediate level developers (to start learning
SWiSHScript). Further, it provides you a big ease by showing you input fields, which
fulfil the requirements of the specific script. As well as Using Expert Mode you are
free to write anywhere and align your scripts according to your coding style. While
reading / practicing this book, I would recommend you to use Expert Mode to Learn
SWiSHScript properly.
32

You can easily switch between modes by using a button on the top-middle
corner of the Script Editor, as shown below:

Which object the script belongs to (currently visible in Script Panel)?

Very Simple! The Outline Panel contains all of your movie objects in a
hierarchical (tree) presentation. More Simple is, all movie objects are listed in the
Outline Panel. Now the script you write is always attached with the object currently
selected in the Outline Panel, either that is a button, a sprite, or any other type of
object, as shown in following screenshot. A selected object in Outline Panel is
automatically highlighted (as Button is highlighted in example), and then you can
start writing script for that selected object in the Script Editor/Panel. The script will
be attached to the selected object. After moving around other objects, when you
return to object (you previously wrote script for) you will find the last
modified/written script in it.

How to put my script/actions in timeline?

I am sure, you are familiar with Timeline Panel/Window. First I must give you
the idea of sprites then we go further. Sprites are the Sub-Movies within Main Movie,
Sprites use to have their own Timeline and further sub components (find more
details in chapter 2, topic 1). I think it is the most simplest/understandable definition
of sprite, if you have already worked on sprites in SWiSH 2.

To write script in timeline on a specific frame, click on the frame and write
your script in the Script Editor Panel. But when you select a sprite object from
Outline Panel and write script in Script Editor/Panel, the script goes into the timeline
33

of the selected sprite. Similarly, when your have selected a Scene and write script,
the script goes into main timeline of the selected Scene.

Now, to write script for a specific frame, you must enclose the script within
the Frame Event handler (onFrame(){ }). See following screenshot carefully.

Frame 1 (one) contains a stop action and frame 2 (two) contains play action. Both
frames contain separate script. There are two different scripts for both frames 1 and
2. And you must have noticed that each frame script is enclosed within

onFrame() {

Some of the script events are relative to their absolute path, such as
onLoad(){} and onEnterFrame(){}, (which will be discussed in chapter 2, topic 2)
which are not shown in timeline frames (as shown above for stop, play actions), but
reside in the timeline, see following screenshot:
34

Adding comments in Code

Comments are additional text in code for explanation of the specific script, so
that, it becomes easy and readable for other developers to understand your code.

Adding comments to SWiSHMax Code (SWiSHScript)

For example we have code:


mysprite.gotoAndPlay(15);

Which is used, to go to frame number 15 of sprite ‘mysprite’ and play it. So, we add
the same explanation as comments with the code as follows:

//go to frame 15 of sprite ‘mysprite’ and play


mysprite.gotoAndPlay(15);

Note: ‘//’ is used to make a comment of single line text

Comments are not compiled neither executed when movie is assembled into final
SWF. Using two consecutive forward slashes ‘//’, we can only remark single line text.

For multiline comments text we will use as follows:

/*
Go to frame 15 of sprite ‘mysprite’ and play
Line 2 comments
Line 3 comments
*/
mysprite.gotoAndPlay(15);

Note: Start with /* and end with */ to remark text as multiline comments

Adding comments to PHP Code

Both above-mentioned methods are used the same way in PHP code, but PHP
extends one more way to add single line comment (using #) as below:

<?
//SWiSH MAX Style Comments 1

/*
SWiSH MAX Style Comments 2
*/

# PHP extra Style Comments

echo “This will be shown on browser”;


?>
35

Chapter 2

Getting Started

ƒ Movie Physical Objects


ƒ Data types and Variables
ƒ Type Casting or Type Juggling
ƒ SWiSHScript Basics
ƒ Mathematical and Comparison Operators
ƒ Taking decisions in SWiSHScript using ‘if’
ƒ Logical Operators
ƒ Ternary If-else structure
ƒ Loop Structures
ƒ Breaking loops Unconditionally
ƒ Skipping the code in loops, Unconditionally
ƒ Tuning up code with ‘switch’ set statement
ƒ Working with Functions
ƒ String manipulation
ƒ Button and Sprite Object properties and event handlers
ƒ My first SWiSHScript application
ƒ Understanding Levels
ƒ _root, _parent, this, and _global
ƒ Use of ‘tellTarget’
ƒ Use of and ‘with’
ƒ Dragging the objects at runtime
36

Movie Physical Objects

I would like to give you much more practice (instead of writing bundles of theory), so
lets get a GO.

In SWiSHMax the Movie objects are categorized as:


1.Shape
2.Text
3.Button
4.Group
5.Sprite
6.Instance

In this topic, we will be discussing Text Object, Button Object, Sprite Object,
and Instance Object. I would like to concentrate upon core Objects, which will be
used during our application development. So let us start from Text object.

Text Object

A Text Object (in a SWiSH Movie) can hold text of specific size, font, color,
direction, and angle. It can be either singleline text or multiline text (which is
dependent upon the application/design requirements). It has 3 (three) types; each
type of Text Object is used for different purpose. Before we continue to explore types
of Text Object, we must know how to create a Text Object in our movie.

How do I create a Text Object in my Movie?

Simply click the Text Tool in Layout Panel (Drawing Tools) as shown below,

then draw the Text Object using Left Mouse Click. Once you click the Left Mouse
Button (do not release mouse button immediately), drag your mouse; It will draw a
thin rectangle until mouse button is not released. So when you come up with the
37

desired size of rectangle, release the mouse button, you will see a Text Object is
drawn in Layout Panel/Window, as shown below:

How to set Text Object Type (static, dynamic, input)?

When you have inserted the Text Object in your Movie, select it, and go to Properties
Tabs, you will find a Tab named Text. Where you may change (each and everything
changeable) all properties of a Text Object, as shown in following screenshot:

(Note: object also visible in Outline Panel)

a. Static Text
As it is clear from title ‘Static’, it cannot be changed via script (assignment) at
runtime. It may have all peculiarities (not properties) usually a text Object has, such
as fonts, color, size, direction, and angle. This type of Object is used for static
headings, titles, and labels.

b. Dynamic Text
This is the topic where you start learning core Script and Objects. So pay full
attention onwards. A Dynamic Text can be changed at runtime (via script). A
dynamic Text Object always has a name (Object name) and a variable attached,
through which we can change and get the value of it.
38

What Is a variable?

Variables can be called the data containers, which are used in your script. We can
assign (initialize) them data, store data of any type in the variables, and their value
can be modified, updated at runtime (through SWiSHScript).

Better approach for creating variables is to define them in the start of your
SWiSHMax project. A variable in SWiSHScript is available after it has been defined.
For defining a variable, first, we must decide the type of data it is going to hold.
Then name of the variable.

Examples:

Defining a variable:

Define a variable with name ‘myVar’ to hold numeric data:

myVar = 10;

Define a variable with name ‘myVar’ to hold numeric data (floating point/ with
fractions):

myVar = 10.34;

Define a variable with name ‘myVar’ to hold text/string data:

myVar = “Ali Imran”;

or

myVar = ‘Ali Imran’;

Define a variable with name ‘myVar’ to hold boolean type data (true/false):

myVar = false;

After a variable has been defined, it is available across the movie to all the objects
and scripts.

Upcoming chapters entail the further study on variables and data types.
39

How to set Name of a Text Object?

Select the Text Object; go to its properties Tab, and type name of the object in
Name field, as shown in following screenshot; we have named our Text Objet
‘MyObj’.

How can I get value from a Dynamic Text Object and Save in other Variable?

Simple way of getting value from a Dynamic Text Object is, to access its text
property, see the following script.

on(press) {
MyTempVar = MyObj.text;
}

on(press) {} the button event handler


MyTempVar a new variable, which will be assigned value of the Text Object ‘MyObj’
MyObj.text accessing property ‘text’ of MyObj (Dynamic Text Object)

Moreover, a variable can be attached to Dynamic Text Object. By attaching a target


variable with a Dynamic Text Object, it becomes easy to get and set value of the
Dynamic Text Object through that variable directly.

How to attach target Variable with a Dynamic Text Object?

See just right to the name field of the Dynamic Text Object in Text properties Tab,
you see a checkbox (captioned Target), as shown below:

By clicking this checkbox and turning it checked/ticked/on, means you are to attach
a target variable with this Dynamic Text Object.
40

So it looks like this

Now to set name of the attached / target variable (being within the properties tab),
select Advanced options from the menu just below color picker, and write the
variable name in the ‘Variable’ field as shown in following screenshot:

So we set/attached the variable ‘myVar’ with Dynamic Text Object ‘myObj’.


Now we can directly access / modify value of the Text Object without using its ‘text’
property, such as

on(press) {
MyTempVar = myVar;
}

on(press) {} the button event handler


MyTempVar a new variable, which will be assigned value of the Text Object ‘MyObj’
myVar Variable attached with the Dynamic Text Object(value in MyObj)

And to set new value, we will use it the same way


myVar = “This is my new value”;

Concatenating / Joining
myVar = myVar + “This is my new value”;
or
myVar = myVar add “This is my new value”;

add operator works same as ‘+’


41

c. Input Text
This type of Text Object has almost same properties as of Dynamic Text, in
extension it is used for user input. By using Input Text Object, we can create input
fields, where users can type some value. The same way is used to attach variable to
an Input Text object as is used for Dynamic Text Object.

Furthermore, we can restrict the user to input specific characters, by using


Character options available, as shown below:

We can also make a text box black rectangular border and make it selectable, so
user can select and copy the text from our application.
42

Button object

Buttons are built-in structure of an SWF movie, so we can utilize buttons


making more and more options (available to user) in our applications (within
SWiSHMax environment). I hope you know how to create buttons (and Group as
button) in SWiSH.

We can control a Button by adding event handlers to it.

What is Event Handler?

A block of code, through which we can capture the (mouse clicks, keyboard keys
pressed, etc) events and perform specific operation on each event occurrence. For
example, we use on(press) for a Button. on(press) Event Handler is used to capture
the mouse single click (mouse key not yet released) over a button. We put all of our
code in it enclosed in curly brackets { and }. We can use on(release), on(rollOver),
on(dragOver), etc as well.

A simple code for a button to go to a certain frame o current timeline and play, (on
mouse click) will be

on(press) {
gotoAndPlay(5);
}

Explanation:
gotoAndPlay(5); go frame number 5 (of current path) and play

Sprite Object

Sprites are very easy to understand, as I already mentioned, “Sprites are


Sub-Movies within Main Movie”, which may contain further Sub Movies and different
Objects. A sprites uses to have its own timeline and frames.

How to group some of my objects in single sprite?

You can do so by selecting the objects to group (as sprite), and then clicking “Group
As Sprite” button from the Grouping Toolbars, as shown below.
43

How to send a sprite on specific frame and play using gotoAndPlay() action?

As we already used one example to go to frame number 5 (five) and played the
movie using gotoAndPlay() function, for sprite we will be putting a prefix path to the
sprite and then call the function. Assume we have a sprite named ‘xyz’ in main
timeline, and a button. When the button is clicked the sprite goes to frame 10 (ten)
and play.

Button Event Hander and code


on(press) {
xyz.gotoAndPlay(10);
}

Where xyz is the prefix path (name of sprite).

The same way we can access / modify the variables in a sprite. The . (dot) is used to
point internal functions or properties of an Object.

Assume we have Dynamic Text Object and its variable ‘myVar’ in the sprite xyz; and
we want to assign it a new value, how would we do that, see code below.
on(press) {
xyz.myVar = 2004;
}

We can use multiple nested sprites within Sprites. To point a sub-sprite within sprite,
we use the same way; suppose we have sprite xyz, and it contains further sub-sprite
named ‘cde’, and then cde contains a variable myotherVar. See how we have
accessed it from main timeline.
on(press) {
xyz.cde.myotherVar = false;
}

This was the simple description of a Sprite Object, now we move on to the Instance
Object.

Instance Object

Instance (as it defines its meanings) is clone of some Sprite Object. You
would be thinking ‘why not to copy and paste a sprite if we need to clone it’. A
copied and pasted sprite is a new sprite, which may contain completely different
Objects and structure from the actual one (it is copied from). But Instance Object is
a bit different type of sprite. An Instance is clone of some sprite and does act same
as the base sprite (the sprite it is cloned from) does. Means that, if you make any
changes in base sprite that will automatically occur in cloned Instance Objects; and
same when you make any changes in cloned one it will effect the base sprite. It is
44

not much useful to us, because we are not going to use it much in our upcoming
SWiSHScript practice.

How to make a copied sprite Instance of other sprite?

Simply copy the desired sprite and paste it, then select the copied one and go to its
‘Sprite’ properties tab; and select a sprite (to make Instance of) from combo field
labeled ‘Instance of’, as shown below:

Reference: SWiSH MAX Help Manual, delivered with SWiSH MAX Product

Note: There are reserved names that you are NOT allowed to use as the name or
variable for scripted objects. The list of reserved words is as follows:

Math, String, Timer, Date, Key, length, text, htmltext, scroll, maxscroll, _root, _parent, this,
do, else, for, if, not, playSound, preloadContent, return, setLabel, setLabelAnchor,
stopSound, tellTarget, trace, var, while, with, return, true, false, PI, E, LN10, LN2, LOG2E,
LOG10E, SQRT2, SQRT1_2, newline, tab, NULL

Data types and Variables

Data / Information may be of any form. The Data usually processed by our
computer applications is of limited types, such as Text data, Numeric data, and
logical true/false (Boolean) data. So whenever we need to store and retrieve data
into/from computer memory we use variables to store it. Variables may be defined
as ‘a name or textual representation, that identifies a specific location of memory
holding specified type of value’. Word ‘Variable’ means, a value holder that can vary
(at runtime) its value according to our application needs. Now it is dependant upon
our application requirement the type of data we will be holding in variables.

How to define a new variable?

Defining a variable in SWiSHScript is so easy, simply use new variable name


and assign it some initial value, variable is created, see below:

varname = some value;


myVar = 10;
45

myVar is the name of new variable and 10 (ten) is its initial (numeric) value. So our
new variable ‘myVar’ contains a numeric value 10 (ten), which may be changed
anytime through script using same expression (e.g. ‘myVar=20’), that we used while
creating it. Type of this variable is automatically adjusted (by movie) to numeric.
Now let us discuss mostly used data types in our scripts.

By the way: ‘=’ is called Assignment Operator, used to assign some value to
variable on left side of it. Which will be discussed in detail in upcoming topics.

Numeric type data (Integer/Float)

As you see in above example, we created a variable and assigned a numeric


value to it, so we can call this variable, an Integral/Integer type variable. What is
integer? Integer is a name of data type (type of information). Variables which hold a
numeric value without fractions (12.098, 10.3), means the variables holding round
value, are called Integer type variables. As well as, a value having fractions/digits
after decimal point are called Float values or floating point values, such as 123.444,
434.66, and 43455.44. So, the difference in Float type variables and Integer type
variables is just digits after decimal point. E.g.

Integer type variable myVar = 10;


Float type variable myVar = 10.43;

When value of an Integer type variable crosses number like 65535, is


considered as Long type variable; as well as, there is a limit for Float values, when
value is more than that specific limit, it is treated as Double. For now, you don’t
need to worry about these extra types, because type is adjusted automatically, by
the Flash Player which runs our movie.

Textual/Text Data (String)

A variable containing Text data, is called of variable of type String. The word
String ,is used in almost all scripting languages to present textual data. String may
be defined as ‘a chain of characters/letters in sequence’. String is most commonly
used data type to store Names, Titles, Labels, Paragraphs, etc.

How to define a String type variable?

varname = “some text value”;


myStrVar = “this is my Text”;

The same way as we defined Integer variables in previous example. The difference is
just the quotes (“) and (”). It is a rule, that, the value of a string must be within
quotes. Now boundary may be single quotes or double quotes around the value. So
you can also assign String value to a variable as shown below:

myStrVar = ‘this is my Text’;

‘myStrVar’ is a variable of type String and holds a text value of ‘this is my Text’.
46

True/False type data (Boolean)

This is the data type used to create variables which can hold either true or
false. Means ON or OFF. These are created and used mostly when we need to create
variables acting like a usual checkbox which is either switched ON or OFF. This type
of variables are called Boolean type variables, which can hold only true or false.

Defining a Boolean type variable

varname = true;
varname = false;
myBoolVar = false;

Remember: Variable myBoolVar can hold only two kinds of value either true or false.

Boolean is an enumerated type where true is 1, and false is 0

Note : If a variable is assigned a new value of different type, the type of variable is
automatically changed to the type of new value.

Type Casting or Type Juggling

Type Casting is a terminology used in powerful languages such as C/C++ and


also in Flash MX ActionScript. It is also called Type Juggling in PHP language. Which
means, conversion from one data type to another data type. Let me quote an easy
example to make it more clear. For example: you have a variable ‘myFloatVar’ that
contains a numeric value, and value type is Float (means, value has fractions), say
13.25, and you want to get its Integer value through Type Casting, so that, it gives
you round value of 13 (thirteen), in stead of 13.25.

Assume myFloatVar is priorly defined as:


myFloatVar = 13.25;

Type Casting, and putting result in another variable ‘myTCv’:


myTCv = int(myFloatVar);

Note carefully, what we did is, we used a built-in function int() to convert a Float
type value to Integer type value, and passed variable ‘myFloatVar’ to this function;
the integral value generated by this function, is then assigned back to variable
‘myTCv’. Now myTCv holds integral value of 13 (thirteen).

In previous example of Type Casting we did conversion between almost


similar data types (Integer and Float both are numeric). Question is: What does a
Boolean value (true/false) give back, when it is converted to Integer using Type
Casting method int()? Answer is so simple: if the value being converted is true, the
result will be numeric 1 (one), otherwise if it is false, the result will be 0 (zero).
E.g.
47

myBVar = true;
myIVar = int(myBVar);

myIVar now contains 1 (one), because value obtained from Boolean variable
‘myBVar’, was true.

Another question is:


If we need to fetch Integer or Float value from a string, how to do that?

Previously discussed function int() may also be used to get numeric value form a
String type data as:

myStr = ”8”;
myInt = int(myStr);

Now value of variable ‘myInt’ is 8. But function int() has a disadvantage or may be
called less in functionality, that, if String value (which is being converted) contains
characters other than digits, the result of conversion is returned as 0 (zero). See
example here:

myStr = ”8xyz”;
myInt = int(myStr);

Variable ‘myInt’ is containing 0 (zero) now, why? Because, if there is any character
that is not digit in String value, the result of conversion will be 0 (zero). As in
example extra characters are ’xyz’ which are not digits, so the resulting value is 0
(zero) in myInt.

Ignore non-numeric characters and convert rest of String to a Number:

Here, we introduce you 2 (two) new functions used for conversion of String type data
to numeric type data. Functions are parseInt() and parseFloat(). Both of the
functions accept a String value as argument and return its possible numeric
representation. An easy example:

myStr =”7”;
myInt = parseInt(myStr);

or

myStr =”7xyz”;
myInt = parseInt(myStr);

Both of the above examples will result value of variable ‘myInt’ as 7 (seven).
The same way we obtain a Float (floating point) value from String type data. See
examples:

myStr = ”7.33”;
myFloat = parseFloat(myStr);

or

myStr =”7.33xyz”;
48

myFloat = parseFloat(myStr);

In both cases, value of variable ‘myFloat’ will be having numeric value 7.33. In
second example (of above two), the characters ‘xyz’ have been recognized as non-
numeric, and ignored while conversion. So we can say, function parseInt() and
parseFloat() are best for conversion from String data type to numeric data types.

Remember: The value of ‘myStr’ must start from a digit otherwise it will result in
NaN (Not a Number).

You can also obtain Integer or Float value out of Hexadecimal, Octal and Binary type
data, using function parseInt(), but passing it second argument as base.

myDecimal = parseInt(“890”,8);

So it treats 890 as octal value, and will return corresponding decimal value. Function
parseInt() with 2 (two) arguments may not be supported by older builds of
SWiSHMax.

SWiSHScript Basics

There is no prior knowledge of scripting required in order to study


SWiSHScript basics. This book guides you through all the levels of SWiSHScript. So,
the key to learn SWiSHScript fully, is to pay full attention to each and every line of
the book.

At this point I am sure, you are capable of creating variables and assigning them
proper type of values. Let us enable our script to take decisions, on different values
of variables. Basics of SWiSHScript start from simple expression evaluation.

E.g.

A = B + C;

Expression : B+C Add B to C


Assignment : A= And save result in A

Remember to put a semicolon after each complete statement of SWiSHScript.

Let us get started with Mathematical Operators first.


49

Mathematical Operators

These are the operators allow you to perform usual mathematical operations,
such as Addition, Deduction/Subtraction, Multiplication, and Division of values of
variables in SWiSHScript. First we discuss 4 (four) basic mathematical operators then
move forward.

Addition or Concatenation Operator (+, add)

Addition Operator ‘+’ (plus) is used to sum/join two or more variables/values.


Previous example shows how to sum two variables, I repeat it here

A = B + C;

Variable ‘B’ is added to ‘C’ using Addition operator and result has been assigned to
variable ‘A’. You can also use Operator ‘add’ instead of ‘+’, such as:

A = B add C;

Which will result exactly the same. Two or more String values/variables can be
joined/concatenated with each other the same way we sum Numerical
values/variables. See example

Str1 = “Ali”;
Str2 = “Imran”;

Result = Str1 + Str2;

or

Result = Str1 add Str2;

Where ‘Str1’ and ‘Str2’ are String type variables, they are joined using
Concatenation/Addition Operator and resulting String value is assigned to variable
‘Result’. (where result is “Ali Imran”)

Question is:
When Operator ‘+’ and ‘add’ work the same, then, why to use 2 (two) different
operators for same purpose?

Answer is simple; They are alternate of to other. You can use either. But
purpose of bringing both into your knowledge is a bit advanced. Good approach is to
use Addition Operator ‘+’ when performing numerical operations, on other hand, use
Concatenation Operator ‘add’ while concatenating/joining String values. It is good
practice because, it makes your code more readable and easy to understand, so the
reader (reading your code) can differentiate between Numerical and String
operations easily.

Now, how about joining a numeric value with a String value?


50

So simple:
Use either of the Addition operators to join String value with a Numeric value. See
example:

Str1 = “Ali Imran is of ”;


myInt = 27;
Result = Str1 add myInt;

So the resulting value is “Ali Imran is of 27”.

Deduction/Subtraction Operator

Operator ‘-’ (minus sign) is used for subtracting one value from another. It is
used for mathematical operations only and not applied over non-numeric data types
such as String data. If it is applied over non-numeric data, the results are not
generated as desired (means results are unpredictable).

So the expression will be:

A = B - C;

Explanation: Subtract the value of variable ‘C’ from the value variable ‘B’, and assign
results to variable ‘A’. I don’t think there is anything special in it to define, so let us
move to further topic.

Multiplication Operator

For performing multiplication between two or more variables/values we use


Multiplication Operator ‘*’ (steric). This operator is specific to Numeric operations.

Expression:

A = B * C;

Multiply the value of variable ‘C’ with the value variable ‘B’, and assign results to
variable ‘A’.

Division Operator

This operator ‘/’ (forward slash) is used to divide value on left side among the
value on right side of the operator. Same to the Multiplication and Subtraction
Operator, this operator is also specific to Numeric operations. See following example
to make it clear:

A = B / C;

Variable ‘B’ is divided among variable ‘C’ and the result is stored in variable ‘A’.
Additional Mathematical Operator

Remainder Operator
51

This is some unique operator to you, I hope. Remainder Operator ‘%’


(percent sign), is used to divide the value of on left among the value on right and
then assign the resulting remainder obtained after division to another variable. For
example:

See Division first


B= 5;
C= 2;
A= B / C;

Here Result is 2.5

But if we use Remainder Operator instead of Division Operator as:


B = 5;
C = 2;
A = B % C;

Will result 1

Because 5 (five) cannot fully be divided among 2 (two), so the remainder becomes 1
(one), and that is the result. So the value of variable ‘A’ is 1 (one) not 2.5.

Compressing the Mathematical operations code

This technique is used when you are using a variable 2 (two) times in your
mathematical expression, such as:

V = V + 5;
V = V - 5;
V = V * 5;
V = V / 5;
V = V % 5;

Technique is so simple, please pay full attention, sew following code:


V += 5;

This performs same operation as V = V + 5;

Technique is:

Bring the Operator (‘+’, ‘-’, ‘*’, ‘/’, ‘%’,) on left side of the assignment
Operator ‘=’, as in above example we added 5 (five) to variable ‘V’ using Addition
Operator. Bring this Operator ‘+’ before the Assignment Operator ‘=’, so that it
becomes ‘+=’. Now second step is to eliminate the repetition of variable ‘V’ on the
right side of Assignment Operator ‘=’. Perform the same way to compress any of the
above mathematical operations, see example below:

Actual Compressed
V = V + 5; V += 5;
V = V - 5; V -= 5;
V = V * 5; V *= 5;
V = V / 5; V /= 5;
V = V % 5; V %= 5;
52

Increment and Decrement Operators

These are the useful operators that make your code more compressed and
easy to read. Increment ‘++’ (two consecutive plus signs) and Decrement ‘--‘ (two
consecutive minus signs) operators are used when we need to subtract/add 1 (one)
from/to a variable. See example:

V = 5;
V++;

V++ means V = V + 1;

Simply, value of variable ‘V’ is increased by 1 (one) and is 6 (six) now. You may also
use the operator before (as prefix) the variable name, such as:

V = 5;
++V;

Result will be same, the value of variable ’V’ is 6 (six).

The same way we decrease value of variable ‘V’ by 1 (one) using Decrement
Operator ‘--‘.

V = 5;
V--;

or

V = 5;
--V;

V-- means V = V - 1;
The result, the value of variable ‘V’ will be 4 (four).

I know what is going in your mind, you must be thinking that, if these operators can
be used either as prefix (before variable name) or suffix (after variable name), then
what is the difference?

Different use of these operators (in prefix and suffix), result the value of expression
differently. Means; If these operators are used within expression (not as separate
statement, as we used in above examples), they increase/decrease, the value of
variable before/after the expression evaluation. Now this makes difference, see
example:
B = 5;
A = B++;

Value of ‘A’ is still 5 (five)

Now Increment Operator ‘++’ is used within expression (not as separate statement).
In this example value of variable ‘A’ remains 5 (five). Why? Because value of
variable ‘B’ will be incremented by 1 (one) after it as been assigned to variable ‘A’.
53

One other hand if was use the same operator as prefix to variable ‘B’ in the
expression, it will result differently, see example:

B = 5;
A = ++B;

Value of ‘A’ is 6 (six)

In this example, value of variable ‘B’ is incremented by 1 (one) before it is assigned


to variable ‘A’, because Increment Operator is used as prefix to the variable ‘B’.

So this is the difference, which may be applied the same way using Decrement
Operator ‘--‘.

Use of Brackets in mathematical expressions

Each type (of 3) brackets have separate use in SWiSHScript. The brackets
used in expressions are ( and ). Simply, if a sub-expression which needs to be
evaluated before entire expression is evaluated, we put it in these brackets. See
example:

B = 5;
A = (B+10)*2;

Which will result as 100 (hundred), the value of variable ‘A’. Because the sub-
expression ‘(B+10)’ is calculated before it is multiplied with 2 (two). Where as:

B = 5;
A = B+10*2;

will result as 25 (twenty five), the value of variable ‘A’. Because first priority is given
to multiplication and then Addition. I hope, we do not do any more mistakes next
time, in numerical operations.

Comparison Operators

Let us have an example of game, ‘car speed on road’. Assume, you are
creating a game, where value of variable ‘speed’ changes according to the car speed
in the game, and you change the value (of variable ‘message’) on each specific
speed.

Scenario

When value of variable ‘speed’ is 10 (ten), change the value of variable


‘message’ to “You are too Slow”; When value of variable ‘speed’ is 80 (eighty),
change the value of variable ‘message’ to “Ideal Speed”; And when value of variable
‘speed’ is 120 (one hundred and twenty), change the value of variable ‘message’ to
“Slow Down, it is dangerous”.

It is time to get started with Comparison Operators.


54

Comparison Operators

The operators, which let you compare values with variables and/or variables with
variables, are called Comparison Operators. Basic Comparison Operators are as
follows (operators are highlighted, A and B are variables):

A == B To check Equality (if A equals to B)

A != B To check Inequality (if A not equals to B - A may be


greater or less than B, but not equal)

A > B To check if A is greater than B

A < B To check if A is less than B

A >= B To check if A is greater than or equal to B

A <= B To check if A is less than or equal to B

(From now on all code color switches to blue)

These operators are mostly used to compare Numeric and Boolean data. It does not
mean == and != cannot be used for String data comparison. Operator for Equality
(==) and Inequality (!=) can be used when comparing String data. But good practice
to use operator eq for Equality and ne or Inequality (instead of == and !=), while
doing String data comparison; so the code becomes easy to understand, and
conditions’ difference becomes clear to the code reader. From now on, we will be
using operators == and != only for Numeric and Boolean data comparison, operators
eq and ne for String data comparison. There are some more comparison operators
which will be discussed later in this chapter.

Taking decisions in SWiSHScript using ‘if’

Now let us have a look over first control structure if-else that allows us to take
decisions in our SWiSHScript.
55

if-else Control Structure

It is a control structure which is used to take decision on a specific condition,


and execute specific code. It is the easiest structure to implement in our script. See
the syntax as follow:

if ( condition_block ) {
code_to_execute
}

Simple example of Numeric data comparison:

speed = 10;
if( speed == 10 ) {
message = “You are too slow”;
}

where

if is keyword (reserved word)

{ is start of block which contains code to be


executed

speed == 10 is the condition to be checked

message = “You are too slow”; is the code to be executed when condition is true.

} is end of block which contains code to be


executed

Note: White Spaces ‘ ‘ between variables, operators, values, and keywords are meaningless,
but make the code more clear and readable.

Result of above example will be, value of variable ‘message’ ‘You are too slow’,
because condition is True (value of variable ‘speed’ is equal to 10 ten). On other
hand if value of variable ‘speed’ is not equal to 10 (ten), the code (within curly
brackets { and }) will not be executed, because the conditions becomes False.

The same way to check further speed variations we will implement more consecutive
‘if’ blocks, as shown here:

if( speed == 10 ) {
message = “You are too slow”;
}
if( speed == 80 ) {
message = “Ideal Speed”;
}
if( speed == 120 ) {
message = “Slow Down, it is dangerous”;
}
56

Code of above example is correct but not efficient and more readable. Read next
topic to make it more clear to you.

Required and non-required curly brackets in SWiSHScript

If we put some light on previous code example, we can see 6 (six) curly
brackets used in. Which were actually not required. Why? Because there is a simple
rule to follow:

“When there are more than 1 (one) statements to be executed, we make a block of
statements using curly brackets { and }, otherwise ignore them”.

Example where brackets are required (two assignments, means two statements):
if(V == 10) {
H = 0;
M = ”Vertices”;
}

Example where brackets are not required (single statement, H = 0;):


if(V == 10)
H = 0;

But if you use brackets where they are not necessary, it does not harm your script
such as:
if(V == 10) {
H = 0;
}

So the code for last example of game shrinks down to


if( speed == 10 )
message = “You are too slow”;
if( speed == 80 )
message = “Ideal Speed”;
if( speed == 120 )
message = “Slow Down, it is dangerous”;

There are some more Comparison Operators in SWiSHScript to be used for


String data type comparison, they are:

gt Greater then (acts as to >)


lt Less then (acts as to <)
ge Greater then or equal to (acts as to >=)
le Less then or equal to (acts as to <=)

In last example of a ‘car speed’ we used 3 (three) consecutive if statements as:


57

if( condition )
…….
if( condition )
…….
if( condition )
…….

which executes each ‘if’ conditional statement and check the value of variable
‘speed’. It is not good practice, because there is a single value of variable ‘speed’ at
a time. Better approach is; We must execute one of the ‘if’ blocks where condition is
true and ignore rest of conditions. How to do this? It is very simple. Put keyword
‘else’ before each ‘if’ statement except first one. So it becomes:

if( condition )
…….
else if( condition )
…….
else if( condition )
…….

Now the flow of execution breaks the chain when condition is met (condition is true).
Means, when first condition becomes true, statement below the condition will be
executed and rest of following ‘if’ blocks will be ignored. Otherwise, when the first ‘if’
condition becomes false, your program goes to check next and so on up to the end
of if-else blocks chain.

Question (a): If I want to execute a new statement when all of the above
conditions are not met (all are false), how to implement this?

Simply put an ‘else’ and write the statement (to be executed) following it, see
example:

if( condition )
…….
else if( condition )
…….
else if( condition )
…….
else
i_am_executed_when_all_above_are_false

So replace ‘i_am_executed_when_all_above_are_false’ with the statement you wish


to execute, when all above conditions are false; so that, it becomes almost like this:

if( condition )
…….
else if( condition )
…….
58

else if( condition )


…….
else
message = “All above conditions were false”;

Question (b): I have 3 (three) ‘if’ blocks, each has separate condition, but I want,
when the conditions in first and second ‘if’ block (both) become true, execute single
statement. Is there any way to put first and second ‘if’ block conditions together?
And when both become true, execute single statement.

Answer is : YES, but, for this purpose, first, we need to have some knowledge of
Logical Operators which join two or more conditions within single ’if’ block. So let us
move to Logical Operators.

Logical Operators

The way, two or more conditions (in an ‘if’ block) are joined together is:
For joining two conditions:
if( condition_1 logical_operator condition_2 )

For joining more than two conditions:


if( condition_1 logical_operator condition_2 logical_operator condition_3)

Logical Operators AND ‘and’ or ‘&&’

Following examples + figures will make you all clear.


For Example, my conditions are (in pseducode not actual code):

Translating PSEUDOCODE it into SWiSHScript code:


PSEUDOCODE : Normal Language words used to express the code.

IF A equals 10 AND B equals 12

if( A==10 and B==12)

or

if( A==10 && B==12)

Or conditions may be different from each other as:

IF A equals 10 AND B is greater than 12


59

if( A==10 and B > 12)

or

if( A==10 && B > 12)

This Logical Operator ‘and’ or ‘&&’ is used when you need to take actions if all
conditions are true. It joins two or more conditions in a way that every condition
(connected with ‘and’) must be true in order to execute statement(s). In traditional
programming languages such as C/C++, we use Logical AND as only ‘&&’ not ‘and’.
But in today’s modern languages such as PHP, Flash MX ActionScript and
SWiSHScript, we have choice to use either.

Implementing code for Question (b) in previous topic:

if(A==10 and B>12)


message = “Both conditions met”;

if(A==10 and B>12) if value of variable ‘A’ is 10 and value of


variable ‘B’ is greater than 12, then,

message = “Both conditions met”; assign new value to variable ‘message’

So, when our requirement is to execute a piece of code where two or more
conditions become true at a time (within single ‘if’ block), this is the way we join
conditions using Logical AND Operator ‘and’ or ‘&&’.

Logical Operator OR ‘or’ or ‘||’

Another case is, we want to execute a statement (or set of statements in {


and } block), when any of the conditions is true in a single if block. What do we do?
Simply we join the conditions using Logical Operator.
60

For Example, my conditions are (in pseducode not actual code):

Translating PSEUDOCODE it into SWiSHScript code:


PSEUDOCODE : Normal Language words used to express the code.

IF A equals 10 OR B equals 12

if( A==10 or B==12)

or

if( A==10 || B==12)

In this case, if any/or both of the two conditions, become true, the code /
statement(s) is executed. See implementation:

if(A==10 or B==12)
message = “Any or both conditions met”;

if(A==10 or B==12) if value of variable ‘A’ is 10 or value of


variable ‘B’ equals 12, then,

message = “Any or both conditions met”; assign new value to variable ‘message’

So, when we need to execute a block where any / both of two or more conditions
become true (within single ‘if’ block), we join conditions using Logical OR Operator
‘or’ or ‘||’.

Nested if Blocks

Sometimes our application requirements are different, we need to keep


further checks (check more conditions) after one condition is already met/true. So
we implement nested ‘if’ structure (‘if’ blocks within ‘if’ blocks).

Example PSEUDOCODE:

IF A equals 10 THEN BLOCK STARTS

IF B is not equal to 10 THEN

ASSIGN MESSAGE A VALUE OF ‘Both are not 10’

BLOCK ENDS
61

Implementing above PSEUDOCODE example in SWiSHScript code:

if(A==10) {
if(B!=10)
Message = “Both are not 10”;
}

It is so simple, and I think it does not need to be discussed further. Creating an ‘if’
block and putting more ‘if’ blocks is not that hard job if you have seen the above
example. So try it yourself now. I am sure you understood it completely, and are
now capable of implementing it yourself. This topic was only to make you aware of
this feature of SWiSHScript.

Ternary If-else structure

Ternary means ‘built up of 3 (three) parts’. Now this is the most likened topic
you will see. If you are feeling burden over your head, stop reading, and take a
break of about 20 minutes. After reading this topic, we will be able to tune up all of
our code we used in previous examples of ‘if’ statement. We would be able to bring
our 4 lines code into single line. So get ready.

This structure is implemented within expressions. We know that there is no


keyword ‘THEN’ in SWiSHScript to use after ‘if’ statement condition part. As you
might already have used in Visual Basic / QBasic / Pascal Language / VBScript etc,
such as

IF X<10 THEN
C = FALSE
ELSE
C = TRUE
In SWiSHScript we don’t have this keyword ‘THEN’ and we directly write our
statement after the condition part, as

if(X<10)
C = false;
else
C = true;

But if we implement the ‘if’ structure within expressions, we use an operator to act
as ‘THEN’, and an operator acting as ‘else’.

How to implement Ternary if-lese structure within expressions?


Take the above example to implement it within expression (see example)

C = X<10 ? false : true;

X<10 if value of variable ‘X’ is less than 10,


which is equal to code if(X<10)
? false THEN C is false
: true else C is true

so we can say
62

? acts logically as THEN


: acts logically as else

You see how beneficial it is, that compresses your 4 (four) lines of code into 1 (one)
single line code. See the diagram giving more and more clear view:

if(X<10)
C = false;
else
C = true;

C = X<10 ? false : true;

Loop Structures

What is a Loop?

Loop means structure that implements a method of repeating / iterating a


statement or set or statements while a condition is true. Loop may be used to iterate
statement(s) up to a specific number of times.

Let us get started with ‘while’ loop

‘while’ loop

It is very simple to understand, if you see the following example carefully.

Example:

while( condition ) { if this condition is true


code to execute repeatedly execute this code again and again
}

or see it with another view, do not make scripting mind rightnow

while( condition ) { while this condition is true


code to execute repeatedly repeat this code again and again
}
But problem is, this way our loop repeats statement(s) (within it), infinitely. There
must be some way to break a loop a certain point. Yes! There is a way. The condition
must become false in order to stop the loop. Means, the loop automatically breaks
63

when condition becomes false. In ‘while’ loop, the condition is started being checked
from the very first time, the loop starts.

For example, we have a variable ‘X’. Initial value of variable ‘X’ is 0 (zero), and we
want a loop to repeat adding 1 (one) to ‘X’, while value of ‘X’ is less than 15
(fifteen). See example:

First part (initialization):


Initialize the variable ‘X’
X = 0;

Second part (condition):


Implement loop structure
while(X<15) {

Third part (change in value of variable used in condition):


Now increase value of variable ‘X’ by 1 (one), each time loop executes the code
X++;

} closing the loop block

so it becomes
X = 0;
while(X<15) {
X++;
}

Explanation:

First of all variable ‘X’ is initialized to 0 (zero). On second line the loop checks
the condition ‘if(X<15)’ and executes the statement ‘X++’ if condition is true. And
repeats the same process (of checking condition and executing ‘X++’), until the
condition ’X<15’ not becomes false. The condition will definitely become false when
value of variable ‘X’ becomes exactly 15 (fifteen) or greater.

One thing more, as I already mentioned (while studying ‘if’), that, if we have more
than one statement to execute, we create blocks otherwise leave statement as it is.
In above example we had only one statement ‘X++;’ so there is no need to create
block for it. The code becomes:

X = 0;
while(X<15)
X++;
Or
while(X<15) X++; Bringing both statements in one line, to
save the lines in code.
Let us show the increasing value of variable ‘X’ in built-in debugger of SWiSHMax,
using trace() function.

X = 0;
while(X<5) {
64

trace(X);
X++;
}

it will result in debugger (within SWiSHMax) as:


01234

trace() is a built-in function to track your output, which may be used for error
tracking, or change in variables/objects at runtime. Os we will be using this function
in upcoming examples.

Coding style and saving lines

It is dependant upon you, the coding style you use, whatever you adopt to write
SWiSHScript. The standard followed by Java language coding and Flash MX
ActionScript coding is the same I am using in my examples. Better is to get used to
it and write your applications same way, so the code is of standard style and
everyone can read it easily.

‘do-while’ loop

Structure of ‘do-while’ loop is almost same to ’while’ loop. But has different
use, when we have different requirement of our application. Simply: When we want
our loop to execute the code atleast once, either the condition is true or false, we
use the ‘do-while’ loop.

Structure of ‘do-while’ loop

do {
code to execute repeatedly
} while(condition);

In do-while loop, either you have one or more statements to be executed, you will
have to create block using { and }. This is restriction of syntax which must be
followed, otherwise the code will not work.

Let us implement our previous example using ‘do-while’ loop, with some alteration.

X = 15;
do {
X++;
} while(X<15) ;

Here, you must be thinking, if value of variable ‘X’ is already 15 (fifteen), how come
the loop will go forward? For example: if we do this to the previous example of
‘while’ loop, the loop will not execute even once. Because in ‘while’ loop, the
condition is checked before the code is executed. But in ‘do-while’ loop, first the code
is executed then the condition is checked. In above example the statement ‘X++’
increased the value of variable ’X’ by 1 (one) fist, then the condition is checked. The
value of variable ‘X’ becomes 16 (sixteen) before the condition is checked. When
condition is checked, the result is false, and loop breaks. So it is clear now, that, ‘do-
while’ loop execute the code once either the condition is true or false.
65

It also has 3 (three) parts of implementation, 1.initialization, 2.change in


value of variable used in condition, and 3.check condition.

‘for’ loop

This is the most commonly used loop in almost all programming languages.
Structure of this loop is exactly same in almost all leading programming languages
such as C/C++, Java, Flash MX ActionScript, PHP, and SWiSHScript etc.

It is assumed that, you can now implement ‘while’ and ‘do-while’ loop (we
discussed previously). Because we will take some reference from previous discussion
to understand ‘for’ loop.

In previous topics we divided the ‘while’ and do-while’ loops in 3 (three)


parts. Those 3 (three) part were:

1.Initialization
2.Condition
3.Change in value of variable used in condition

The same 3 (three) parts will be followed to implement a for loop, but jointly. Syntax
to implement ‘for’ loop is:

for( initialization ; condition ; change in value of variable) {


code to execute repeatedly
}

let us implement the example using ‘for’ loop; the example we used for ‘while’ loop:

Example we used for ‘while’ loop was:

X = 0;
while(X<5) {
trace(X);
X++;
}
66

if we implement it using ‘for’ loop, it will look like:

for( X=0; X<5; X++ ) {


trace(X);
}

for( keyword to start implementation of ‘for’ loop


X=0; initialize the variable (acting as counter) with
value 0 (zero)
X<5; check condition each time if value of variable ‘X’
is less than 5 (five), execute the code.
X++ increase the value of variable ‘X’ by 1 (one), after
condition has been checked
trace(X); built-in function to show flow of execution
} close the block created for ‘for’ loop

It has many uses. It is mostly used when you need to repeat/iterate a statement or
block up to specific number of times.

For example, I have to change value of variable ‘message’ 3 (three) times. Which
loop I must use? Answer is ‘for’ loop, because for loop is best when we now the
number of iterations. See code below:

for( I=1; I<=3; I++) {


message = “value of I is “ add I;
}

which will result as the change in value of variable ‘message’ 3 (three) times.
First time value of variable ‘message’ will be value of I is 1
Second time value of variable ‘message’ will be value of I is 2
Third time value of variable ‘message’ will be value of I is 3

Although this process will take less than a second and you won’t be able to see the values passing one by
one so fast (if you are displaying on screen).

Breaking loops Unconditionally

Some times our application’s need is, to break the loop even when the
condition is still true and loop can be continued repeating the execution of code. This
is called unconditional break of a loop. There a single way of doing this which can be
applied in all kind of loops in SWiSHScript.

To break a loop unconditionally, we use a keyword ‘break’ (which is not


function) but acts as function get into the internal structure of the loop. Within the
loop we call this functionality when we after checking some condition, see example:
67

for( I=0; I<1000; I++) {

as it is clear from the structure, the loop will repeat 1000 (one thousand) times. But
in following example we will break the loop when the value of variable ‘I’ is greater
than 10 (ten). How? See example:

for( I=0; I<1000; I++) {


if(I >10) if value of variable ‘I’ is greater than 10,
break; break current loop
}

Skipping the code in loops, Unconditionally

Opposite to the unconditional breaking of a loop, we also have a functionality


in SWiSHScript, to skip the execution of the code (in loop), on a specific condition.
Where can this be used? This can be used in applications like, you need to show only
the numbers divisible with 2 (two) within 1..100, and skip all others. See example:

for( I=1; I<=100; I++) {


if(I%2 != 0)
continue;
trace(I);
}

We used a new keyword ‘continue’ to skip the code ‘trace(I);’ to be executed,


unconditionally. Why do we call it unconditionally, when we are implementing
condition for it? Because we ordered the loop to skip it at certain point, if we did not
have done this, the loop had continued with each number and displayed all the
numbers in debugger (even if they are not divisible by 2 (two)).

Why not to make a loop increasing the value of counter variable ‘I’ by 2?

Yes the best way to implement the above example is, to increase value of variable ‘I’
by 2 (two), instead if 1 (one). So the iterations will lessen down and we can save the
execution time of the loop. Question is: how to do this.
Simply change the expression in last part of ‘for’ loop (the ‘I++’) which is increasing
the value of variable ‘I’ by 1 (one). So it becomes

for( I=2; I<=100; I+=2) {


trace(I);
}

‘I+=2’ is the short form of expression of ‘I=I+2’, which has already been discussed
in previous topics.
68

Tuning up code with ‘switch’ set statement

‘switch’ is also a powerful structure that is used in all most powerful


programming languages such as C/C++, Java, Flash MX ActionScript, SWiSHScript,
PHP etc. In most cases, it provides an ease to get rid of much more if-else
statements in your SWiSHScript code.

To understand ‘switch’ structure, first, we must implement an example of if-


lese chain of conditions. After it, we will translate the chain of if-else into switch. So
let us have our previous example of ‘car speed on road’ which was:

if( speed == 10 )
message = “You are too slow”;
else if( speed == 80 )
message = “Ideal Speed”;
else if( speed == 120 )
message = “Slow Down, it is dangerous”;

Better implementation and use of ‘switch’ is, when your application needs to keep
check on single variable (as it is in above example, variable ‘speed’). So after
converting the above example into ‘switch’ we get resulting code as:

switch( speed ) {
case 10:
message = “You are too slow”;
break;

case 80:
message = “Ideal Speed”;
break;

case 120:
message = “Slow Down, it is dangerous”;
}

switch( speed ) { keep check on value of variable ‘speed’


case 10: if value of variable ‘speed’ is 10 (ten)
message = “…….”; assign new value to variable ‘message’
break; do not check next case if condition is met.

For example, we want a statement to be executed when all the conditions become
false. As we did in if-else examples, we put an ‘else’ and joined new statement with
existing if-else chain. See below (one from the previous examples):
if( condition )
…….
else if( condition )
…….
else if( condition )
…….
else
message = “All above conditions were false”;
Now the green part of the above example has been implemented with ‘switch’ in
previous ‘switch’ example. Now we implement the last blue part of above example
69

within ‘switch’. Remember, when implementing ‘switch’ and you wish to put a
statement to be executed when all above go false, you will use keyword ‘default’
(not ‘else’, because ‘else’ is only for if blocks).

Some addition to ‘switch’ will be

default:
message = “All above conditions were false”;

Note: whenever you add new ‘case’ or ‘default’ (acts as else) to the ‘switch’, do not
forget to put break after all the previous cases.

So the final code becomes (after addition of ‘default’ in code):

switch( speed ) {
case 10:
message = “You are too slow”;
break;

case 80:
message = “Ideal Speed”;
break;

case 120:
message = “Slow Down, it is dangerous”;
break;

default:
message = “All above conditions were false”;
}

The newly added code is styled BOLD.

Structure ‘switch’ is very useful, when you have to concentrate on single variable
and you are sure of the expected values. In ‘switch’, you cannot use Comparison
Operators with ‘case’s’. It is not much flexible comparing the ‘if-else’ structure, but it
is best for small applications, where, your expected values are known.

Working with Functions

What is a function?

1. Function is a named routine in our code.


2. Function is set/combination of several executable statements
3. Function is set of statements to perform a specific piece of task.

Above are the 3 (three) simplest definitions of a function.


Why do we create our own functions?

When we need to execute several statements again and again, and we don’t want to
repeat the set of code; We create a block of code and name it, then we call this
70

routine/block by using its name and the whole set of statements are executed
(without putting all statements once again).

Creating your own Functions

We have seen many of the built-in functions we used within our SWiSHScript
code. Now it is time to create our own functions. Syntax for creating simple function:

function function_name () {
set of statements to execute
……
……
}

Using this way, the function may be defined anywhere in the code. But if we need to
define a function within an event handler (say onLoad()) or other function, we do it
different way:

onLoad () {
function_name = function () {
set of statements to execute
……
……
};
}

Remember: if you have any more initializations, or code after the function definition
within a handler or other function, you must put a semicolon on the end of closing
bracket (as shown above ‘};’).

Example:
We will write a new function, which will display (in SWiSHMax internal
debugger) all numbers divisible by 3 (three) between and 10.

function myFunction() {
for(I=1; I<=10; I++) {
if(I%3 == 0)
trace(I);
}
}

we create a new button in our movie


then we call this function in event on(release) of the button, as:

on(release) {
myFunction();
}
Note: we used name of the function ‘myFunction’ and ‘()’ brackets to call function.
And remember to run movie within SWiSHMax when testing with internal debugger.

You can open example file function1.swi and test it yourself.


So the code (within function) is executed, and results in debugger as like:
71

Click this button in example

This was the simple way of creating your own functions, now we move to a bit
advanced techniques involved in writing functions.

Writing functions that accept arguments (accepting parameters)

What are arguments/parameters of a function?

The values or variables passes in the ‘( )’ after function name are called its
arguments. For example, we have been using a function gotoAndPlay() in our
previous examples, which accepts one argument as the frame name or label. See
example:

gotoAndPlay(12);

‘12’ is the argument/parameter passed to function gotoAndPlay(). So we can say


this function accepts one argument. If any function accepts more than one
arguments, we separate them with comma ,. Such as:

duplicateSprite(“xyz” , 2);

this function accepts two arguments, in first argument we passed “xyz”, and 2 in
second one, and both are separated with , (comma).

In our first example of function creation, we wrote a function that did not accept any
argument/parameter, so we put empty brackets ‘()’ after the function name
‘myFunction’. Let us create a new function which will accept single argument. Our
new function ‘myFunc2’ will calculate its square and show in the debugger (using
trace()).
Syntax of a function accepting arguments:

function function_name (arg1 , arg2 , ……) {


}

Example:
72

following example is contained in file function2.swi.

function myFunc2(myNum) {
myNum *= myNum;
trace(myNum);
}

‘myNum’ is the variable which is processed within the function, and is visible only to
the function. But when we call this function we can pass value or another variable to
this function, which value will directly go into variable ‘myNum’ and processed by the
function.

on button action the code is

on(release) {
myFunc2(5);
}

The result in debugger is


Click this button

Creating functions which can return a value

In our previous examples of functions, we used to display the results (using


trace()) from within the functions. Now our requirements have been changed. We
want to write a function which will square the number passed to it (as argument),
and return the square back, so that we can store that square value in some other
variable. Here, we introduce you a new keyword ‘return’, which allows a function to
return value back to the caller.
73

Take previous example, and let us implement it different way, so that it can return
back value (we changed the function name as well).

Open file function3.swi, which contains:

function mySQR(myNum) {
myNum *= myNum;
return myNum;
}

on button action the script is


on(release) {
tempVar = mySQR(4);
trace(tempVar);
}

after running this example within SWiSHMax environment, the result is:
Click this button when you run it

tempVar = mySQR(4); create new variable ‘tempVar’ and put the


value returned from function ‘mySQR’ in
it.

trace(tempVar); display the value of variable ‘tempVar’ (in


debugger), the value returned from
function ‘mySQR’.

This method is very useful, when we need to distribute the statements among
several tasks (functions). Although there is already a function for having square (of a number) in
SWiSHScript, but our goal was to teach you to create your own functions of the same style. We will be
writing variety of functions/routines when we get into final chapters of this book. For
now, this is just a description to give you start.

String manipulation functions


74

In this topic, we will be discussing (shortly) some useful functions, which are
most commonly required to manipulate String data. Further String manipulation
functions will be discussed in later chapters (topic : other scripting objects).

Function and expression Usage Result

myStr = toUpperCase(“aBcd”); Converting all character to upper case ABCD


myStr = toLowerCase(“aBcd”); Converting all character to lower case abcd
myStr = trim(“ aBcd ”); Remove space characters in start and end aBcd
myLen = myStr.length; get length of a String 4
myArr = split(“aBcd”);
myArr = myStr.split(); split a string among Array a,B,c,d

Up to here, we have studied almost all of the Control structures of SWiSHScript.


Now, we will move to most commonly used object (sprite, button) and their common
properties and event handlers.

Button and Sprite Object properties and event handlers

Button Object properties

A button uses to have some properties which can be accessed through


SWiSHScript. Some of the properties are specifically for button object, and the rest
of the properties (we will discuss), are specific to the sprite object. Let us see the
some of the useful properties specific to the button object.

useHandCursor

‘useHandCursor’ property of a button object is of type Boolean (true/false).


this property is used to set the default had mouse cursor ON or OFF. A button object
has default mouse cursor as a small hand (when mouse cursor is over the button),
shown below:
75

If you set this property to false, the ‘hand’ mouse cursor is not shown when mouse is
over the button object, but the default mouse pointer will be used, as shown here:

Syntax to set the ‘hand’ mouse cursor OFF via SWiSHScript.

button_name.useHandCursor = false;

You must set a name for button object button before modifying its useHandCursor
property. When you create a new button or convert some shapes to button object in
SWiSHMax, you can see it is unnamed and by default is set to Button, as shown
below:

You must set its proper name from the property tabs shown here:

As I named it myBtn, so that it looks like

So you will use following SWiSHScript to set hand cursor OFF for the button object
myBtn:

myBtn.useHandCursor = false;

Setting it to true will turn back the default ‘hand’ cursor ON, as:

myBtn.useHandCursor = true;

enabled

This property is also of type Boolean. By assigning false to this property of a


button object, will result in, the button will not function anymore. Means, any action
to be taken/associated with button object, will not work anymore. Simply, by setting
it to false, means to disable the button object completely.

Syntax:

button_name.enabled = false;
76

So if you have named the button object as myBtn, use following SWiSHScript to
disable it.

myBtn.enabled = false;

and to re-enable it use (set property value to true):

myBtn.enabled = true;

This method is useful especially when you have to disable buttons, while processing.
E.g. a user fills out a contact form on your site and has submitted it once, and you
disable the submit button, so that, the user won’t be able to submit it again until
s/he gets next message to proceed, or the confirmation that, his message/mail has
been received successfully.

Button Object Event Handlers

The event handlers are somehow functions which are implemented by


scriptor. They are implemented for capturing specific events of the objects and
performing specific action on their occurrence. The button object is implemented for
user input, mostly users click the buttons to take action; Now the user can either
click the button using mouse, or use keyboard keys (if associated). It is our
(scriptor) duty to capture specific event and perform action on its occurrence. For
example, we have a button object named myBtn. Now, we want to track the if the
user takes mouse cursor over our button and presses the mouse button and releases
the key. How to track, if user has clicked the button? In your SWiSH movie select the
button object, go to script panel, and put following script in. See the code below, to
implement the event handler:

on(release) {
take_some_action
}

Now when the user presses mouse button over our button object, and releases the
it, ‘release’ event is automatically generated. So, as we have tracked it above, we
can take any action when event has been generated. Same to this one, you can even
track when user has pressed the mouse button but not yet release it ,by
implementing ‘press’ event handler as:

on(press) {
take_some_action
}
77

Some more event handlers can be implemented as:

rollOver when mouse cursor is rolling over the button object


rollOut when mouse cursor rolls out of the button object area
dragOver when mouse button is pressed and moving (not released)
dragOut when mouse button was pressed but taken out of button
boundary
releaseOutside when mouse button pressed and taken out of boundary and
released.

Implementing event handlers as functions

When you wish not to put/attach script directly to the button but implement it
outside (within some other event handler or normal function), you will do it as
(assume button object name is myBtn):

myBtn.onRelease = function() {
take_some_action
};

Above example is specifically when button has generated ‘release’ event. Similarly,
to implement other event handlers use:

Event Name Equivalent Event Handler

onPress on(press)
onRelease on(release)
onRollOver on(rollOver)
onRollOut on(rollOut)
onDragOver on(dragOver)
onDragOut on(dragOut)
onReleaseOutside on(releaseOutside)

These were all the mouse events which can be used to implement handlers.

Now we take a look at the event that is generated when a key (from keyboard) is
pressed.

on (keyPress("<Space>")) {
take_some_action
}

In this example an event “KeyPress()” has been generated by your movie when
Space “ “key is pressed from the keyboard. How to implement this handler with
other keys? If you switch you script panel to Guided mode (assumption: this event
handler is already in the code), you can choose from a list of keys as sown below:
78

These are 15 (fifteen) keys to capture, already available in SWiSH max script editor
event options.

In case, if you wish to use some other keys, which are not mentioned in the menu.
First implement an event handler ‘onKeyDown’ as new function for the object you
wish to listen when key is pressed. Then you will have to add a listener for the object
(on which key is pressed). The object may be _root (the root path of movie), any
button, sprite, etc. In following example of SWiSHScript we have implemented an
event handler ‘onKeyDown’ for _root (the root path of the movie), so, wherever the
key is pressed can be captured. And then we passed the _root object to a function
‘addListener()’ of the ‘Key’ built-in object. See following example code from key.swi:

onLoad() { implement onLoad event handler in _root


_root.onKeyDown = function() { implement onKeyDown event handler for
_root

code = Key.getCode(); Get Key code of the last key pressed and
assign it to variable ‘code’

};

Key.addListener(_root); Add new listener for _root to built-in


object ‘Key’ for the

Through this method you can capture ASCII value of any key pressed (by the user)
on the keyboard. This is useful in creating custom menus and/or games.
79

Second example is to listen the keys pressed on a button object. Following example
is implemented in btn_key.swi. See example below:

onLoad() { implement onLoad event handler in _root


myBtn.onKeyDown = function() { implement onKeyDown event handler for
button object ‘myBtn’
code = Key.getCode(); Get Key code of the last key pressed and
assign it to variable ‘code’
};
Key.addListener(myBtn); Add new listener for button object ‘myBtn’
to built-in object ‘Key’ for the
}

Above example will show the Code of the last key pressed (on keyboard) in the text
box. Now, the next example captures Up and DOWN key press, using the built-in
function ‘isDown’ of Key object. Where you have to pass it the key identifier.

onEnterFrame() {
if(Key.isDown(Key.UP)) {
_alpha +=10;
} else if (Key.isDown(Key.DOWN)) {
_alpha -=10;
}
}

And changes the alpha value of current movie. Note, here, we did not associate the
key capture with any object and did not add any new Listener. So this is the best
method to capture key strokes in SWiSHScript.

Key capture events can be implemented with both button or sprite objects equally.

Sprite Object properties

In this topic we will be discussing the only properties which are not available
for a button object, rest of the properties which are available for both (button and
sprite) objects, will be discussed in upcoming topics.

_currentFrame

This property ‘_currentFrame’ is used to get current frame of the sprite being
played. This may also be used to get frame number currently being played in any
other path or level.

Syntax:

myVar = mySpr._currentFrame;
80

Where ‘mySpr’ is a sprite, and number of its current frame (being played) is
assigned to variable ‘myVar’. You can also get currently being played frame of the
main movie (_root), as:

myVar = _root._currentFrame;

Use same method to get frame number from higher levels, as:

myVar = _level2._currentFrame;

_totalFrames

This property ‘_totalFrames’ returns the total number of frames in a sprite,


path, or level. Syntax for using this property is as simple as the previously discussed
property, see example:

myVar = mySpr._totalFrames;

So, the variable ‘myVar’ is assigned the number of total frames in sprite ‘mySpr’.

_framesLoaded

property ‘_framesLoaded’ the number of frames loaded upto now. This can be
used to get number of loaded movie frames from any path or sprite.

Example:

myVar = mySpr._framesLoaded;

or

myVar = _level2._framesLoaded;

Note: both of the properties (_currentFrame, _totalFrames) are of integer type. So


the value obtained from these properties, must be treated as integer value. And both
are read-only properties which means, they cannot be assigned value, but, values
can be obtained from them.
81

Properties that are available for both Sprite and Button Object

Let use put some light on physical properties of both button and sprite
objects.
_x get/set X coordinates of the object
_y get/set Y coordinates of the object
_width get/set Width of the object
_height get/set Height of the object
_alpha get/set Alpha/Opacity/Transparency of the object (minimum 0,
maximum 100)
_rotation get/set rotation (rotate) angle of the object (0..360).

Frequently used functions available for sprites/movie control

play()

Play a specific sprite, from frame currently stopped at. Syntax as follows:

sprite_name.play();

To play main movie (_root) or any level, use:

_root.play();
_level2.play();

stop()

Stop the sprite, _root, or any level playing the timeline. Follow the syntax as below:

sprite_name.stop();

To stop main movie (_root) or any level, use:

_root.stop();
_level2.stop();

gotoAndPlay()

This function is used to go to a specific frame and play it.

Syntax:

sprite_name.gotoAndPlay(15);

Where 15 (fifteen) is the frame number of sprite ‘sprite_name’. Play main movie or
level the same way:

_root.gotoAndPlay(15);
_level2.gotoAndPlay(15);
82

This may also work with labels.

Labels: Labels are used to identify the frames of any path timeline with names. For
example we wish to set a label on frame 10 (ten), we use setLablel() function, see
example:

onFrame(10) {
setLable(“some_label”);
}
83

so you can jump to a labeled frame via function gotoAndPlay(), passing it the label
name instead of frame number as:

sprite_name.gotoAndPlay(“some_label”);
_root.gotoAndPlay(“some_label”);
_level2.gotoAndPlay(“some_label”);

gotoAndStop()

This function is used to go to a specific frame and stop the sprite, level, or
_root (main movie).

Syntax:

sprite_name.gotoAndStop(15);
Where 15 (fifteen) is the frame number of sprite ‘sprite_name’. Stop main movie or
level the same way:

_root.gotoAndStop(15);
_level2.gotoAndStop(15);

and to jump to a labeled frame and stop, use:

sprite_name.gotoAndStop(“some_label”);
_root.gotoAndStop(“some_label”);
_level2.gotoAndStop(“some_label”);

Some additional functions for movie control

These are the functions specific to the SWiSHScript only (not Flash MX
ActionScript). Here is a short description to these functions, which are an extension
to existing movie control functions in SWiSHScript:

nextFrameAndPlay() Go to next Frame of any sprite/path and play


nextFrameAndStop() Go to next Frame of any sprite/path and stop

prevFrameAndPlay() Go to previous Frame of any sprite/path and play


prevFrameAndStop() Go to previous Frame of any sprite/path and stop

nextSceneAndPlay() Go to next Scene (of movie) and play


nextSceneAndStop() Go to next Scene (of movie) and stop

prevSceneAndPlay() Go to previous Scene (of movie) and play


prevSceneAndStop() Go to previous Scene (of movie) and stop
84

Event Handlers for Sprite Object and Main Movie ‘_root’

onFrame()

This is most frequently used event handler in SWiSHScript. It is used to


implement a specific piece of code to be executed when a specific frame of a sprite /
main movie is played. Syntax:

onFrame(15) {
take_some_action
}

‘15’ is the number of frame of specific path, where we have to execute some
SWiSHScript instructions.

This event handler must be implemented within the timeline of specific object it
relates to. E.g. if it is required to be implemented for a specific sprite, then it must
be put in the timeline of the sprite. Similarly, if it is to be used in main movie
(_root), it must be in main timeline.

You can implement this event handler repeatedly for separate frames in the same
Script Panel area. This feature is not available in Flash MX ActionScript Editor; In
Flash MX all frames’ actions cannot be put within one script area, you have to write
code for each frame separately. So, this is a big advantage in SWiSHMax.

onLoad()

This event invoked/fired/generated when a Sprite or _root is started loading


by the Flash Player. So this may be used as a Constructor in C++ class, to do initializations. This
event handler is usually implemented when we need to do initializations in the sprite
or main movie. example may be of creating / defining new variables and assigning
them initial value, defining custom functions. Simple example:

onLoad() {
myVar = 0;
}

We put this script in the main timeline, so a new variable is defined ‘myVar’ in _root
and its initial value is 0 (zero). If we copy the same script and paste in the script
panel of a sprite ‘mySpr’, the variable ‘myVar’ will be defined in that sprite, and
variable will become local to that sprite (means, not visible outside if used without
prefix path to sprite).

I want to implement onLoad() event handler for a sprite within the onLoad() event
handler of main movie, how would I do that?
85

Very Simple! We already have studied defining functions within other event handlers,
so do the following (implement the onLoad() event handler of sprite ‘mySpr’ as
function in main movie’s onLoad() event handler):

Remember: following script is in the main timeline of the movie.

onLoad() { onLoad() event handler of main movie


mySpr.onLoad = function() { onLoad() event handler of sprite ‘mySpr’
myVar = 0; initialize variable of sprite ‘mySpr’
};
}

onEnterFrame()

I don’t want you to mess with this event handler name ‘onEnterFrame’. Just
remember this line of text I am to quote here, “This is an event generated/
invoked/fired all the time, the movie is playing, so take it as an internal loop which
iterates all the time”. Whatever code you put in it, is executed all the time, the
movie/sprite is playing. This event handler can be implemented for every Sprite and
Main Movie individually. By the Way: putting huge set of code in it will cause your movie slow down
even if frame rate is set higher.

Syntax:
Note: this is for main timeline.

onEnterFrame() {
myVar = mySpr._currentFrame;
}

When this example is ran, it will change the value of variable ‘myVar’ all the time
and assign it value of the current frame (being played) of sprite ‘mySpr’. Use the
same way to implement for any sprite.

Now if you wish top implement this event handler for some sprite ‘mySpr’ within the
main timeline, implement it as function and within the onLoad() event handler of the
main movie, as:

onLoad() {
mySpr.onEnterFrame() {
myTxt = _currentFrame;
};
}
86

My first SWiSHScript application

Please open file 001.swi before you continue reading.


This file contains 4 (four) objects, Static Text, Dynamic Text, Input Text, and a
Button Object. This simple application demonstrates how to assign a value to a
dynamic text Object. In this example, user will enter his/her name in the Input Text
Object and that name value will be displayed in Dynamic Text Object by adding
‘Hello’ as prefix.

Script for the button object

on(press) {
myVar = "Hello " + myVar2;
}
87

Understanding Levels

Levels work as hard layers on the main movie ground. When you first time run an
SWF movies that are loaded in level 0 by default. That means your movie is running
on the ground level. See the following fig to make it clearer:

Movies loaded in higher levels physically appear just over the level 0 movie, means
that a new layer is created for the higher level and that new layer comes on the top
of existing level layers. We can also load external movies in sprites and place the
sprite on specific area (x, y coordinates) of movie.

Function loadMovie() is used to load and external SWF or JPEG file within sprites.
Syntax is as under

How to load an external Movie in Sprite?

Please open file 002.swi before you continue reading.


onFrame(1) {
mysprite.loadMovie(“external1.swf”);
}

In above example we are loading ‘external1.swf’ file in our sprite called ‘mysprite’.

Let us get back to the point (loading external movies in higher levels)

How to load an external Movie in Higher Levels?

Please open file 003.swi before you continue reading.


This time we are loading the same ‘external1.swf’ in Level 1, the code would be

onFrame (1) {
loadMovieNum("external1.swf",0);
}
88

Remember: If you load an external movie in Level 0, that will replace the actual
movie already in Level 0. So preventing from this conflict, always load movies in
higher levels, higher than 0 (ZERO). Now question appears that

Now question is, How to control movies loaded in levels higher than 0?

(Level 1+)
For example, to give action gotoAndPlay(10); to movie loaded in level 1, you will
have to target the path first, or use _levelN prefix path before function (where N is
level number), e.g.

on(press) {
_level1.gotoAndPlay(10);
}

Targeting the path and then using function or putting some expression
on(press) {
tellTarget(_level1) {
gotoAndPlay(10);
}
}
or
on(press) {
tellTarget(_level1) {
someVarInLevel1 =”some value”;
}
}

Function tellTarget() may also be used to target some sprite. e.g.


on(press) {
tellTarget(sprite_name) {
someVarInSprite =”some value”;
}
}

For unloading/removing movies loaded in higher levels, use function


unloadMovieNum(N), (where N is level number) e.g.

Open sample file 004.swi


on(press) {
unloadMovieNum(1);
}

Same for unloading/removing movies loaded within sprites, use function


sprite_name.unloadMovie(),e.g.

Open sample file 005.swi (use sprite name as prefix – target path)
on(press) {
mysprite.unloadMovie();
}
Similarly, if you want to load in level 2, you will use _level2.
89

_root, _parent, this, and _global

_root, _parent, this, _global may be called pointer objects to the paths. These
objects enable you to point some path directly, such as parent movie, main movie
timeline, or current movie, by using them as prefix while calling function, or using
some valid expression. In SWiSHMax, the variables always have a path, where they
have been defined/created. And they are not visible to other paths/objects in movie
directly.

Variables Scope in SWiSHScript

For example if we have defined a variable as x=15; on first frame of the movie (in
main timeline), all the scripts of main timeline (either on frames or even buttons'
action), will be using variable 'x' directly. E.g.

x=x+10;
or
x+=10;

_root

Using _root object we can point the variables/sprites/text objects/buttons of


main timeline directly. See 006.swi, contains following code (on button event):

on(press) {
_root.myVar = "This is new Value";
}

_parent

Using _parent object we can point any variables/sprites/text objects/buttons


in parent path (which may be a sprite or _root). E.g. we have a sprite called ‘a’,
which contains further sub sprite called ‘b’ (means ‘b’ is within ‘a’, and ‘a’ is within
_root). Now the following script is in sprite ‘b’, which is assigning a value to variable
‘v’ in its parent sprite ‘a’, Open 007.swi to see the following code.

onFrame(1) {
_parent.v = "parent accessed";
}

Following screenshot will make clear it to you:


90

Or open 008.swi where we have accessed the variable ‘v’ of parent sprite ‘a’ (being
within sprite ‘b’), via a button.
onFrame(1) {
_parent.v = "parent accessed";
}

Screenshot of 008.swi making it more clear:

E.g. Targeting a variable ‘y’ defined in sprite ‘a’ contained in root. What should we do
if we want to point it directly? is; We will access the variable like this
'_root.mysprite.y'. And if it is in higher level (level 1) then, ‘_level1.mysprite.y’.

this

Object this refers to current sprite, and acts differently than _parent and
_root objects. It refer to variables/text objects/sprites objects/button objects
defined/created in current path. It is used, especially when we need to load or send
variables from out-resources (may be a PHP/ASP/PERL script) to SWiSHMax, to
prevent response-back values going into another path.

E.g. this.loadVariables("script.php", 'GET');


91

In above example the script.php will be receiving the variables (of current path) via
get method; and if script.php responses back, all variables will be received in current
path. By the way function loadVariables() will be started discussed in chapter 3, topic
1. It is actually not necessary to use object this, all the time. But it is better
approach to use object this to make the code more readable and understandable,
that all the object/variables/functions followed by keyword this are of current path.

Why use _root, _parent, or this?

Very simple and comprehensive answer; Using paths with variables or objects
is a good programming approach, which prevents/eliminates the chances ambiguity
between two/more variables of same name defined in different paths.

_global

Object _global may be called the most powerful object in path objects
category. Object _global is used to define globally accessible variables, functions,
etc; Means, all the variables/functions defined with this prefix are accessible
anywhere in the movie without any prefix path. Such as:

_global.myVar = 786; a new variable ‘myVar’ has been created


an global variable and has been assigned
a new integer value of 786.

Now variable ‘myVar’ can be accessed / modified from anywhere in the movie. e.g. If
your script is in a sprite and you wish to get value from variable ‘myVar’, you do not
need to use any prefix path to access it, such as:

varInSprite = myVar; assumed local variable ‘varInSprite’ in any


sprite is assigned value of global variable
‘myVar’ directly without any prefix path,
such as _parent.myVar.

or

myVar++; increase value of global variable by 1


(one).

Use of ‘tellTarget’

Traditional way (followed from flash 4 up to now) of targeting specific path


and then accessing its properties/variables/sub objects/functions/etc directly without
any prefix path, is using ‘tellTarget’ control structure. Example:
tellTarget(_root.mySprite) {
spriteVar = 1;
gotoAndPlay(“lable2”);
}
92

structure of ‘tellTarget’ is very simple to understand, “target a path/sprite/level and


use its inner things”.

Explanation:

tellTarget(_root.mySprite) { Target/Get into sprite ‘mySprite’ created


in main timeline ‘_root’.

spriteVar = 1; Assign value 1 (one) to variable ‘spriteVar’


defined in the sprite we targeted
‘mySprite’.

gotoAndPlay(“lable2”); Jump to Labeled frame ‘label2’ in sprite


we targeted and play the sprite.
}

Note : ‘tellTarget’ is used only to point paths/levels not variables or scripting objects.

Why not to use this way directly as following?

_root.mySprite.spriteVar = 1;
_root.mySprite.gotoAndPlay(”lable2”);

Answer:

As I already mentioned that, ‘tellTarget’ is the traditional way not compulsory/only


way, so it is not compulsory to use it, you may use any of the ways seems easy to
you. But I will follow direct method and not using ‘tellTarget’ structure anymore in
next upcoming examples and topics. It is being discussed here, just to give you idea
of almost complete control structures dictionary of SWiSHScript.

You can also jump to higher levels _level1, _level2, etc using ‘tellTarget’ as:

tellTarget(_level2) {
take_some_action
}
93

Use of ‘with’

Structure of ‘with’ is not much different from ‘tellTarget’ but, it has extensive
usage. Structure ‘with’ enables your script to access inner properties / functions /
variables of even scripting objects as well as sprites/other paths.

Use of ‘with’ with text object

with(myTxtObj) { point the text object ‘myTxtObj’ to access


its properties.
_text = “I am vale of myTxtObj”; assigning value of property ‘_text’ of text
object ‘myTxtObj’ (used in ‘with’
structure).
}

Use of ‘with’ with sprite object (path pointing object)

with(mySprite) { point the sprite object ‘mySprite’ to access


its properties and functions.
gotoAndPlay(“lable2”); go to labeled frame ‘lable2’ of sprite
‘mySprite’ and play it.
}

or

with(mySprite) { point the text object ‘mySprite’ to access


its properties and functions.
spriteVar = 786; assign a new integer value to the variable
‘spriteVar’ defined in as local variable of
sprite ‘mySprite’.
}

Dragging the objects at runtime

There are 3 (three) basic functions of SWiSHScript to control a runtime drag of the
objects through mouse click of user.

startDragUnlocked

function startDragUnlocked allows you to clip the dragable object from any point
(through mouse). See example file drag1.swi. See code on button in sprite.

startDragUnlocked with constraints:

If same function ‘startDragUnlocked’ is passed the boundary of the drag area it


makes the object dragable within specified boundary. See example file drag2.swi.
See code on button in sprite.

this.startDragUnlocked(0,100,0,100);
Where 1st argument is left X, 2nd 100 maximum right, 3rd 0 top Y, and last 4th
argument is 100 maximum bottom.
94

startDragLocked

allows the user to drag the object only from the anchor point. E.g. if the sprite is top-
left it will drag it from 0,0 top-left and if anchor point is origin it will drag from center
(the origin) 0,0.

You may also set constraints for this functions by passing it four integer arguments
that we used in previous example. But my personal observation is, users do not like
the Locked dragging because the object is automatically repositioned when drag is
started, so it looks a bit jerky in start.

stopDrag

Stop the dragging, it is the single function to stop any type of dragging being
performed.
95

Chapter 3

TEXT/JPEG File Management with


SWiSH MAX

ƒ Loading data from Text Files, loading external JPEG files


ƒ Creating static Address Book with images (without PHP)
96

Loading data from Text Files, loading external JPEG files

This technique may be used on web as well as on local computer (without


using PHP). For example you are developing a huge presentation; you want its text
be loaded from text files and then process it according to the presentation needs.
What will you do? You will maintain many text files and put text data in them.

What is the proper way of putting data in text files (to be loaded by SWiSH movie) ?

We put data in text files, in a specific way allowed by FlashPlayer. E.g. you have a
text file named ‘data.txt’ which will be containing ‘This is text in from data.txt’. And
when you load data from SWiSH movie the data will go in variable ‘myVar’. For this
you will be arranging data in text file as shown below:

&myVar=This is text in from data.txt&

Note: Remember to use character ‘&’ before and after assignment.

Open 009.swi before you continue, which contains one Dynamic Text Object named
myObj and its variable is ’myVar’, and a button which contains following code:

on(press) {
this.loadVariables("data.txt");
}

this current path


loadVariables(); function used to communicate a script file or load data from
text file (its communication with scripts will be discussed in
chapter 4)

When button is clicked in above example 009.swi, it loads the text file and change
the value of myVar in movie (try it).

How does my movie load multiple variables from single text file?

Very Simple! Open example file 010.swi, you will see 3 (three) different Text
Objects in it; their variables are ‘myName’, ‘myAge’, ‘myEmail’. This example loads
data from text file ‘data2.txt’, which contains:

&myName=Ali Imran&
&myAge=27&
&myEmail=news@swish-db.com&

Each Variable assigned a value on separate line.

Loading external JPEG files


97

We use the same of for loading external JPEG/JPG (picture) files, as we used
to load external SWF files. I would not prefer you to load external files in higher
levels, instead, load them in sprites; Because you can easily adjust place and size of
a sprite within the main movie, for this you will be using function loadMovie(). And if
you prefer use higher movie levels to load external SWF or JPEG, you will have to
adjust x, y coordinates in each and every SWI file separately.

How to load external JPEG/JPG picture file, in sprite?

Open 010.swi that contains a sprite named ‘jpg_loader’ and a button, which
performs action when clicked. Action on button is as follows:

on(press) {
jpg_loader.loadMovie("external1.jpg");
}

How to align loaded JPEG file within sprite (e.g. left aligned)?

Open 011.swi and see the structure of sprite ‘jpg_loader’, which contains a
rectangular shape in it. That shape is aligned Top-Left (set from transform properties
tab) and is put on 0 (zero) as x, 0 (zero) as y, which means the JPEG’s (to be
loaded) x, and y coordinates will be, where shape is placed.

Furthermore, if you want not to show the inner shape of sprite ‘jpg_loader’, then set
its Opacity/Alpha to 0 (zero) or Transparent, from Tint property Tab, as in example
file 012.swi.

Now I move forward with a huge hope that you have learnt techniques in
previous chapters, perfectly. At this point we will be creating a static Address Book,
which data will be alter/modifiable from a text file. So let us get a go.

Creating static Address Book with images (without PHP)

At this point when we have not yet started learning PHP yet, we will be using
plane text files to retrieve data from.

Open 013.swi, which contains 4 (four) Dynamic Text Objects, for Name,
Email, Address, and Phone number; and their variables are ‘myName_v’,
‘myEmail_v’, ‘myAddress_v’, and ‘myPhone_v’, a sprite named ‘myPhoto’ (where JPG
image will be loaded), and two buttons to go to next and previous entry in the
Address Book. The best way of doing all this is to use ‘Dynamic variables’ and
evaluation (use of eval() function), but as we are not yet familiar with this, we
continue with direct method.
98

For ‘_myAddressObj’, we have used multiline Dynamic Text Object.

How to make a Dynamic Text Object multiline?

Make a Dynamic Text Object (as demonstrated before), and select ‘Dimensions’ from
drop down menu (just below the color picker) in Text property Tab, as shown below:

Then, click button (button must look normal not pressed) Auto-size height, as shown
below:

After doing all this, come to Layout Panel, you will see a small change in Address
Text Object, as shown below:

Click the green dot at bottom-right corner of Text Object and stretch it down up to
desired Text Box size, so it looks like this:
99

Preview of the Address Book

By the way if you wish to load html in the Dynamic Text Object, select Formatting
options and click the Render text as HTML; it will enable your Text Object to accept
HTML tags loaded from text file. See the screenshot below:

Date in our text file ’data2.txt’ is

&myName=Ali Imran&
&myEmail=news@swish-db.com&
&myAddress=Islamabad, Pakistan&
&myPhone=not available&
&myphoto=contact1.jpg&

&myName2=Ali Roman&
&myEmail2=admin@swish-db.com&
&myAddress2=Taunsa, Pakistan&
&myPhone2=PPPPPPPPPPP&
&myphoto2=contact2.jpg&

&myName3=James&
&myEmail3=news@swishzone.com&
100

&myAddress3=SWiSHZone pty, ltd. Australia&


&myPhone3=OBTAIN FROM SITE 123&
&myphoto3=contact3.jpg&

&done=1&

We receive following variables (in SWiSH movie) when ’data.txt’ is loaded:


myName, myEmail, myAddress, myPhone, myPhoto, myName2, myEmail2,
myAddress2, myPhone2, myPhoto2, myName3, myEmail3, myAddress3, myPhone3,
myPhoto3, and done. Variable ‘done’ has already been defined, but rests of the
variables do not exist in our SWiSH movie previously. As we know that these
variables exist in the text file, so we will 100% be sure that we have received them
in our movie, after loading the text file.

Defining the code in 013.swi in main timeline:

onLoad() {
this.loadVariables("data2.txt");
current=1;
done=0;
}

What is onLoad()?

It is an event handler (or event procedure/function), that runs automatically when a


movie starts loading. So whatever code you put in this hander, will execute when
movie is run. This handler can also be put/attached with sprites, to execute some
instructions immediately when a sprite is loaded in FlashPlayer.

So we put onLoad() event handler in our main timeline, and put 3 lines of code as:

this.loadVariables(“data2.txt”) load variables from data2.txt in current path


which is _root (main movie timeline)

current=1; define a new variable, to check current entry

done=0; simple variable but working as flag, tells either to


process entry or not. It is initially set to 0 (zero),
because we do not want following code to
execute while text file is being loaded.

When we go forward reading the code we find:


onEnterFrame() {
if(done==1) {
if(current == 1) {
myPhoto.loadMovie(myPhoto);
myName_v = myName;
101

myEmail_v = myEmail;
myAddress_v = myAddress;
myPhone_v = myPhone;
} else if(current == 2) {
myPhoto.loadMovie(myPhoto2);
myName_v = myName2;
myEmail_v = myEmail2;
myAddress_v = myAddress2;
myPhone_v = myPhone2;
} else if(current == 3) {
myPhoto.loadMovie(myPhoto3);
myName_v = myName3;
myEmail_v = myEmail3;
myAddress_v = myAddress3;
myPhone_v = myPhone3;
}
done=0;
}
}

What is onEnterFrame()?

It is also an event handler. This event handler may also be put/attached with sprites.
It runs (the code it contains,) continuously in the path it is defined. In simple words,
“it is a loop automatically created (when you write its code), which iterates your code
all the time (either in _root or sprite)”. It is very useful when we need to keep check
on some variables, changed oftenly in the movie, such as variable ‘done’ we have
used.

if(done==1) a conditional block which executes when value of variable


‘done’ is 1 (one)

if(current == 1) When variable ‘done’ is 1 (one), it means we have to process


entry number ‘current’ (which is 1 (one) by default), and then
we check the variable ‘current’, 3 (three) times. After the
condition is met and ‘current’ is 1 (one), we put newly received
variables’ values in Text Objects, and loaded image for the
contact in a sprite named ‘myPhoto’, as shown below:
myPhoto.loadMovie(myPhoto);
myName_v = myName;
myEmail_v = myEmail;
myAddress_v = myAddress;
myPhone_v = myPhone;

done=0; You would be thinking why did we set done to 0 (zero) once
again. Answer is so simple, “we set done to 0 (zero), so that
event handler onEnterFrame() will not process entry until done
is set back to 1 (one)”.

Buttons’ Actions defined:


102

Button used for next entry named ‘next’

on(release) {
if(current < 3) {
current++;
done=1;
}
}

if(current < 3) check variable ‘current’ if it is already on last entry. If it is not


then,
current++ increase value of ‘current’ by 1 (one).
done=1 Tell the event handler onEnterFrame() to process next entry.

Button used for previous entry named ‘prev’

on(release) {
if(current > 1) {
current--;
done=1;
}
}

if(current > 1) check variable ‘current’ if it is already on first entry, and cannot
move back. If it is not then,
current-- decrease value of ‘current’ by 1 (one).
done=1 Tell the event handler onEnterFrame() to process previous
entry.

Two more objects Info_Area and Background are only to draw layout of our Address
Book.
103

Chapter 4

Interaction with PHP

ƒ Sending data to PHP script


ƒ Receiving data from PHP script
ƒ My first text echo application
ƒ Creating e-mail Contact Form, mail in PHP
ƒ Writing Text Files
ƒ Reading Text Files
ƒ Introducing loadVars Object and its reliability
ƒ Sprite Duplication and accessing duplicated sprite’s properties
ƒ Arrays in SWiSHScript, more flexible and powerful than in ActionScript
104

Sending data to PHP script

I hope you remember the function loadVariables(), we have already studied.


In previous (chapters’) examples we have used function loadVariables() without any
http method (we passed it only one argument such as loadVariables(“data.txt”)).
Any server-end script (such as PHP) uses to receive data via two methods, GET and
POST. On most Unix/Linux servers (where PHP is available), globals are set on.
Which means the received data may be via any method, the severs-side script
receives the sent variables as its own variables, so in our upcoming examples we will
be writing code in a view that globals have been set ‘on’ on the server.

How to add HTTP method as argument to function loadVariables(), if my server does


not allow globals?

Send variables via POST method:


Path.loadVaribles(“script.php”, ”POST”);

Send variables via GET method:


Path.loadVaribles(“script.php”, ”GET”);

Where Path may be ‘this’ (current path), or any sprite.

This was the method to send data variables to server-side scripts (to process).

Receiving data from PHP script

Same function loadVariables() is used to send and receive data variables


to/from a PHP script. Then why we have split this information among two topics of
this chapter? Only because, at this point we will be demonstrating the way of
sending variables from PHP back to SWiSH movie; For doing this, we must learn
some basics of PHP.

Quick Tips for PHP basics (we need to know before we continue):

PHP code starts with <? and ends with ?> (in ASP enclosures are <% and %>).
Some functions such as print, echo, and printf are used to send data back to client
application (client application can be a browser, FlashPlayer, or any other ActiveX).
As I use echo function most frequently, I will be moving using this function.

Syntax of function echo in PHP (Simplest example script001.php)

<?
echo “&myVar=This is text sent from PHP&”;
?>

Explanation:
105

This simple script (script001.php) will send a value ‘This is text sent from PHP’ to the
SWiSH movie (when it is called using loadVariables() function in SWiSH MAX), in
variable ‘myVar’, which may further be processed in SWiSH movie.

My first text echo application

In this topic we will demonstrate, how to create a small application sending a


variable data to PHP script (script002.php), then send back the same data as
different variable to SWiSH MAX Movie (from PHP). Open 014.swi and have a look.

This SWiSH file contains 4 objects in it; a Static Text Object, a Dynamic Text
Object, an Input Text Object, and a button. The Static is only to label the input text
object. The input text object (named myObj) has variable myVar. And the Dynamic
Text Object (named myObj2) has variable myVar2.

In button’s press event handler we have code as below:


on(press) {
this.loadVariables("script002.php", 'POST');
}

this.loadVariables("script002.php" Sending all the data variables (available in


current path) to the PHP script
(script002.php).

'POST' Send data via POST method

After the PHP script (script002.php) has received the variable myVar, it sends back
some data as in following code:

<?
echo "&myVar2=Hello $myVar from PHP&";
?>

&myVar2= Send response back to SWiSH movie


in variable myVar2

$myVar is the PHP variable we sent from


SWiSH Movie.

Note: PHP variable ‘$myVar’ is within double quotes “ and “. Which means variables
are even within (/or not within) quotes, are visible. So the data contained in
‘$myVar’ is sent to SWiSH movie, by adding a word ‘Hello’ before it and ‘from PHP’
after it.
106

When you test this application, it will generate results as shown below:

Now please upload the 014.swf and script002.php on some PHP enabled server and
run 014.swf via typing its complete URL in browser (hint: try different name each
time). You may also text it on local computer, if you already have installed PHP on
localhost.

Creating E-Mail Contact Form, mail in PHP

This is the most wanted resource all over the net. Most of the people search for such
forms where users (or their clients) can contact them via a simple form; you want
users to fill out the form and send it, and after they send, an email be sent to you.
Believe me, it is the easiest application to implement under PHP and SWiSH MAX.
Because, what you have to do is only create a Mail form (in SWiSH MAX) with
required fields, and use function loadVariables() (in SWiSH MAX) to pass on the
information to PHP. Where PHP will be using built-in mail() function to send email
directly to your (or you company) email address. THEN WHY NOT TO IMPLEMENT
OUR OWN FORM? Because our major goal is to learn, not to copy.

Open 015.swi, before you continue further.


This file contains total 10 (ten) objects, 4 (four) Static Text Objects to Show Caption,
4 (four) Input Objects _myName, _myEmail, _mySubject, _myMessage (their
variables myName, myEmail, mySubject, myMessage), a Dynamic Text object
_response (variable response), and a simple Button.

In button’s event handler (release), we have following code:


on(release) {
this.loadVariables("script003.php", 'POST');
}

this.loadVariables("script003.php", 'POST'); Send all the variables (in current


SWiSH MAX movie) to PHP script
(script003.php).
107

Now, data variables have been dispatched to PHP script (script003.php), let us see
how the PHP script processes the received variables, and processes it. For doing this,
first, let us study code in script003.php, as shown below:

<?
$recipient_email = "webmaster@somesite.com";

mail($recipient_email, $mySubject, $myMessage, $myEmail);

echo "&response=Mr/Miss.$myName, Your Mail has been sent&";


?>

$recipient_email = Change webmaster@somesite.com to email address


where you will receive users’ emails

mail( built-in function of PHP, through which you can send


emails directly

$mySubject, Variables received from SWiSH Movie


$myMessage,
$myEmail

Further, if you want the sender’s name be displayed instead of his/her email address
(in from portion of email), then load script004.php which contains following code:

<?
$recipient_email = "webmaster@somesite.com";
$from = "From: ‘$myName’ <$myEmail>";

mail($recipient_email, $mySubject, $myMessage, $from);

echo "&response=Mr/Miss.$myName, Your Mail has been sent&";


?>

That was all for creating your E-Mail contact form, and sending mail through PHP.

Writing Text Files

Before you continue, make sure that the server folder (where you upload
upcoming scripts) allows your script to write new files. Which means, the folder
permissions are set appropriately. You may use some good FTP program to change
folder permissions. For allowing folder to write new files chmod it to 777.

To make sure the folder permissions are set accurate, upload PHP script file
script005.php on server and run it via browser (by typing its complete URL). If you
find a new file called script005.txt (after running script005.php), that means folder
permissions are ok.
108

Now open script006.php, to learn accurate code (first) for writing text files in PHP.
This file contains following code:

<?

$f = fopen("myTextFile.txt","w");

$myText = "This is my Text";

fwrite($f,$myText);

fclose($f);

?>

Filing in PHP is almost same to the filing in traditional C Language.

$f = fopen("myTextFile.txt" Open new file ‘myTextFile.txt’ and keep a


variable $f for pointing it

"w" Create new file, if already existing,


overwrite it

$myText = "This is my Text"; define new variable $myText and assign


some string value to it

fwrite($f, $myText); Write data of $myText into file ($f is


pointing variable)

fclose($f); Close the file we opened/created to


read/write ($f is pointing variable).

Upload script006.php on server and run it. After running this PHP script, logon to
your FTP and see, there will be a new file myTextFile.txt in the folder, from where
you ran the script. So this was the procedure to write a Text file via PHP.

Reading Text Files

We already have read the Text files through SWiSH MAX movie directly. When
you have practiced much with reading directly, and writing text files, let us move
towards reading Text files via PHP.
109

Now open script007.php, to learn PHP code fist (for reading text files and
response back to SWiSH Movie). In following example PHP code, we will read the file
we created in previous example. Let’s see the code:

<?

$f = fopen("myTextFile.txt","r");

$filesize = filesize("myTextFile.txt");

$data = fread($f, $filesize);

fclose($f);

echo $data;

?>

Details

$f = fopen("myTextFile.txt" Open new file ‘myTextFile.txt’ and keep a


variable $f for pointing it

"r" Open file for reading purpose only

$filesize = filesize("myTextFile.txt"); define new variable $myText and assign


file size (in bytes) to it

$data = fread($f, $filesize); Read data from file ($f is file pointing
variable), $filesize (total file size)
characters, and put the read data in
variable $data

fclose($f); Close the file we opened to read ($f is


pointing variable).

echo “&myData=$data&”; Send the data contained in variable $data


to client movie. myData is variable in
016.swi
For instance, variables of PHP directly
work within double quotes, as variable
$data is enclosed in “ and “.

If you upload and upload this example ‘script007.php’ on server and run it,
you will see an output (in browser), like:

Output

&myData=This is my Text&
110

Now let us receive data via our SWiSH MAX Movie, we will have to create a
Dynamic Text Object in our movie and set its target variable, suppose we set the
target variable ‘myData’. Open 016.swi to see that contains a single Dynamic Text
Object _myData with variable myData; and code on first frame as

onFrame (1) {
loadVariables("script007.php");
stop();
}

Function loadVariables() has already been discussed in Chapter 3.


This file is used to receive data from script007.php. The File 016.swi must be
exported to SWF, first and then the SWF file must be uploaded in the same folder
and ran. The 016.swf will display output as ‘This is my Text’ in Text Box, s shown
below:

Introducing loadVars Object and its reliability

loadVars is a scripting object available in SWiSHScript as well as in Flash


ActionScript. Object ‘loadVars’ has a bit different use but it is more reliable than the
generally used function ‘loadVariables()’. Object ‘loadVars’ has 2 (two) separate
methods to send and retrieve/load variables data to/from target script or simple text
files. Whereas, the function ‘loadVaribles()’ is used for both loading/retrieving or
sending data variables to a script. loadVars object also allows us to check the total
and loaded bytes of the target script/file/result, as well as using this ‘loadVars’ object
we can know if any error occurred while requesting data through an event handler.
So we can implement good application without having problem in load-time and/or
post-load process, means, we process further when we know our data variables are
successfully received without any error. Remember! ‘onLoad’ event of the ‘loadVars’
object must be implemented as function in SWiSHScript. The variable ‘success’ used
in below examples is of type Boolean.

1.Example for loading data:

l = new loadVars(); create new instance of object ‘loadVars’


l.load(“myFile.txt”); start loading data variables from file
‘myFile.txt’

l.onLoad = function(success) {
if(success) {
take_action_file_loaded_successfully
} else {
handle_error_occured
}
}
111

2.Example for loading data with knowledge of percentage of data loaded:


Total, Loaded, Percent, msg are the variables attached to 3 (three) dynamic text
boxes.

l = new loadVars(); create new instance of object ‘loadVars’


l.load(“myFile.txt”); start loading data variables from file
‘myFile.txt’

l.onLoad = function(success) {
if(success) {
take_action_file_loaded_successfully
} else {
handle_error_occured
}
}
onEnterFrame() {
Total = l.getBytesTotal();
Loaded = l.getBytesLoaded();
Percent = (Total/Loaded) * 100;
}

The ‘onLoad’ event handler is also used to ensure either data has been sent
successfully of not (while sending data through send function).

3.Example for Sending data


l = new loadVars(); create new instance of object ‘loadVars’
l.send(“script.php”, “POST”); send available variables (in current path)
to server script.php via POST method.
l.onLoad(success) {
if(success) {
take_action_file_loaded_successfully
} else {
handle_error_occured
}
}

4.Example for Sending and Receiving data using function ‘sendAndLoad’


l = new loadVars(); create new instance of object ‘loadVars’
l.sendAndLoad(“script.php”, this, “POST”); send available variables (in current path)
to server script.php, receive them in
current path current object ‘this’, via http
protocol method POST.
l.onLoad = function(success) {
if(success) {
take_action_file_loaded_successfully
} else {
handle_error_occured
}
}
112

Open SWiSHMax file loadVars.swi which contains example of loading variables from
a text file with accuracy. Export to SWF6 and upload SWF + myFile.txt to server and
test it. It can also be tested on load computer. Code in file is:

onLoad() {
l = new loadVars();
l.load("myFile.txt");

l.onLoad = function(success) {
if(success) {
_root.msg = this.msg; data successfully received, assign
value of received variable ‘msg’ to
variable ‘msg’ available in _root
(attached to a dynamic text
object).
} else {
_root.msg = "Error loading file!";
}
}
}
onEnterFrame() {
Total = l.getBytesTotal();
Loaded = l.getBytesLoaded();
Percent = (Total/Loaded) * 100;
}

Sprite Duplication and accessing duplicated sprite’s properties

The better approach (used in standard applications) is sprite duplication,


when we need to create objects of same structure / variables but with different data,
size, colors, text(s) etc.

What is sprite Duplication actually?

This is the method used to clone an existing sprite object in our SWiSHMax
movie.

Why to clone? Instead simply Copy/Paste the sprite?

Answer is too simple; the copied objects increase the size of your final
publishable (on web) SWF movie. So it is simple to say: the more objects in movie,
the more memory / processing is required to run it; so your application becomes
heavy (to load) and of course slow. Our major aim must be use of core features to
have full functionality within limited sized movie. We will move forward, keeping in
mind that our applications will be using small amount of memory (by using less code,
data, & objects) and producing 100% results.

Now let us move to the code used for Sprite Duplication.

A built-in function (duplicateSprite()) is used to clone / duplicate sprite


objects. It works exactly same as duplicateMovieClip() in Flash. For duplicating a
113

sprite you must provide three types of data to this function (two as arguments), and
one as prefix to the function (that is base sprite). First is the new name of the
duplicated object, and the second is depth of cloned object. Duplicated sprite name
must be a valid identifier that must contain alphabets, digits, and underscore
character (_), but starting letter of name must not be a digit.

Easy example to duplicate sprite:


Open 017.swi, select red button object and see its script that contains:

on(release) {
spr.duplicateSprite("newSpr",2);
newSpr._x += 50;
newSpr._y += 50;
}

spr The actual/base sprite to duplicate/clone.

duplicateSprite The function used for duplication

"newSpr" The name of duplicate/cloned/new sprite

3 The depth of duplicated sprite (remember:


depth must be unique/higher number than
the existing objects’ depths, otherwise the
duplicate sprite will replace the existing
one (if) in same depth)

newSpr._x += 50; Add 50 in the X coordinates of the


duplicated sprite, so it moves to right 50
pixels.

newSpr._y += 50; Add 50 in the Y coordinates of the


duplicated sprite, so it moves to down 50
pixels.

What is depth?
Each object has a depth, the order or the objects in stack over each other.
E.g. you have 2 objects in a SWiSH movie, the object on bottom has depth 1, and
the top one has 2. So when you duplicate some sprite in same movie use higher
depth preferably 3.

Now run the movie and click the button captioned “ Duplicate sprite ‘spr’ ”. Now You
see a new sprite (exactly same to spr) appears immediately. You are done; your
sprite has been duplicated successfully.

Remember: If data/size/color/(or anything else that can be changed at runtime) of a


sprite, has been changed at runtime, and it is duplicated; the (new) duplicated one
will not be same to it, but as the base sprite was by default.

Now a question may be appearing in your mind, “if our sprite contains a dynamic
text object that has a variable ‘xyz’, how to access xyz in duplicated sprite?”
114

Solution is so simple, in previous example we accessed _x and _y properties of the


duplicated sprite. Use the same way to access variable ‘xyz’ as

newSpr.xyz = “some new value”;

See example file 018.swi, run it (in player or browser), you see a new sprite with
text ‘some new value’ appears, where value of original sprite spr.xyz was ‘MySprite’.
Conclusion is, you can access variables of any sprite the same way (either sprite is
duplicated or original which has already been discussed in chapter 2, topic: Sprite
Object).

Arrays in SWiSHScript, more flexible and powerful than in ActionScript

What is Array?

I am writing two simplest definitions of Array:

1.Array is collection of different data elements handled by single variable name.


2.Array is chain of sequential data items accessed under single variable name.

You know how to create variables. Variables use to hold single value at a
time, either that is numeric, text, or logical data. But, Arrays can hold more than one
data items of different data types sequentially under single variable name.

Following is the example of a simple Array in SWiSHScript.

Example:

myArr = new Array(123, “Ali”, 3.15, false);

In above example, we created new Array of 4 elements , where each element is of


different data type, and assigned this array to be accessed through variable ‘myArr’.

How to access item/element number 1 of the Array?

trace( myArr[0] ); function trace() is used to show


something in internal debugger of
SWiSHMax.

You have to use square brackets to access elements of an Array. And pass it N-1 to
access item number N. as in above example we had to access item number 1 of the
Array. So N is 1 (one) and we passed N-1 is 0 (zero). Similarly if you need to access
item number 15 (fifteen) you will pass 14 (fourteen) as myArr[14] within the square
brackets. 14 is index of element in Array.
115

How to get length of and Array?

So simple! Use the built-in property ‘length’ of Array, as:

arrLen = myArr.length;

Where ‘arrLen’ is new variable, we assigned it the length of the Array ‘myArr’ (which
is 4 - four).

How to add elements to an Array at Runtime?

Very simple.
Creating variable once:
myArr = new Array(); create empty array variable

Add items at runtime:


myArr[0] = 123;
myArr[1] = “Ali”;
myArr[2] = 3.15;
myArr[3] = false;

How come, it is more powerful than in Flash MX ActionScript?

It is! Because SWiSHScript provides you a well managed way of handling


Array elements, by naming the indexes. SWiSHScript follows the same way used by
PHP language to extend the use of Arrays. You can create names of the indexes of
the elements in an Array. See example of a student record:

myArr = new Array();

myArr[‘std_name’] = “Ali Imran”;


myArr[‘std_age’] = 27;
myArr[‘std_marks’] = 315.90;
myArr[‘std_email’] = “news@swish-db.com”;
myArr[‘std_site’] = “http://www.swish-db.com”;
myArr[‘std_grade’] = ‘B+’;
myArr[‘std_assist’] = false;

Now we show the std_site item of the student record Array in internal debugger of
SWiSH using trace() function.

trace( myArr[‘std_site’] );

open Array1.swi and run it within SWiSHMax, internal debug window.


116

The output in debug window will be

You can also pass Integer or String variables instead of constant indexes, as:

Through Integer variable as index:

myArr = new Array(12, “Ali Imran”);


I = 1;
trace( myArr[I] ); which will output ‘Ali Imran’ in debug window.
Value of variable ‘I’ is 1 so index number 1
(element number 2) is accessed.

Through String variable as index:

myArr = new Array();


myArr[‘std_name’] = “Ali Imran”;
myArr[‘std_age’] = 27;

S = “std_age”;
trace( myArr[S] ); which will output ‘27’ in debug window. Value of
variable ‘S’ is “std_age” so is index of array
(element number 2) is accessed.

Another example of adding 10 (ten) random numbers to an Array and printing them
one by one:

Assign:
myArr = new Array();
for(I=0; I<10; I++) {
myArr[I] = random(1000);
}

Display in Debug Window:


for(I=0; I<10; I++) {
trace(myArr[I]);
}

Facility of named indexes is not available in Flash MX ActionScript, but is in


SWiSHMax SWiSHScript. That is why I said, Arrays are more powerful in
SWiSHScript than in ActionScript.
117

Chapter 5

Advanced Events Handling and other


Scripting Objects

Before going forward, I would like to quote the name of the person who is an
ActionScript guru for me and who taught me almost complete events handling
through online chat. I learnt most of the events’ working from my honorable teacher
Mr.Gregory Baker (Nick Greg, AKA gsb on SWiSH/Flash community forums). I am
proud to say that he taught me the most advanced techniques involved in events
handling (which I have used while creating UI Collection Objects). Mr.Gregory
Baker may be contacted at Greg@GypayTrader.com.

ƒ Evaluation/Access of Dynamic Objects/Variables


ƒ Advanced Techniques of Events Handling (an Introduction)
ƒ How to implement existing event handlers within functions
ƒ Deleting Event Handlers when job is done
ƒ Defining/Attaching new events handlers to Sprite object, and using them
ƒ Creating Events to accept variables as Arguments
ƒ Connecting Objects through events
ƒ Defining Global functions to use anywhere without reference
ƒ Creating Sprite pointers
ƒ Collision detection for games creation
ƒ Encoding special characters before sending to SWiSH Movie
118

Evaluation/Access of Dynamic Objects/Variables

Let us get started without loosing time. Here (in topic title), I am using the
word ‘dynamic’ for the objects created at runtime, means, the objects which are not
actually part of your movie, but they are created at runtime through script (or cloned
from existing objects as we did in topic sprite duplication), when movie is running.

So word ‘dynamic object’ is clear, but, what about Dynamic Variables? At this
point, most of the students ask a question “Variable means the identifier which can
vary / change anytime, then how we call a variable being ‘dynamic’?”.

So simple answer to understand: The variables we define in our movie, are always
named, such as ‘myName’, ‘myEmail’, ‘x’, ‘y’, etc, now if our SWiSH movie is
receiving data from some text file or a PHP script, and that text or script responses
back with some new variable names such as ‘myName2’ or ‘myEmail2’ which are not
already in you movie, they are the dynamic variables actually.

Major question is: How to fetch value from dynamic variables, which are not
already defined in our SWiSH movie?

No need to worry, use ‘eval()’ function, that evaluates variables and objects;
You simply pass the name of variable or object to this function, and this function
pulls out value or path of it. See the example below (contained in 019.swi):

Note : If anything passed to eval function is a sprite object, it will return path of the
sprite, and if the passed argument was variable name, then, eval function will pull
out its value.

myText = eval(“this.myName2”);

In above example, we are loading a simple text file (using function loadVaribles),
that responds with a new variable called ‘myName2’. We are getting value of
dynamic variable ‘myName2’ and assigning it to already defined variable ‘myText’
(attached to/target of a dynamic text box). When you run the movie, you will see
immediate change in value of text object from ‘Default Value’ to ‘Ali Imran’.
Complete code of 019.swi:

onLoad() {
119

l = new loadVars();
l.load("019.txt");

l.onLoad = function(success) {
if(success) {
myText = eval("this.myName2");
}
};
}

Understanding line by line:

onLoad() { Event Handler, that runs when a Sprite


Object or main movie is started loading.
(Works almost as constructor of a class in C++)

l = new loadVars(); Create new Instance of loadVars object in


memory

l.load("019.txt"); Load a simple text file (019.txt) that


contains variables and data

l.onLoad = function(success) { Implement the onLoad event hander of


Object loadVars yourself, to check if data
received successfully, and proceed
further.

if(success) { If data received successfully (without any


error in transfer)

myText = eval("this.myName2"); If data received successfully without error,


then evaluate assumed variable name and
assign its value to variable ‘myText’.

Where text file 019.txt contains

&myName2=Ali Imran&

Now, when we understand the procedure to get value from a dynamic


variable (which is not already in scope), let us move forward to learn advance use of
this technique.

For example, you are creating an application for kids learning, which loads a
text file at each specific point of runtime, and duplicates some sprite up to a specific
number ‘N’ each time, considering number ‘N’ is being received from a plain text file
‘020.txt’. Now open the 020.swi and see the code.

In ‘onLoad()’ event of the main movie we loaded a text file ‘020.txt’; When it
has completely loaded, we start duplicating sprite ‘mySpr’ up to number N (which is
received form the text file).
See the code of 020.swi:
onLoad() {
l = new loadVars();
120

l.load("020.txt");

l.onLoad = function(success) {
if(success) {
cx = mySpr._x;
for(i=0; i<this.N; i++) {
mySpr.duplicateSprite("newSpr"+i,i+1);
temp = eval("newSpr"+i);
temp._x = cx;
cx +=mySpr._width;
}
}
};
}

As we already have studied the sprite duplication and accessing duplicated


sprites’ variables, I will not be discussing it again in here.

In above example we have created a instance of Object loadVars() (at


runtime), and loaded a text file 020.txt using its function load(). After the file is
successfully loaded, we received a variable ‘N’, then we repeated a set of 4 lines
instructions within a ‘for’ loop, up to ‘N’. the 4 lines of instructions are:

mySpr.duplicateSprite("newSpr"+i,i+1); Duplicate Sprite mySpr

temp = eval("newSpr"+i); get reference of newly duplicated sprite,


and put reference in new variable ‘temp’

temp._x = cx; Change X position of duplicated sprite to


variable ‘cx’

cx +=mySpr._width; Add width of base sprite ‘mySpr’ to


variable ‘cx’, and assign to variable ‘cx’

What I actually discussion is going for, is, that, you can also evaluate objects’
names (“newSpr”+i); Put reference in other variables to point them, and access the
objects through pointing variables (which was ‘temp’ in above example).

Advanced Techniques of Events Handling (an Introduction)

We already have studied the basic events of button and sprite objects.
Objective of this topic is to teach you how to customize existing events, passing
them variables, defining/attaching new events to a Sprite object, and using them. In
this chapter we will also learn how to implement existing event handlers within
custom functions or other existing event handlers.
121

How to implement existing event handlers within functions?

As we already created our own functions within onLoad() event handler, we will
follow the same here. Implementing event handler ‘onEnterFrame’ of sub sprite xyz.

onLoad() {
xyz.onEnterFrame = function() {
take_some_action
};
}

Implementing the same event handler ‘onEnterFrame’ within a custom function

function myFunction() {
xyz.onEnterFrame = function() {
take_some_action
};
}

What is the use of implementing an event handler within function?

When we need to activate event handlers and want them not to take place
automatically, we put them in functions, so that, they are activated when function is
called.

In above example we implemented event handler ‘onEnterFrame’ of sprite


‘xyz’ within our custom function ‘myFunction’. Now, when we call this function (as
myFunction()), the event handler ‘onEnterFrame’ of sprite ‘xyz’, is activated and
starts working.

What to do, when I want to deactivate an event handler when job is done,?

Deleting Event Handlers when job is done

E.g. You have event handler ‘onEnterFrame’ in so many paths/sprites, this will
slow down your movie and will directly effect everywhere in the movie e.g. dragging,
animations, typing etc. The best way to utilize this event handler is to have the job
done by it and then delete it. Example

if( all_done ) {
delete xyz.onEnterFrame;
}
This way we can delete any event handler or function and utilize the memory
resources in a proper manner, when event handlers / functions become useless to
movie, or no more required. E.g.

if( all_done ) {
delete xyz.onLoad;
//almost senseless, because sprite may have already been loaded
}

or Deleting custom function


122

if( all_done ) {
delete myFunction;
}

Even you can delete an event handler or function from within itself. Such as:

onLoad() {
xyz.onEnterFrame = function() {
take_some_action1
take_some_action2
take_some_action3
take_some_action…..
……
job_is_done

delete xyz.onEnterFrame;
};
}

Open 021.swi and play it. You will see something like this

Now click the red button. You will see the animation is immediately stopped. Why?

Description:
The animation is implemented within the event handler ‘onEnterFrame’ which
changes the ‘_rotation’ property of the sprite ‘mySprite’ continuously. Now, on
button press we have deleted this event handler ‘onEnterFrame’ so, all the actions
taken by this event handler are stopped immediately. Code we used for deletion is:

delete onEnterFrame;
123

Defining/Attaching new events handlers to Sprite object, and using them

There are many methods to attach events to sprite objects, but I will
demonstrate you the most easiest and efficient method. This can only be understood
through examples.

Our First custom event handler example:

onLoad() {
mySprite.onAnimationEnded = function() {
msg = “Sprite Animation has ended playing.”;
};
}

open 022.swi contains source of above example.


Above code is in main timeline, means, we implemented new event handler
‘onAnimationEnded’ of sprite ‘mySprite’ as function, in ‘onLoad’ event handler of
_root (main timeline).

See the swi file structure:

New event handler ‘onAnimationEnded’ of sprite ‘mySprite’ must be generated from


within the sprite ‘mySprite’. See in above screenshot we simply called it (as a normal
function onAnimationEnded()) on Frame # 50 of sprite ‘mySprite’, so it has been
invoked/fired. Now, when it has been invoked/fired, it is immediately detected by the
event handler we implemented in _root and the code in that event handler
‘onAnimationEnded’ is executed, which is

msg = “Sprite Animation has ended playing.”;

By the way, ‘msg’ is a variable attached to a dynamic text box ‘_msg’. So the value
of that dynamic text box is changed when event is invoked/fired from the sprite
‘mySprite’.

Let us have another example. Now we try to replace existing events on a button
object, ‘onPress’, ‘onRelease’ with ‘onMousePress’ and ‘onMouseRelease’.
124

Example:

Code in main timeline:

onLoad() {
mySprite.onMousePress = function() {
msg = "Mouse is pressed";
};

mySprite.onMouseRelease = function() {
msg = "Button of Mouse is Released";
};
}

Code on button action:

on(press) {
onMousePress();
}

on(release) {
onMouseRelease();
}

NOTE: sprite name is same as above example.

Open 023.swi contains above mentioned source.

This was the most easiest way of attaching new event handlers to your sprites.
Implementation and use custom event handlers is best when we create reusable
components such as UI Collection Objects (coming in next chapters). Especially,
when, the users write functional sprites but they do even start to work because of
the functions and event handlers not loaded into memory immediately. So users try
to put their initialization code in far frames such as on frame number 20.

Most frequently occurred problem with Intermediate level scriptors:

If I want to initialize and use functions of my object in ‘onLoad’ event handler of


main movie, I do not get the desired results, although the code/script is 100%
accurate. Now, when I put the same code in an ‘onFrame(20)’ event handler it works
perfectly. But it messes up with animations and other code of main timeline, and I
want this code be within ‘onLoad’ event handler of main timeline. How to prevent
these unwanted results, and how to implement to have it working within ‘onLoad’?
Solution to above problem:
125

We will have to implement an event handler working as trigger. We will fire it


when we know all the script and sub-objects have been loaded into memory
successfully. Let us have an example. Open 024.swi and see, it contains a sprite
‘mySprite’ which contains further sub sprites ‘a’, ’b’,….., so on.

Structure of 024.swi (what users actually do):

Here we need to know a new built-in function typeOf() before we move forward:

Function typeOf() gives us the type of a movie object passed as argument. It


acts exactly same as in Flash MX ActionScript ‘typeof’. I we pass it a sprite name it
will return “movieclip”. See example code below, remember: in 024.swi ‘mySprite’
is a sprite object:

msg = typeOf(mySprite);

it will show results in the movie as

So this is the type of a sprite object, you may pass any object name and obtain its
type as string name.

It returns following string results for different type of objects as:

Object type resulting Type


String string
Sprite movieclip
Path (_root/_parent/_level) movieclip
Button object
Text Field object
Numeric (integer/float) number
Boolean (true/false) boolean
126

Function function
Event handler function
Object object
And the objects not yet loaded or not exist unknown

So we have no more concern with other return types; We will simply utilize the
return type “unknown”. If we are sure we have an object and it function ‘typeOf’ is
returning ‘unknown’, it is confirmed that it is not yet loaded into memory.

So let us move back to our discussion. File 024.swi contains the source usually does
not work.

If you see carefully the sprite ‘d’ contains a small animation which is stopped on first
frame. Now go to main timeline, it contains:

onLoad() { event handler in _root


mySprite.d.gotoAndPlay(2); go into sprite ‘mySprite’ then into sprite
‘d’, and play the stopped timeline.
}

Generally it seems to work, but it does not, generate desired results. Because the
time when this code is executed, the sprite ‘d’ is not yet loaded into memory.

On other hand if you see code on button action (works perfectly):


on (release) {
mySprite.d.gotoAndPlay(2);
}

Now open 025.swi where we will use the same example within ‘onLoad’ event
handler using function ‘typeOf’ for sprite ‘d’. see the code in main timeline:

onLoad() {
onEnterFrame = function() {
if(typeOf(mySprite.d) ne "unknown") {
mySprite.d.gotoAndPlay(2);
delete onEnterFrame;
}
};
}

operator ‘ne’ (not equal to - for String comparison) same as != in numeric


comparison.

Detail:
onEnterFrame = function() { implement event handler to check type of
sprite ‘mySprite.d’ continuously.
if(typeOf(mySprite.d) ne "unknown") if type of ‘mySprite.d’ not equals to
“unknown” that means it is fully loaded
into memory
mySprite.d.gotoAndPlay(2); play the sprite ‘d’ timeline from frame 2.
delete onEnterFrame; once it has been played remove the event
handler ‘onEnterFrame’, so that it does
not check and play again.
127

Now this is also lacking functionality, because we may need to implement event
handler ‘onEnterFrame’ for further code execution, and we have deleted it. Let us
implement this event handler within sprite ‘d’ and generate custom event handler
from within ‘d’ and track it in main timeline. Open 026.swi which contains code in
main timeline:

onLoad() {
mySprite.d.onFullyLoaded = function() {
mySprite.d.gotoAndPlay(2);
};
}

‘onFullyLoaded’ is the custom event generated by the sprite ‘d’, code in the timeline
of sprite ‘d’ is below:

onLoad () {
onEnterFrame = function() {
if(_framesLoaded == _totalFrames) {
onFullyLoaded();
delete onEnterFrame;
}
};
}
onFrame (1) {
stop();
}

Explanation of code in sprite ‘d’:

onLoad () { ‘onLoad’ event handler of sprite ‘d’


onEnterFrame = function() { implement event handler ‘onEnterFrame’
in sprite ‘d’, as function
if(_framesLoaded == _totalFrames) if loaded frames of current path (sprite
‘d’) are equal to the total frames of
current timeline, then
onFullyLoaded(); generate/fire custom event handler
‘onFullyLoaded’, and
delete onEnterFrame; remove the event handler ‘onEnterFrame’
of current path, we implemented, because
event ‘onFullyLoaded’ has been
invoked/fired once.

Explanation of code in main timeline:

onLoad() { ‘onLoad’ event handler in main timeline


mySprite.d.onFullyLoaded = function() implement the handler for the event
‘onFullyLoaded’ invoked/fired from sprite
‘d’
mySprite.d.gotoAndPlay(2); now, event has been tracked, take the
required action, go to frame number 2
(two) of sprite ‘d’ and play it.
128

Creating Events to accept variables as Arguments

Now, another question appears:


If we have more than 1 (one) sprites same to sprite ‘d’ in our movie, do we have to
implement custom event handler ‘onFullyLoaded’ for each sprite separately? Such as

onLoad() {
mySprite.d.onFullyLoaded = function() {
take_some_action
};
mySprite.E.onFullyLoaded = function() {
take_some_action
};
mySprite.F.onFullyLoaded = function() {
take_some_action
};
}

ANSWER IS ‘NO’, the code is errorless but not efficient neither compressed.

Then, what to implement?

We have to implement the same name custom event handler ‘onFullyLoaded’


but with different approach, so that, it accepts a variable as argument and that
argument will be the id/name of the sprite that is ready and is fully loaded. Open
027.swi and see following code is in any of the sprites ’d’, ‘e’, or ‘f’:

onLoad () {
onEnterFrame = function() {
if(_framesLoaded == _totalFrames) {
_parent.onFullyLoaded(this._name);
delete onEnterFrame;
}
};
}
onFrame (1) {
stop();
}

And code in main timeline is:

onLoad() {
mySprite.onFullyLoaded = function(sName) {
if(sName eq "d") {
mySprite.d.gotoAndPlay(2);
} else if(sName eq "e") {
mySprite.e.gotoAndPlay(2);
} else if(sName eq "f") {
mySprite.f.gotoAndPlay(2);
129

}
};
}

Explanation of code in sprites ‘d’, ‘e’, and ‘f’:

onLoad () { ‘onLoad’ event handler within sprite ‘d’,


‘e’, and ‘f’
onEnterFrame = function() { ‘onEnterFrame’ event handler within sprite
‘d’, ‘e’, and ‘f’
if(_framesLoaded == _totalFrames) if loaded frames of current path (sprite)
are equal to the total frames of current
timeline,
_parent.onFullyLoaded(this._name); fire/generate the event ‘onFullyLoaded’ in
parent path ‘_parent’ which is ‘mySprite’,
so that. It belongs to parent path. And
pass it the name of current sprite using
sprite property ‘_name’.
delete onEnterFrame; delete event handler ‘onEnterFrame’ when
job is done.

Explanation of code in main timeline:

onLoad() { onLoad event handler of


main timeline ‘_root’
mySprite.onFullyLoaded = function(sName) { implement handler for event
fired in path ‘mySprite’,
where ‘sName’ is the
variable receiving the value
passed from the sprites
when event was fired; The
value of sName will be the
names of sprites ‘d’, ‘e’, or
‘f’, replacing this._name.
if(sName eq "d") { now when event is working
and sprites’ names have
been received in variable
‘sName’, let us compare it
with sprite names and
perform the action required
on each sprite fully loaded.
mySprite.d.gotoAndPlay(2); if value of variable ‘sName’
is ‘d’, that means the event
is invoked/fired from sprite
‘d’ , so play the sprite ‘d’
……..
Note: type of property _name is String, you can use it with any pat, e.g. use parent._name to
obtain name of parent path/sprite.

Connecting Objects through events


130

There is nothing special in this topic, if you have read the last topic carefully.
Now when you have learnt how to create and fire events, track them and implement
handlers, you can easily connect more than one sprites to work together. E.g. if
sprite ‘x’ is fully loaded (which contains scroller), start loading the text file from
server into sub sprite ‘y’ of sprite ‘x’.

Defining Global functions to use anywhere without reference

This is the important topic. Please pay full attention. In this topic, I will
demonstrate the method to write your own global functions which can be used
anywhere in any path without prefix reference. We already have studied the Object
‘_global’, which will be used to implement such functions. See example below, open
028.swi which contains code in main timeline as:

onLoad() { ‘onLoad’ event handler in main timeline.


_global.showMsg = function(myMsg) { implement a new function ‘showMsg’ in
‘_global’ object, so that it can be used
globally. ‘myMsg’ is the variable used as
an argument to be passed to the function.
_root.msg = myMsg; ‘msg’ is variable in _root attached with a
dynamic text box. So the value passed to
this function goes directly into the text
box.
}; close the function block
} close the ‘onLoad’ event handler block.

How to call this function when needed?

Simply: showMsg(“this is my message”);

Now let us call it on a button action (button is in main timeline _root). See the script
of button object ‘RBtn’ in 028.swi, which is:

on(release) {
showMsg("Function Called from _root");
}

How to call this function from paths other than _root? that may be from within some
sprite.

The same: showMsg(“this is my message”);

INVALID ONE: _root.showMsg(“this is my message”);


No prefix path is required.

Now see the script on button ‘SBtn’ in sprite ‘mySprite’


131

So, you can see, we did not use any prefix path _root, _parent, _level or any sprite
name to call this function, because it has been declared global function and can be
called from anywhere. This type of functions are useful when you need to implement
some global formulas to be used in all the movie frequently.

Creating Sprite pointers

Some times, we need to point a sprite several times in our application, and
we usually use the absolute path to that sprite e.g. _root.xyz.abc.mySprite, which
needs a lot of code to be written just to point a single object again and again. Then,
why not to implement a variable or object in global context that can point to the
sprite or path without problem of big code lines and avoid use of prefix path. One
way is to use ‘with’ structure which has already been discussed; Example:

with(_root.xyz.abc.mySprite) {
take_some_action
take_some_action
take_some_action
}

And the second way is to create a globally accessible variable. This technique is
useful while creating games. I am sure you are familiar with ‘_global’ object, we
have been using in previous topics/chapters. The method is, simply assign the sprite
or path to the variable in ‘_global’ object, as:

_global.pointer = _root.xyz.abc.mySprite;
132

Explanation:

‘pointer’ is the new variable accessible from anywhere which can be used to access
the sub-sprite ‘mySprite’ wherever sprite is located. E.g. accessing the sprite through
pointer from within another sprite:

pointer.gotoAndPlay(1); go to frame number 1 (one) of sprite


‘_root.xyz.abc.mySprite’ and play it.

Better is to use the assignment expression in ‘onLoad’ event handler of the main
timeline, as:

onLoad() {
_global.pointer = _root.xyz.abc.mySprite;
more_statements
more_statements
more_statements
}

So the variable ‘pointer’ is global now and is accessible from anywhere without prefix
path, to access the properties or functions of embedded sub-sprite ‘mySprite’.

Collision Detection for games creation

Collision Detection is the method to detect when some objects collide/cross


each other on a certain point/position. Simple definition, “To detect if 2 (two) objects
are on the same place in movie X/Y axis or near to each other, is called collision
detection”. There are some built-in functions and properties in SWiSHScript to detect
collision, such as isNearThis(), isNearTarget(), _deopTarget, and _target.

Let us have an example here:

Let us create a drag drop game. We have two sprites ‘plane’ and ‘runway’.
Sprite ‘plane’ is dragable and is to be dropped over the sprite ‘runway’ correctly. If
‘plane’ is dragged and dropped over the sprite ‘runway’ a message is shown
‘ACCURATE’ otherwise ‘WRONG LANDING’.

Open 029.swi. Open sprite ‘plane’, it contains one shape object and one
button object, the first (greenish) object ‘click’ is a button object where the airplane
‘plane’ can be dragged from. Script for this button ‘click’ is as below:
133

Explanation:

on(press) { button object’s event handler when left


mouse key is pressed
startDragUnLocked(); start dragging the current sprite ‘plane’,
regardless the mouse click position over
button
}

on(release) { button object’s event handler when left


mouse key is released up

stopDrag(); stop the dragging of current sprite (if


already being dragged)

if(_dropTarget eq "/runway") when current sprite ‘plane’ is stopped


being dragged, now, if it is dropped over
sprite ‘runway’ (sprite in _root, ‘/’ is used
for _root, so /runway means sprite
runway on _root), then

_parent.msg = "ACCURATE"; change the value of variable ‘msg’ in


parent path, to, ‘ACCURATE’ (where
parent path to sprite ‘plane’ is _root,

else otherwise,

_parent.msg = "WRONG LANDING"; set the value of variable ‘msg’ to ‘WRONG


LANDING’.

Where variable ‘msg’ is attached to a dynamic text object ‘_msg’.


This was the first example where we used ‘_dropTarget’ property to get the name of
sprite where sprite ‘plane’ is dropped over. Property ‘_dropTarget’ returns the
absolute path to sprite over which current sprite is dropped. If you use prefix
path/sprite name to property ‘_dropTarget’, it will detect the collision for sprite used
as prefix, such as:
if(mySprite._dropTarget eq “/Spri”) if sprite ‘mySprite’ is dropped over sprite
‘Spr2’ in _root.
134

Let us have a look over next example 030.swi. this example is implemented using
function ‘isNearThis()’. This is one of the core functions used for collision detection in
game development. 030.swi contains the same objects used in previous example,
but the sprite ‘plane’ moves with keyboard keys ‘up’, ‘down’, ‘left’, and ‘right’ and
button within sprite ‘plane’ is transparent. Here is the preview of this small game:

See the code on button to implement movement of sprite ‘plane’:

Code with Explanation:

on (keyPress("<Down>")) { if arrow key is pressed,


_y++; increase the Y axis of current sprite by 1
(one), so it goes down on pixel
}
on (keyPress("<Up>")) { if arrow key is pressed,
_y--; decrease the Y axis of current sprite by 1
(one), so it goes up on pixel
_rotation=0; rotate sprite ‘plane’ back to normal
}
on (keyPress("<Right>")) { if arrow key is pressed,
_x++; increase the X axis of current sprite by 1
(one), so it goes one pixel right
_rotation=45; rotate current sprite ‘plane’ to angle 45
degree
}
on (keyPress("<Left>")) { if arrow key is pressed,
_x--; decrease the X axis of current sprite by 1
(one), so it goes one pixel left
_rotation=-45; rotate current sprite ‘plane’ to angle -45
degree
}
135

So the movement of sprite ‘plane’ is clear now. Let us see the code found in timeline
of sprite ‘plane’:

onEnterFrame() {
pointer = _parent.runway;
if (pointer.isNearThis())
_parent.msg = "PLANE IS NEAR THE RUNWAY";
else
_parent.msg = "WRONG LANDING";
}

Explanation:

onEnterFrame() { implement event handler ‘onEnterFrame’


in sprite ‘plane’ to execute following
statements continuously

pointer = _parent.runway; create variable ‘pointer’ to point sprite


‘runway’ in root directly without using
prefix path ‘root’

if (pointer.isNearThis()) if sprite ‘runway’ is near current sprite


‘plane’, then,

_parent.msg = "PLANE I…….. change value of variable ‘msg’ in _root to


‘PLANE IS NEAR THE RUNWAY’

else otherwise

_parent.msg = "WRONG…….. change value of variable ‘msg’ to ‘WRONG


LANDING’

Now run the example and move the airplane using keyboard arrow keys, watch the
message just below the design, it changes when sprite ‘plane’ come near to the
sprite ‘runway’, and does same when goes away from it.

Function ‘isNearThis()’ returns true when a sprite is near to another, otherwise


returns false. so we can say this function return Boolean value.

Now, let us have a bit more useful example where, there will be 2 (two)
sprites, ‘ball’ and ‘box’. The moving sprite ball is to be caught and dragged with
mouse and to be dropped over the box, If drop was accurate, the player gets 1
point, player has to make maximum points in limited time 60 (sixty) seconds that’s
equal to 1 (one) minute.

In this example we will be learning ‘Timer.ticks()’, ‘Math.randomRange()’,


‘Stage.width’, and ‘Stage.height’ (Stage Object). Open 031.swi, and test the game.
136

Game preview:

Timer.ticks()

This is alternate to function ‘getTimer()’ in Flash MX ActionScript, which


returns the number of milliseconds that have passed since the Flash Player started
playing movie. TIP: Dividing obtained value by 1000 (one thousand) returns the
number of seconds passed.

Math.randomRange()

First, let us look at the simple functions that return some random value:

MyVal = random(100); //returns some random value <= 100 (one hundred)
MyVal = Math.random(); //returns any random value (a number)

Now, if we need to obtain a random value within a range, e.g. a random number
between 5 to 100 we will use function ‘randomRange()’ of Math object, as:

MyVal = Math.randomRange(5,100); //returns random value between 5 (five)


and 100 (one hundred)
Stage Object

Object available in SWiSHScript as well as in ActionScript gives us information


about the physical Movie, where we can obtain width, height, alignment in browser,
and information about current Scale Mode.

Stage.width Returns physical width of the movie in browser or player (in


pixels).
Stage.height Returns physical height of the movie in browser or player (in
pixels).
Stage.align Returns current alignment of movie on stage, as string.
Stage.scaleMode Returns current Scale Mode as string “showAll”, “exactFit”, etc.
137

There is an event handler available ‘onResize’, which may be implemented according


to needs (when movie has been resized), as:

onLoad() {
Stage.onResize = function() {
take_some_action
};
}

Encoding special characters before sending to SWiSH Movie

Most of the times, when we load some text from outside resources (especially
using loadVars() object), some of the characters are ignored are shown as %20,
%24, etc. Especially the character ‘&’ is used to identify variables in text data, and I
we put it in a text file as text, it is no recognized as a simple text character but a
separator to start reading value of new variable. The technique we will be using is
called “URL Encoding in Flash”.

In some other cases when we have a dynamic text object and is html
enabled, and we need to display <b> (as I said display not to make text bold but
show the bold html tag), in html we use to &lt; to display ‘<’ and &gt; to display ‘>’.
I we do adopt the same way and send the values to back to swish movie html
textbox it will no display anything at all, why?
See the code e.g. text file contains

&myVar=&lt;b&gt; //which must display <b> in html file usually


//and in flash player as well

what happens when this text is loaded? The second ‘&’ sign is just after the ‘=’ sign,
so ‘lt;b’ is not being treated as data, similarly third after ‘&’ sign there is ‘ft;’ which is
also not being treated as data because both are right after the ‘&’ sign. If we want
them be treated as data we must encode them before sending back to SWiSH movie.

like convert ‘&’ to %26


so that the data of text file becomes:
&myVar=%26lt;b%26gt;

Run the example 032.swi to test it yourself.

Reference Flash MX Help Manual

URL Encoding: Reading special characters from a text file


One common technique used to load variables in Macromedia Flash is reading the
data from a text file on the server or CD. This works well in most situations.
However, there are certain characters that cannot be read directly from text.

Entering these characters in a text file read by Macromedia Flash may cause unusual
results. These characters need to be URL encoded. URL encoding replaces the
alphanumeric character with the hexadecimal combination which represents that
character.
138

Note: Macromedia Flash MX adds full Unicode support to the Macromedia Flash
Player. This may be helpful in encoding your data. For complete details see Working
with Multiple Languages in the Macromedia Flash Support Center.

Use encoding to ensure that variables are passed correctly


The example below illustrates how special characters can be retained using URL
encoding:

A text file containing the following variable value:


Cost=+85
Will read into Flash as 'Cost= 85', dropping the + character.

However, using URL encoding to replace the + character the original text:

Cost=%2b85
Will result in Flash displaying 'Cost= +85' correctly.

Use this URL Encoding table for special characters:

backspace %08
tab %09
linefeed %0A
return %0D
space %20
! %21
" %22
# %23
$ %24
% %25
& %26
' %27
( %28
) %29
* %2A
+ %2B
, %2C
- %2D
. %2E
/ %2F
0 %30
1 %31
2 %32
3 %33
4 %34
5 %35
6 %36
7 %37
8 %38
9 %39
: %3A
; %3B
< %3C
= %3D
139

> %3E
? %3F
@ %40
A %41
B %42
C %43
D %44
E %45
F %46
G %47
H %48
I %49
J %4A
K %4B
L %4C
M %4D
N %4E
O %4F
P %50
Q %51
R %52
S %53
T %54
U %55
V %56
W %57
X %58
Y %59
Z %5A
[ %5B
\\ %5C
] %5D
^ %5E
_ %5F
` %60
a %61
b %62
c %63
d %64
e %65
f %66
g %67
h %68
i %69
j %6A
k %6B
l %6C
m %6D
n %6E
o %6F
p %70
q %71
r %72
140

s %73
t %74
u %75
v %76
w %77
x %78
y %79
z %7A
{ %7B
| %7C
} %7D
~ %7E
¢ %A2
£ %A3
¥ %A5
| %A6
§ %A7
« %AB
¬ %AC
¯ %AD
º %B0
± %B1
ª %B2
, %B4
µ %B5
» %BB
¼ %BC
½ %BD
¿ %BF
À %C0
Á %C1
 %C2
à %C3
Ä %C4
Å %C5
Æ %C6
Ç %C7
È %C8
É %C9
Ê %CA
Ë %CB
Ì %CC
Í %CD
Î %CE
Ï %CF
Ð %D0
Ñ %D1
Ò %D2
Ó %D3
Ô %D4
Õ %D5
Ö %D6
Ø %D8
141

Ù %D9
Ú %DA
Û %DB
Ü %DC
Ý %DD
Þ %DE
ß %DF
à %E0
á %E1
â %E2
ã %E3
ä %E4
å %E5
æ %E6
ç %E7
è %E8
é %E9
ê %EA
ë %EB
ì %EC
í %ED
î %EE
ï %EF
ð %F0
ñ %F1
ò %F2
ó %F3
ô %F4
õ %F5
ö %F6
÷ %F7
ø %F8
ù %F9
ú %FA
û %FB
ü %FC
ý %FD
þ %FE
142

Chapter 6

Using UI Collection Objects


ƒ Introduction to UI Collection Objects
ƒ UI CheckBox
ƒ UI Radio Button
ƒ UI Menus
ƒ UI Combo Box
ƒ UI Toolbars
ƒ UI Spreadsheet
ƒ UI Form Dialogue
ƒ UI Pie Charts
ƒ UI Bar Graphs
ƒ UI Line Graphs
ƒ Connecting UI Spreadsheet with UI Pie Charts, UI Line Graphs, and UI Bar
Graphs

Note:
This chapter specifically elaborates the UI Collection Objects version1, definitions,
techniques, and code samples.

Disclaimer:
UI Collection Objects v1 has no relation/partnership with SWiSHZone Pty. Ltd,
Macromedia Inc, and/or any other third-party, and this product or any part of this
product may not be published/redistributed/resold in any case in any form without
the permission of respective author. This product purely belongs to author: Ali Imran
Khan Shirani, and is created to enhance functionality of SWiSHMax Projects.
143

Introduction to UI Collection Objects

We are proud to introduce a huge enhancement in the SWiSHMax world. This


type of collection is being launched for the very first time on web (although some
other controls have already been introduced by individuals). This is the collection of
pre-made controls with higher functionality that enables you to enhance your
existing SWiSHMax projects in an organized manner, and generate a professional
look of your web projects. This collection is made to facilitate the advance and
moderate level SWiSHMax users, to not to waste time on creating usual combo
boxes, menus, radio, check, and almost all type of inputs, just use them via copy-n-
paste easy technique. These are written keeping in view the higher functionality
within limited size of output publishable movies and higher speed to accommodate
all type of internet connections, so that the dialup users do not need to worry about
load-time of your application.

UI Collection Objects are very useful for business solutions with inclusion of
embedded Bar Graph, Line Graph, and Pie Chart Controls. In beginning, the code of
these controls seems hard, but gradually a moderate level user can also go through
all of the controls and implement desired high level application after reading
examples and complete explanation included alongwith book. Best and easiest
examples do not let you mess with the actual code of controls but make you all
understand easily and enable you to use them properly.

I am sure, after reading this chapter, you will be able to accept any web
application challenge and will be able to write higher level web applications within
limited duration easily and comfortably.
144

UI CheckBox

UI CheckBox works exactly as a normal Checkbox, you usually see in html


pages or in windows applications. A CheckBox is used for input of Boolean type value
(true or false). in other words, it acts like ON/OFF button, so we can say a CheckBox
can contain only single Boolean value either true or false, If it is checked it means it
is true otherwise false. See the screenshot of usual CheckBox in window applications,
and UI CheckBox:

Open UICO_01.swi and test (either in browser or player). When it is running, click
the checkbox, notice that, once it is checked and one second click it is unchecked. It
is the automatic functionality of UI CheckBox.

How to insert UI CheckBox in my SWiSHMax project?

Copy the sprite ‘UICheckBox’ from file UICO_01.swi, paste it in your SWiSHMax
project, and move it to desired place in the movie surface. Make its copies as many
as required in your SWiSHMax project, but Remember: Name of each UI CheckBox
sprite must be unique, otherwise they will not function correctly.

See the code of file UICO_01.swi in main timeline:

onLoad() {
UICheckBox.onReady = function() {
UICheckBox.caption="This is my caption";
};
UICheckBox.onChecked = function() {
msg="checked";
};
UICheckBox.onUnchecked = function() {
msg="unchecked";
};
}
145

Explanation:

Note: variable ‘msg’ is attached to a dynamic textbox in the example file, so, the
display of textbox is changed when value of variable ‘msg’ is changed.

onLoad() { ‘onLoad’ event handler of main movie

UICheckBox.onReady = function() { implement handler for event ‘onReady’ of


UI CheckBox, which is automatically
invoked/fired when a UI CheckBox has
successfully been loaded into memory

UICheckBox.caption="This is….."; When it is assured that UI CheckBox has


been loaded into memory, change the
caption text of the CheckBox, by
accessing the ‘caption’ property of the UI
CheckBox.
}; Close ‘onReady’ event handler
implementation block.

UICheckBox.onChecked = function() { implement handler for event ‘onChecked’


of UI CheckBox, which is automatically
fired when a UI CheckBox is checked
(turned ON) by user click
msg="checked"; So, when it is checked change the value of
variable ‘msg’
}; Close ‘onChecked’ event handler
implementation block.

UICheckBox.onUnchecked = function() { implement handler for event


‘onUnchecked’ of UI CheckBox, which is
automatically fired when a UI CheckBox is
unchecked (turned OFF) by user click

msg="unchecked"; So, when it is unchecked change the value


of variable ‘msg’
}; Close ‘onChecked’ event handler
implementation block.

} Close ‘onLoad’ event handler


implementation block in main timeline.

There are some more events for a UI CheckBox such as ‘onClick’. You can take
desired action when a checkbox is clicked, this event is invoked/fired when a UI
CheckBox is clicked in no concern with checked or unchecked. You can implement its
handler as:

UICheckBox.onClick = function() {
take_some_action
};
146

You can also turn a UI CheckBox ON(checked) or OFF(unchecked), through following


mentioned functions of a UI CheckBox:

UICheckBox.check(); check (set ON)


UICheckBox.uncheck(); uncheck (set OFF)

Open UICO_02.swi, which contains the example of unconditional uncheck and


check of a UI CheckBox at runtime; test it in player. After testing it see code of
buttons ‘ON’ and ‘OFF’.

How to either a UI CheckBox is checked or unchecked?

Use function ‘getValue()’ which returns true if it is checked and false otherwise, as:

if(UICheckBox.getValue())
msg = “It is Checked”;
else
msg = “It is Not checked”;

Check example file UICO_03.swi, run it, check the checkbox and press button
‘getValue’, now uncheck and press button ‘getValue’ again, see the value of variable
‘msg’ has been changed.

To Enable or Disable a UI CheckBox control, use:

UICheckBox.enabled(false); Disable to UI CheckBox, so that it is no


more clickable
UICheckBox.enabled(true); Re-Enable if the UI CheckBox was
disabled, so that it becomes clickable
again

How to either a UI CheckBox is enabled or disabled currently?

Use function ‘getState()’ which returns true if it is enabled and false otherwise, as:

if(UICheckBox.getState())
msg = “Control is Enabled and is clickable”;
else
msg = “Control is Disabled and is NOT clickable”;

Additional Events for UI CheckBox

onDisabled event invoked/fired when a UI CheckBox


is disabled through function ‘enable(false)’
onEnabled event invoked/fired when a UI CheckBox
is Re-Enabled through function
‘enable(true)’
onResized event invoked/fired when a UI CheckBox
is resized through function ‘setWidth()’
147

Open file UICO_04.swi and test in player. Note, when it has been disabled, it is no
more clickable, and user can’t check or uncheck through click.

Utility Functions for UI CheckBox:

Following are the utility functions, that modify a UI CheckBox at runtime.

remove() Destroy the UI CheckBox control


setCaption(newCap) Change text caption of UI CheckBox
setBgColor(newCol) Set Background color of the UI CheckBox
setSelectionColor(newCol) Set selection color when mouse is over
setWidth(newW) Set width (clickable pan area)
moveTo(x,y) Alternate to change in _X= and _Y=
moveBy(x,y) Alternate to change in _X+= and _Y+=
getWidth() Get current (clickable pan width in pixels)
getHeight() Get current (clickable pan height in pixels)
getX() Current _X coordinates in parent path
getY() Current _Y coordinates in parent path

Open and test file UICO_05.swi, that contains multiple UI CheckBoxes in.
So, this was the quick and almost complete study if UI CheckBox, let us move to
other UI Collection Objects.

UI Radio Button

Radio Buttons are also called Option Buttons. Radio buttons work collectively
and perform the action within a group. These are used when we want our user to
have multiple (more than 1) options, where s/he can select one of them at a time,
e.g.

• (2 radios group) Selection of Male and Female


• (4 radios group) Married, Unmarried, Divorced, or Widow
• (3 radios group) Age less than 18, More than 18 and less than 26, More than 26

Example of the third scenario in windows application may look like:


148

Open UICO_06.swi and test (either in browser or player). When it is running, click
any of the radio buttons, notice that, when you select any of them, the last selected
is automatically unselected.

How to insert UI Radio in my SWiSHMax project?

Copy the sprite ‘UIRadio’ from file UICO_07.swi, paste it in your SWiSHMax project,
and move it to desired place in the movie surface. Make its copies as many as
required in your SWiSHMax project, but Remember: Name of each UI Radio sprite
must be unique, otherwise the Radio group will not function properly, because of
ambiguity.

UI Radio Buttons use to have unique groups. E.g. there are 5 UI Radios in your
movie, first 3 Radios are being used to let user select age, and other 2 UI Radios are
being used to let user select Gender (male/female). So there will be 2 logical groups,
first group will be ‘age’, and other one will be ‘gender’.

How to assign group to a UI Radio Button?

First 3 UI Radios in logical group ‘age’


Radio1.group = “age”;
Radio2.group = “age”;
Radio3.group = “age”;

Last 2 UI Radios in logical group ‘gender’


Radio4.group = “gender”;
Radio5.group = “gender”;

I don’t think there is any complication in understanding the group assignment to UI


Radios.

See the code of file UICO_06.swi in main timeline:

onLoad() {
a1.caption = "Under 18";
a2.caption = "Exact 18";
a3.caption = "Over 18";

a1.group = "age";
a2.group = "age";
a3.group = "age";
onRadioReady = function(rID) {
if(rID == a2)
a2.select();
};
}

Remember: there are three UI Radio Buttons in the file.

We have some more ease here; when we have only one group of UI Radio in our
movie, there is no need to assign them group, because the UI Radio’s which are not
149

assigned group are considered of default unnamed group, and they work perfectly as
one group. Grouping of UI Radio objects is used when we have many radios in the
movie in same path but of different groups.

See the code of file UICO_08.swi in main timeline, which is almost similar to the
one in file UICO_06.swi but only difference is, we did not assign the UI Radio
objects any group.

onLoad() {
a1.caption = "Under 18";
a2.caption = "Exact 18";
a3.caption = "Over 18";

onRadioReady = function(rID) {
if(rID == a2)
a2.select();
};
}

Explanation of above code:

onLoad() { event handler ‘onLoad’ of main timeline


a1.caption = "Under 18"; Set caption of UI Radio named ‘a1’
a2.caption = "Exact 18"; - do -
a3.caption = "Over 18"; - do -

onRadioReady = function(rID) { event handler ‘onRadioReady’ for UI Radio’s, this


event is invoked/fired when a UI Radio is
completely loaded into memory and is ready to
take any action. Where ‘rID’ is the variable
(which may be of any name), which fetches out
the path of UI Radio became ready recently.
if(rID == a2) comparing variable ‘rID’ with UI Radio ‘a2’, if
they are equal, it means UI Radio ‘a2’ I
completely loaded into memory and ready to
operate. Now, if UI Radio ‘a2’ is ready, then,
a2.select(); select it within the group of UI Radio’s. this is
almost similar function to the one available for UI
CheckBox as ‘check()’, but operates differently
according to the nature of object.
}; close code block of event handler ‘onRadioReady’.
} close code block of event handler ‘onLoad’

Further study on event ‘onRadioReady’

This event is invoked/fired/generated/released by the UI Radio buttons in their


parent path only. E.g. there are 5 radio buttons (may of different groups) in a sprite
‘x’, the event ‘onRadioReady’ will be available within sprite ‘x’ only. Furthermore if
you wish to implement it within another path such as main timeline ‘_root’, you will
do as:

onLoad() {
150

x.onRadioReady = function(radioID) {
take_some_action
};
}

Utility Functions to operate a UI Radio Collection Object

setCaption(newCap) change caption (display text) of UI Radio,


where you can also change it using
‘caption’ property.
enabled(true_false) disable or enable, so that, if UI Radio is
disabled, it is no more clickable by user.
select() select any UI Radio from a group, and
unselect previously selected
unselect() remove selection
getValue() to check either UI Radio is selected or not,
if it is selected the function returns true
and false otherwise.
getState() to check either UI Radio is enabled or
disabled, if enabled (by default), the
function returns true and false otherwise.
setBgColor(newCol) change background color to ‘newCol’ a
hex value
setSelectionColor(newCol) change the background color when mouse
is over the object
getWidth() current physical width of the UI Radio
object
getHeight() current physical height of the UI Radio
object
getX() get current X coordinates
getY() get current Y coordinates
moveTo(x,y) move to specific location on stage
moveBy(x,y) increase X and Y coordinates and move on
stage
setWidth(newW) change background and selection width
remove() destroy the object from movie as well as
from memory.
getGroup() get name of group the UI Radio is
associated with (function return string)
setGroup(group_name) change or set group of a UI Radio
getId() get sprite name of a UI Radio (function
returns name as string data)

NOTE : to get height or width of the UI Radio or UI CheckBox object, use function
getHeight() and getWidth() not usual properties _height and _width which may
report wrong values.

Additional Events for UI Radio Collection Object

onDisabled event invoked/fired when a UI Radio is


disabled through function ‘enable(false)’
151

onEnabled event invoked/fired when a UI Radio is


Re-Enabled through function ‘enable(true)’
onClicked event invoked when a UI Radio has been
clicked by user, regardless the information
either it is selected or not.

See the example of multiple groups working at a time, implemented in file


UICO_09.swi. Here is the preview of the file running in player:

UI Menus

UI Menu Object is the most sophisticated source for runtime menu creation.
Design and colors of the UI Menu can be altered only within SWiSHMax environment
(not at runtime), but extension (adding main and sub menus) is done at runtime
(through script). UI Menu Collection object does not allow to add hierarchical menus.
It supports checked menu items (to work as checkbox), and option menu items (to
work as radio buttons) as well. You can add unlimited number of main and sub
menus (at runtime) simultaneously. File UICO_10.swi contains first sample of UI
Menu example. Here is the preview of the example:

How to insert UI Menu in my SWiSHMax project?

Open file UICO_10.swi, copy sprite ‘UIMenu’ and paste it in your SWiSHMax
project; that’s it.
Let us have a view over the code to generate menus at runtime. Following code is
from example file UICO_10.swi:

onLoad() {
UIMenu.onReady = function() {
menu1 = UIMenu.addMenu("Menu 1","main1");
152

menu2 = UIMenu.addMenu("Menu 2","main2");


};
UIMenu.onMenuReady = function(menu) {
switch(menu){
case menu1 :
menu.addItem("I am Menu Item 1","item1");
menu.addItem("I am second Item","item2");
menu.addSeperator();
menu.addItem("Last Menu Item","item3");
break;
case menu2 :
menu.addItem("Item1","i1");
menu.addItem("Item2","i2");
menu.addItem("Item3","i3");
}
};
}

Explanation:

onLoad() { event handler ‘onLoad’ of main


timeline
UIMenu.onReady = function() { implement event handler ‘onReady’
for UI Menu collection Object Sprite
‘UIMenu’. This event is
fired/generated automatically when
a UI Menu object is 100% loaded
into memory and is ready to
operate. When it is confirmed that
UI Menu sprite is ready, then,
menu1 = UIMenu.addMenu("Menu 1","main1"); Create a top-level menu (main
menu) using function ‘addMenu’ in
our SWiSH movie. And create a
pointing variable ‘menu1’, through
which we will access the menu
later. Where ‘Menu 1’ is the caption
displayed and ‘main1’ is the unique
name/id of the top-level menu.
menu2 = UIMenu.addMenu("Menu 2","main2"); Create another top-level menu and
to assign pointer ‘menu2’.
}; closing block for event handler
‘onReady’
UIMenu.onMenuReady = function(menu) { implementation of event handler
‘onMenuReady’ of UI Menu. This is
another event handler
‘onMenuReady’ which is
fired/generated/released when a
top-level menu I ready to accept
further sub-menu items. It
provides the absolute path of the
top-level menu item sprite (created
at runtime), which is ready to
accept further sub-menu items.
153

Path of the ready item is obtained


from the argument ‘menu’. Now,
when it has been confirmed that
any of the top-level menus is read
to accept sub-menus, then,
switch(menu){ keep a check on value of ‘menu’
(which contains path to ready
item)
case menu1 : if ready menu is ‘menu1’ (that is
pointer to first top-level Menu 1),
then,
menu.addItem("I am Menu Item 1","item1"); add sub-menu/item to currently
ready top-level menu, using
function ‘addItem’. Where ‘I am
Menu Item’ is the caption to be
displayed, and ‘item1’ is the unique
name of the item added, through
which we can access it directly.
Note : names of the sub-
menus/items may be similar in
different top-level menus.
menu.addItem("I am second Item","item2"); do the same, add new sub item
menu.addSeperator(); add a separator, a normal line
under the last inserted sub-menu,
so that the next menu seems to be
separated by a line from other
items, using function
‘addSeparator’.
menu.addItem("Last Menu Item","item3"); do add another sub menu.
break; break the ‘switch’ statement so
that it does not execute code
following to current code.

case menu2 : Now, if top-level menu ‘men2’ is


ready, operate the same way, and
menu.addItem("Item1","i1"); and do add the sub menu items.
menu.addItem("Item2","i2");
menu.addItem("Item3","i3");
} close the ‘switch’ block
}; close ‘onMenuReady’ event handler
block.
} close ‘onLoad’ event handler block.

How to know which item has been clicked?

Very simple, there is an event handler ‘onClick’ available for this purpose. Open file
UICO_11.swi and see only first 4 (four) lines of code, which are:

Code and explanation:

UIMenu.onClick = function(id) { implement event handler ‘onClick’, which


is fired/generated when a sub menu is
clicked. This function also provides us the
154

id of the last clicked item, variable ‘id’ is


used to track the clicked item id.
msg = "Item clicked " + id; ‘msg’ is a variable attached to a dynamic
text box. So, change the value of variable
‘msg’ to the “some text” and object id,
which will directly be displayed on the
textbox.
}; closing block of event handler ‘onClick’.

Run the example in player yourself, click any of the sub menus, and see the text
being changed in the textbox (through the event handler). When you click the last
item in first top-level menu, the out put in text box is:

Can I disable and then re-enable a sub-menu item, if yes then HOW?

YES.

In this case, you need to remember sub-menu items’ ids, or assign then to some
pointing variables directly or using function ‘getItem’ or ‘getItemById’. For example,
we need to disable the first sub-menu item in menu1, we will use

Direct method 1:
While creating menu items, create pointing variables, such as:
item1=menu.addItem("I am Menu Item 1","item1");

then use,
item1.disable();

Direct method 2:
menu1.getItem(1).disable();

or

Direct method 3, through ID:


menu1.getItemById(“item1”).disable();

or

Indirect method, through pointing variable:


item = menu1.getItem (1);
item.disable();

there are variety of ways you can access the sub-menu items. See example
UICO_12.swi, where we are disabling a sub-menu item via button on(release)
event handler. Code of button is:

on(release) {
item1.disable();
}
155

remember, id of sub-menu ‘item1’ was crated while creation of sub-menu items.


See output before clicking button ‘Disable first item of Menu 1’:

And see the preview, after button has been clicked, and the menu item has been
disabled (after being disabled, first item is no more clickable via mouse):

How to enable a disabled sub-menu item?

Use the same method to adopt the id of the sub-menu item then use function
‘enable’, here is the example:

on(release) {
item1.enable();
}

Let us move to a bit advanced use of the UI Menu Collection Object. In next example
we will create a top-level menu and add check items to it (to act as checkbox), using
function ‘addCheckItem’ instead of ‘addItem’. Open example file example
UICO_13.swi, and see the code.

Here is the screenshot of above example:

Practically function ‘addCheckItem’ receives 3 (three) arguments as follows:

menu.addCheckItem( item_caption, item_id [,default_checked]);

where ‘item_caption’ is the string/text to be displayed, ‘item_id’ is the unique name


of the item, the last argument ‘default_checked’ is of boolean type and is optional. If
you do not pass this argument and let function work with 2 (two) arguments, well
and good, the function will consider it false by default; And if you pass ‘true’ or any
positive integer value as last argument, the newly added sub-menu will be checked
by default (as shown above). So the code in file is:

Script and Explanation:


156

menu.addCheckItem("Check Item","item1",true); Add new menu item of type


checkbox, where ‘item1’ is
its unique id, and last
argument ‘true’ is passed
to have it checked by
default.
menu.addCheckItem("Check Item2","item2"); add new item, the same
way, but keep it unchecked
by default. Note: we
ignored/did not pass the
last (third) argument, so
that, it is considered false.

Test the movie and note that items added using this function ‘addCheckItem’ act a
as usual checkboxes and are once checked and unchecked on second click I they are
enabled.

How to know which item has been checked or unchecked through use click?

There are two events available to track checkbox type menu items behavior,
‘onCheck’ and ‘onUncheck’. Open example file UICO_14.swi, and see the
implementation of these event handlers, which is almost same to the one ‘onClick’
we already discussed in recent topic. See the following is the preview of the textbox
when an item is unchecked:

Code to implement the event handlers ‘onCheck’ and ‘onUncheck’:

UIMenu.onCheck = function(id) {
msg = "Item CHECKED " + id;
};
UIMenu.onUncheck = function(id) {
msg = "UNCHECKED " + id;
};

I hope you understand it very clearly if you have read the previous topic on
implementation of ‘onClick’ event handler. This type of items are useful when you
want to allow the user to enable or disable specific options in your SWiSHMax
application (at runtime). NOTE: checkbox type items are disabled and re-enabled the
same way other items are dealt.

Adding Radio Type UI Menu sub-menu items:

Another advance use of UI Menu is to add Radio type sub-menu items (at
runtime). As we previously studied the behavior UI Radio buttons, these act almost
the same but can contain single group under on top-level menu (where you cannot
define group, group is automatically defined as default). So that, they act as radio
buttons’ group, when one item is selected the others remain unselected, similarly
when some unselected is selected (by user click), the last selected is automatically
157

unselected. See the preview of radio type menu items (example from file
UICO_15.swi); Run this example and test yourself. You will see as following, that,
the a small radio circle with previously selected menu item has been removed, and is
currently with the second menu item:

After user click on second menu item:

Ok, how to add radio type sub-menu items? What is specific function to do this?

Use function ‘addRadioItem’ to add radio type menu item. This function takes
3 (three) arguments, 1st: caption of the item, 2nd:unique name/id of item, and 3rd:
default selected. If third argument is ignored, it is considered false. Passing ‘true’ or
any positive integer value as third argument, turns the item to be default selected
under the radio’s in current top-level menu. See the code:

menu.addRadioItem("Radio Item 1","item1",true);


menu.addRadioItem("Radio Item 2","item2");

Now you must be thinking about tracking the behavior of this type of items, to know
which one is clicked and selected, and which one was previously selected (which is
currently unselected).

Events to capture for radio type items:

For this purpose, we have two events ‘onSelect’ and ‘onUnselect’, which may
be implemented as handlers, according to our needs. Both of events do provide us
the id of the item as well. Open example file UICO_16.swi, and see the code where
we have created two textboxes (and attached two variables ‘msg’ and ‘msg2’ to
them) to display id of selected one as well as the unselected one:

Code is:

UIMenu.onSelect = function(id) {
msg = "SELECTED : "+id;
};
UIMenu.onUnselect = function(id) {
msg2 = id + " is UNSELECTED";
};
158

where ‘id’ is the name/id of currently selected/unselected item. And here is the
preview of movie when second item is clicked by the user:

NOTE: remember, item may be of any type (check, radio, or simple), it produces
event ‘onClick’ in the environment when it is clicked by the user, but two additional
types (check, radio) produce ‘onCheck’, ‘onUncheck’, ‘onSelect’, and ‘onUnselect’.

Additional functions for top-level menus to enable, disable, change width etc:

menu=UIMenu.getMenu(1); Create pointing variable for first top-level


menu
menu=UIMenu.getMenuById(“meu1”); Create pointing variable for a top-level
menu, obtain path by the id/name you
gave it while creating.
menu_id.disable(); To disable a top-level menu
menu_id.enable(); And to re-enable

menu.setHeadWidth(newW); change the width of the top-level menu


heading area
menu.setPanWidth(newW); change the width of sub-menus container
area
menu.incPanWidth(nNum); increase the width of sub-menus container
area (by pixels)
menu.openMenu(); unconditional opening of the top-level
menu
menu.closeMenu(); unconditional collapse of the top-level
menu
menu.getX() obtain X coordinates of a top-level menu
menu.getY() obtain Y coordinates of a top-level menu
menu.getWidth() obtain width of a top-level menu (do not
use _width property)
menu.getHeight() obtain height of a top-level menu (do not
use _height property)

NOTE: Disabling a top-level menu means to disable entire drop down items list as
well.
159

Test the example file UICO_17.swi in player; example is using functions


‘setPanWidth’. Here is the preview o the movie:

Additional Events for top-level menus:

UIMenu.onClose(id) A top level menu has been closed, ‘id’ is


the menu id/name
UIMenu.onExpand(id) A top level menu has been
expanded/opened, ‘id’ is the menu
id/name

UI Combo Box

This object provides you a big ease to create drop down list (at runtime)
within seconds. It has variety of functions to manipulate overall UI Combo object,
and many more events to track behavior of UI Combo at each point of execution. UI
Combo works in two different ways, it is capable of working as a usual combo box as
well as a list box where user does not need to drop the list and select (all the items
are visible to select from). UI Combo automatically become dragable when it is
turned to list box style. You can switch between these two styles at runtime, even
allow user to switch to desired style. You can turn ON or OFF the dragging and style
switching for user, and do all of it initially.

Our first example for UI Combo Collection Object is contained in file UICO_18.swi,
its preview is as follows (after you click on the dropper button on right of the
combo):

You can copy and paste sprite ‘UICombo’ in your SWiSHMax project and utilize it.
160

Where code in the main timeline is:

onLoad() {
UICombo.onReady = function() {
UICombo.addItem("I am Item 1","item1");
UICombo.addItem("I am Item 2","item2");
UICombo.addItem("I am Item 3","item3");
UICombo.addItem("I am Item 4","item4");
UICombo.select(2);
};
}

How to insert a UI Combo in my SWiSHMax project?

Simply copy the sprite ‘UICombo’ from any of the UI Combo examples and paste in
your SWiSHMax project on desired position.

Explanation:

onLoad() { ‘onLoad’ event handler of main timeline


UICombo.onReady = function() { implementation of handler for event
‘onReady’ of UI Combo, which is
fired/generated when a UI Combo is fully
loaded into memory and is ready to
accept new items and further
manipulations. So, when it is fully loaded
into memory and ready, then,
UICombo.addItem("I am …… Add new item to UI Combo using function
‘addItem’, where first argument is the
caption/label of the new item and second
argument is the unique id/name of the
newly inserted item.
UICombo.addItem("I am …… do the same to add further item.
UICombo.addItem("I am …… -do-
UICombo.addItem("I am …… -do-
UICombo.select(2); set default selected item number 2 (two)
in UI Combo list using function ‘select’.
Number of an item is the physical
appearance of it in the list.
}; closing block for event handler ‘onReady’
} closing block for event handler ‘onLoad’

You can add unlimited number of items to a UI Combo Collection Object (at runtime
only). UI Combo allows some modifications in design and layout at runtime, rest of
the design, color, layout, and/or font must be altered within SWiSHMax environment.
161

Now, a problem appears, e.g. you have 100 entries to be added to a UI Combo; of
course it will get larger in height and will not fit your design.

What to do in this regard?

We have a function ‘setSize’ available to fix the length of a UI Combo upto


specific number of items. This function accepts only one argument as number of
items to be shown at once. After the size has been set, there is a scrollbar added to
UI Combo automatically. Open file UICO_19.swi, which contains such example, in
this example, we order the combo to show only 3 (three) items at a time, so that
rest of the items are visible through scroll. The code of example contains only one
different line at almost end: ‘UICombo.setSize(3);’ which is used to set the constant
size of the UI Combo. So that, the preview will be as shown below (after expansion):

How to remove the size limitation?

Use function ‘removeSize’, as:


UICombo.removeSize();

How to add new Items at runtime?

Use function ‘addItem’ to add new entries to a UI Combo.

Repeated Example:

UICombo.addItem(“Label of New Item”, “item1”);

Explanation:

Argument 1 (one) ‘Label of New Item’ is the caption/label/text of the new item,
where argument 2 (two) ‘item1’ is the unique name/id of the new item to be added.

How to track the clicked item?

We have an event ‘onClick’ which is fired/generated when an UI Combo item


is clicked. We can implement this event as handler according to our needs. Event
‘onClick’ gives us the id of the last clicked item’s complete path, through which we
can negotiate the item individually. Much better way to recognize the clicked item,
we do create pointing variables for all items while adding them. Open file
UICO_20.swi, and see the code in main time line. We have only two UI Combo
entries, 1.Play Animation, and 2.Stop Animation. There is a sprite ‘animation’ in our
movie, which is played and stopped according to the UI Combo item select. First run
162

the example and test it through selecting UI Combo entries. Note that, the animation
will stop and play according to the item select. Here is the preview of the move,
running in player:

First of all see the pointing variables ‘p1’ and ‘p2’ we have created, while adding the
items:

p1=UICombo.addItem("1.Play Animation","item1");
p2=UICombo.addItem("2.Stop Animation","item2");
now move onto the implementation of the ‘onClick’ event handler:

Code and Explanation:

UICombo.onClick = function(ID) { Implementation of event handler ‘onClick’


of UI Combo, where ‘ID’ is the absolute
path of the item sprite recently clicked.
if(ID == p1) if path of the clicked item is equal to path
of item1 ‘1.Play Animation’, then,
animation.play(); play the sprite ‘animation’
else if(ID == p2) else if the path of clicked item is
same/equal to path of item2 ‘2.Stop
Animation’, then,
animation.stop(); stop the animation in sprite ‘animation’
}; closing block of event handler ‘onClick’

Note: You can also get the last clicked/selected item using variable ‘selected’, as:

if(UICombo.selected == p1) ……

How to have a UI Combo default expanded/opened?

Use function ‘expand’ to have a UI Combo default opened, example implemented in


next file:

UICombo.expand();

How to get an item from a UI Combo to operate on?

There are two built-in functions ‘getItem’ and ‘getItemById’ when give you direct
access to an item individually. In next example, we will get access to first item and
change its caption to ‘CHANGED’, through property ‘caption’ (all at runtime).
Example is in file UICO_21.swi.

See preview of example. Note: the caption of first item has been changed to
163

‘CHANGED’ after the button click.

Code on Button Object found in example, that is used to change caption of first item:

on(release) {
item = UICombo.getItem(1);
item.caption = "CHANGED";
}

Explanation:

item = UICombo.getItem(1); create pointing variable for item No. 1


item.caption = "CHANGED"; assign new caption through property
‘caption’

which may also be implemented through function ‘getItemById’, as:

item = UICombo.getItemById("item1"); create pointing variable for item No. 1


item.caption = "CHANGED"; assign new caption through property
‘caption’

Direct methods without use of pointing variable:

UICombo.getItem(1).caption = "CHANGED";
or
UICombo.getItemById("item1").caption = "CHANGED";

Disabling and Enabling a UI Combo item:

Disabling mean, stop user access to click the item. Combo level Functions
‘disableItem’, ‘disableItemById’ and ‘enableItem’, ‘enableItemById’ are used for this
purpose.

Example from file UICO_22.swi:

1.Direct methods:
UICombo.disableItem(1);
UICombo.disableItemById("item2");

Use the same to enable the disabled items:

UICombo.enableItem(1);
UICombo.enableItemById("item2");

2.Disabling and enabling through direct access to an item:

UICombo.getItem(1).disable();
UICombo.getItemById("item2").enable();
164

Note: if you want to disable or disable an item through direct access to an item, use
functions ‘enable()’ and ‘disable()’. These two functions have different functionality
on combo level.

See the preview of above example. Note, the first item has been disabled, when
button (at bottom) is clicked.

Disable and Enable UI Combo completely:

To disable, and re-enable a complete UI Combo use functions ‘enable’ and ‘disable’,
so that user cannot perform any operation over it (through mouse). Example of it is
in file UICO_23.swi. test through clicking the buttons at bottom o the movie.
function ‘disable’ disables a UI Combo on the position wherever it was previously.
See the preview of the example, after it has been expanded and then disabled:

Stop a UI Combo to accept more items:

This is another feature of UI Combo. It allows you to stop your UI Combo to not to
accept more items at a certain point. This functionality is performed by combo level
functions ‘lock’ and ‘unlock’. Such as:

UICombo.lock(); from now on, do not accept anymore entries


UICombo.unlock(); start accepting new entries from now on

UI Combo Style switching at runtime (using UI Combo as List Box)


165

Style switching is one of big features of UI Combo, where you can turn your UI
Combo box to a List box. By default the user can switch between 2 (two) styles
(combo, listbox) by clicking the small button on top-left corner of the UI Combo, so
that, it does not remain a UI Combo anymore after being switched to style listbox.
Test the example file UICO_24.swi. and click the small button in top-left corner of
the UI Combo, as shown below:

You will notice that, your UI Combo is turned into a full functional list box and the
dropper button (which was on top-right corner of UI Combo) is automatically
disappeared; as sown below:

You can switch the mode through script as well. See example file UICO_25.swi.

Extra code line in example and its explanation:

UICombo.setClipable(true);

function ‘setClipable’ is used to switch between styles and accepts only one
argument of boolean type. If ‘true’ or a positive integer value is passed as argument,
your combo is turned to a listbox, and if ‘false’ or <= 0 (zero) negative value is
passed, it is restored original layout.

Note: the combo turned to a listbox style, and became dragable too; you may drag
the listbox by clipping it from title.

Now for example, you do not want to allow the user to switch between modes, and
set a default mode for him/her to work with. Use function ‘allowUserClipping’ to turn
style switching ON or OFF. Open example file UICO_26.swi. run the example and
see, that, you cannot find the button (on top-left corner of UI Combo) which allows
you to switch between styles.

Code to set style switching OFF (false):


UICombo.allowUserClipping(false);

Similarly the code to set style switching ON (true):


UICombo.allowUserClipping(true);
How to make a UI Combo non-dragable?

You may also want to disable the dragging of the control for user. If you wish to plan
such, use function ‘setDragable’, and pass it boolean value ‘false’ as argument to
166

disable the dragging, pass ‘true’ otherwise (default is true), see example code taken
from file UICO_27.swi:

UICombo.setDragable(false);

UI Toolbars

UI Toolbar Collection Object provides you ease to create a set of icons within
a dragable/resizable interactive toolbar. You can add shortcut icons to a UI Toolbar
at runtime. It has some events to work with, which allow you to capture the behavior
of a UI Toolbar at runtime, and some functions to manipulate a UI Toolbar. You can
also add separators to make icon groups, as well as add tag to create drag area.
Note: UI Toolbar is only dragable horizontally. For now, there are only 10 (ten)
different icons have been embedded into the control, you can embed further icons
yourself (procedure will be demonstrated in upcoming discussions).

How to insert a UI Toolbar in your SWiSHMax project?

Copy the sprite ‘UIToolbar’ from any o the relevant examples and copy in your
SWiSHMax project.

Our first example of UI Toolbar is implemented in file UICO_28.swi (preview):

Run the example and test it.


Now, come to the code in main timeline (explanation):

onLoad() { event handler ‘onLoad’ of main timeline


UIToolbar.onReady = function() { implementation of handler for event
‘onReady’ of UI Toolbar object, which is
automatically generated/fired when a UI
Toolbar is ready to operate. Now, when it
is ready to operate,
with(UIToolbar) { use ‘with’ statement to access inner
functions and properties of the sprite
‘UIToolbar’.
addTag(true); add a new Tag using function ‘addTag’,
from where user can drag the whole
toolbar. Value ‘true’ is passed as
argument, which means the new added
tag is dragable, pass ‘false’ otherwise.
This is tag area:
167

addButton("b1","screen"); add new button to the UI Toolbar, using


function ‘addButton’. This function
requires 2 (two) or 3 (three) arguments
(all are string type). Where the first
argument is the unique id/name of the
button through which we can access it
individually, 2nd argument is the
embedded icon name.
Names of Embedded Icons:
cd, folder, document, screen, setup, globe, help, tip, documentblue, and folderblue.

addButton("b2","folder"); -do- (add another button)


addButton("b3","document"); -do- (add another button)
} closing block of ‘with’ statement
}; closing block of event handler ‘onReady’
} closing block of event handler ‘onLoad’

Note: If third argument of function ‘addButton’ is ignored it does not set any ToolTip
for the added button. Your can also set custom ToolTip text to buttons in a UI
Toolbar, while adding the buttons.

Adding a button with ToolTip:

addButton( button_id, icon_name [, tooltip_text]);

See example UICO_29.swi of UI Toolbar where we have added ToolTip to each


button. Here is the preview of the file, a ToolTip (‘Go to Home’) is shown when
mouse cursor rolls over the first button:

Here is the code in main timeline:


addButton("b1","screen","Go to Home"); 3rd argument passed, so, ToolTip
set for this button.
addButton("b2","folder","Open Document"); -do-
addButton("b3","document"); We did not pass 3rd argument, so
that, the ToolTip will not be set for
this button.
168

Separate Buttons by adding separator:

See example UICO_30.swi of UI Toolbar, where we have 4 (four) buttons; 2 (two)


groups (each of 2 buttons) are separated with a separator in between them:

Separator

See the code (extra line) in main timeline and it explanation:

addSeparator(); Function ‘addSeparator’ of UI Toolbar that allows


to add new separator between button. It accepts
no argument at all. Simply call it the way it is
shown.

Resizing the width of the UI Toolbar:

User can resize the UI Toolbar at runtime, by using the button in right most corner of
the UI Toolbar, as shown below (highlighted in green border):

Try resizing the UI Toolbar from this button (at runtime) yourself by running any of
the examples provided for UI Toolbar.

Resizing the width of the UI Toolbar through script:

You must be looking for a way to resize a UI Toolbar yourself, so that, an initial
width of the UI Toolbar is set when user starts using it. There is a function ‘setWidth’
which allows you to resize a UI Toolbar through script at runtime. This is
implemented in example file UICO_31.swi.

See the additional code line:

setWidth(280); set the width of UI Toolbar to 280 pixels

After running it, you will notice that the width of the UI Toolbar is large by default.
As shown here:

Adding additional non-dragable tags within the UI Toolbar:


169

e.g. To make the UI Toolbar more cool, you wish to add more tags to it instead of
separators. See the file UICO_32.swi that contains example of additional tags in a
toolbar (preview):

See the code (addition line) ‘addTag(false);’, which adds a new tag, but due to the
argument passed ‘false’, the UI Toolbar is not dragable from the send tag.

Disable and re-Enable a UI Toolbar for the user:

You can also disable a UI Toolbar by using function ‘disable’, so that, the user cannot
perform any operation over it through mouse. Run the example file UICO_33.swi
and click the button ‘Disable UI Toolbar’. You will notice that after clicking this button
the UI Toolbar is no more clickable and no more dragable, and has been faded
something like this:

The code for button to disable is:

on(release) {
UIToolbar.disable();
}

and to re-enable the UI Toolbar click the button ‘Enable’ which will enable the UI
Toolbar, the code for this button is:

on(release) {
UIToolbar.enable();
}

Let use move to core discussion of events to capture when a button in UI Toolbar is
clicked.

Tracking the clicked button in a UI Toolbar:

An event ‘onClick’ is generated/fired when a button of a UI Toolbar is clicked by the


user. Now we can implement this event as handler according to our needs. Our first
example of UI Toolbar event capture is implemented in example file UICO_34.swi
which gives is the id of the button clicked, so that, we can take specific action on
specific button click.

Implementation of ‘onClick’ event handler:

See last few lines:


170

UIToolbar.onClick=function() { implement a handler for event ‘onClick’,


now, when event has been fired, let us
write the code to be executed.
msg=UIToolbar.lastID; get the id of the last clicked button from
variable ‘lastID’ of UI Toolbar (‘UIToolbar’
sprite), and assign it to the variable ‘msg’
which is attached to a dynamic textbox.
};

Now run example and notice the value of the textbox is changed according the
button click from the UI Toolbar.

Move to a bit advanced example, run/test file UICO_35.swi that contains a simple
animation which is controlled through the UI Toolbar buttons. 1st button is used to
play the animation and second button is being used to stop the animation. Here is
the preview of the movie:

Let us see the code in main timeline that is controlling the events of button click:
With Explanation:

UIToolbar.onClick=function() { implement handler of event ‘onClick’ of UI


Toolbar
id=UIToolbar.lastID; get the id/name of the last clicked button and
save it in a new variable ‘id’, it may also be as:
‘id=UIToolbar.getLastClicked();’
if(id eq "b1") now, if the last clicked button id is equal to ‘b1’
then,
animation.play(); play the timeline of sprite ‘animation’
else if(id eq "b2") otherwise if the last clicked button’s id then,
animation.stop(); stop the playing sprite ‘animation’
}; closing block of event handler ‘onClick’

Additional Function to manipulate a UI Toolbar:

setTooltipText(bID,bText) set Custom ToolTip text of a button at runtime,


where you replace ‘bID’ with button id and
‘bText’ with the new ToolTip text.
171

removeTooltipText(bID) remove the ToolTip text from a button (if set)


getButtonById(bID) get access to button directly, where ‘bID’ is the
button id
disableButon(bID) disable a single button in UI Toolbar.
getWidth() get current width of the UI Toolbar in pixels
(don’t use _width property which may respond
wrong)
totalItems() get number of buttons in a UI Toolbar.

Additional Event for UI Toolbar:

onStartDrag event fired/generated when UI Toolbar is started


being dragged by the user
onDragged event fired when UI Toolbar has been placed
somewhere after dragging
onStartResize event fired when UI Toolbar is started being
resized
onResize event fired when UI Toolbar is being resized
onResized event fired when UI Toolbar has been resized
onButtonAdded event fired when a new button is added to UI
Toolbar.

UI Spreadsheet

This sophisticated allows you to add full functional spread sheets to your
SWiSHMax projects. Where you can control almost everything of the UI Spreadsheet.
This is the 2nd biggest UI Collection Object after UI Menu. You can add unlimited
number of Columns and Rows at runtime. User can select individual row/column,
resize columns, select data cell, and alter cell values etc. All of the UI Spreadsheet
functions are controlled through script, where the developer can allow or disallow
some or a set of functions to user. Colors, font, and other layout options can be
altered from within SWiSHMax environment except some of the functions which allow
alteration through script at runtime. Note: this version does not support formulas
(such as sum, avg, etc) that are usually available in Spread Sheet software such as
Microsoft Excel. Here is the preview of a normal UI Spreadsheet:

How to insert a UI Spreadsheet in my SWiSHMax project?

Open any of the examples of UI Spreadsheet, such as UICO_36.swi, copy the sprite
‘UISpreadsheet’ and paste in your SWiSHMax project file.

Getting started with UI Spreadsheet:


172

To get started with this Collection Object, first, we must know some
functioning structure of the UI Spreadsheet Collection Object. UI Spreadsheet works
like a normal spread sheet built up of columns and rows, where Each cell may
contain different value from others. As in other spread sheet software, you cannot
insert a new single cell, but new column and/or new row. You can also name the
head tags of the columns to specify the data contained in specific column’s cells.
Through these tags you can select entire column at a time. There is also one tag
available for each inserted row, through which you can select entire row. Each
column is also selectable individually through user click. The developer can get the
data from selected or unselected cell, column, or row through script and process it
according to your project requirements. This type of control can be used to develop a
site for school results, employee sales/payroll program, or polling and user ranking
systems etc.

There is no limit for number of columns and/or rows, it is dependant upon the
memory and power of user’s computer either it can handle a huge UI Spreadsheet or
not. Usually it does not take much memory, but its examples are tested on Pentium
IV processor, and worked perfectly with huge number of columns and rows. The
columns are resizable at runtime, so that, the user can view the data the way s/he
feels comfortable.

Let UI Spreadsheet get started with examples and code. Our first example is
contained in file UICO_36.swi.

Code of main timeline and its explanation:

onLoad () { event handler ‘onLoad’ o main timeline


UISpreadsheet.onReady = function() { implementation of the handler for event
‘onReady’ which is fired/generated
automatically when a UI Spreadsheet is
fully loaded into memory and is ready to
accept operations.
UISpreadsheet.addColumn("Name"); Add a new Column to the UI Spreadsheet,
using function ‘addColumn’, where
"Name" is the caption of the new column
to be added (caption is shown over the
head of column)
UISpreadsheet.addColumn("Email"); Add another column with head "Email"
UISpreadsheet.addRow(); Add new Row to the UI Spreadsheet,
using function ‘addRow’ which does not
take any argument.
UISpreadsheet.addRow(); -do- add one more Row
}; closing block of event handler ‘onReady’
} closing block of event handler ‘onLoad’

Note: It does not matter, if you add Rows before adding Columns.

Changing the value of a cell:


173

Here we demonstrate you the function ‘getCell’, which returns the path of a cell we
can operate upon. Open file UICO_37.swi and press button ‘Change value at 1,1’,
you will notice that the value of the cell at row:1 and column:1 has been changed to
‘Ali’. After the example has been run, and the button has been clicked by user, the
value of the cell at row:1 and col:1 is changed to ‘Ali’. See the preview:

Let us view the code, that is used to alter the value of cell:
Following is the script for button (implementation of on release event handler)

on(release) {
mycell=UISpreadsheet.getCell(1,1);
mycell.value="Ali";
}

Explanation:

on(release) {
mycell=UISpreadsheet.getCell(1,1); function ‘getCell’ is used to get direct
access to a specific cell. New variable
‘mycell’ is assigned and is pointing to the
specific cell we obtained through ‘getCell’
function of UI Spreadsheet.
mycell.value="Ali"; Assign a new value to the cell through its
property ‘value’
}

This operation may also be done through a shortcut method as:

UISpreadsheet.getCell(1,1).value="Ali";
174

Can user alter/change the values of cells:

Yes, the user can alter the values by clicking on the cell and alter the value through
a popup input text. Run the previous example again and click on any of the cell; you
will notice that, an input box appears on the top-left corner of sheet, as shown
below:

Above shown popup input textbox has 2 (two) buttons attached with it on the right
corner. The button on top is used to close/hide the textbox, and second button
(lower one) may be clicked to clear the field. While altering/typing the value you will
also notice that, the value of selected cell is also being changed exactly as the typed
text. This feature is to provide an ease to the user to edit the UI Spreadsheet data
him/herself. But you have the full control over this Collection Object, where you can
turn user editing ON or OFF. How?

Turning the user editing ON/OFF:

By turning user editing OFF, the user is no more able to modify the data/values of
the cells, although s/he can select the cells as in normal mode. Open file
UICO_38.swi, run the example, and select any of the cells by clicking over it. You
will notice that, there is no input box appearing anymore. How did we do that?

See the code we used to disable the user editing option (explanation):
There is an additional line of code in the main timeline, as:

UISpreadsheet.setEditable(false); use the function ‘setEditable’ to turn the user


editing OFF by passing the argument value
‘false’.

Now if, at a certain point you wish to turn the user editing ON, simply use the
function ‘setEditable’ but pass the boolean value ‘true’, which will enable the user
editing, as here:

UISpreadsheet.setEditable(true);

How to get the value of currently selected cell?

For this purpose we have an event ‘onSelect’, which is invoked when a single cell is
selected. Open example file UICO_39.swi which contains the implementation of
handler for event ‘onSelect’, run it, and select any of the cell (suppose you selected
cell at col:1 and row:1), note the textbox at bottom of movie contains the value of
the selected cell:
175

See the code that contains the implementation of handler for event ‘onSelect’:
Almost last 4 (four) lines in the main timeline of example:

UISpreadsheet.onSelect = function() {
mycell=UISpreadsheet.selectedCell;
msg=mycell.value;
};

Explanation:

UISpreadsheet.onSelect = function() { implementation of the handler for event


‘onSelect’ which is invoked/fired when a
cell is selected by the user through mouse
click.

mycell=UISpreadsheet.selectedCell; Get the currently selected cell from the UI


Spreadsheet from its property
‘selectedCell’, and assign it to a new
variable ‘mycell’, so that, we would access
the selected cell directly through variable
‘mycell’ (mycell is the pointing variable).

msg=mycell.value; get the value of selected cell through its


property ‘value’ and assign the to variable
‘msg’ which is attached to a dynamic
textbox _msg.

}; closing block of the event handler


‘onSelect’

How to alter the value of priorly selected Cell?

Simply, get access to currently selected cell through property ‘selectedCell’ of UI


Spreadsheet and alter the cell property ‘value’ through it, as:

UISpreadsheet.selectedCell.value = 1500;
176

How to get access to/obtain value of each cell of a specific column?

Logically a column may contain 1 (one) or more cells in it, so that, the values of the
cells may not be obtained as a single value. So we put all the values of cells
sequentially into a data Array. The function ‘getColumnValues’ returns an array
containing the values of all cells within a column of UI Spreadsheet. I hope you
remember the use of Arrays, we already studied in depth. Open file UICO_40.swi
which contains the example of obtaining data from a selected cell. Run the example
and click button captioned ‘Get values of Column 1’. You will see the values of first
column (separated with comma ‘,’) are shown in the textbox at bottom of the movie,
as shown here:

Note: if an array is displayed in a textbox, final value automatically becomes a


comma ‘,’ delimited string of the values in the Array.

See the code and explanation:


This code is for the button in the movie:

on(release) {
myArray = UISpreadsheet.getColumnValues(1); Get values (as array) of column #1
(one), through function
‘getColumnValues’ and assign to a
new variable ‘myArray’,
msg = myArray; then assign the values in array to a
variable ‘msg’ that is attached to a
dynamic textbox.
}

Obtain values of a specific row from UI Spreadsheet:

The Same way you can obtain values of a row in UI Spreadsheet through function
‘getRowValues’, see screenshot of example file UICO_41.swi. after the button
(captioned ‘Get Values of Row 2’) is clicked:
177

Where code for the button used to operate was:

on(release) {
myArray = UISpreadsheet.getRowValues(2);
msg = myArray;
}

Obtaining access to a specific Column or Row:

Logically obtaining access to a specific column means to get access to all cells
attached to a specific column. Similarly obtaining access to a row means to get
access to all the cells in a specific row. Following are the functions used for this
purpose:

Remember: these functions do not return the values of cells but accurate path to the
cell sprites, so you can obtain each cell value by ‘mycol[n-1].value’ where n is the
index/serial of cell in sequence

mycol=UISpreadsheet.getColumn(1); get column #1 from UI


Spreadsheet and save
returning cells as array into
variable ‘mycol’
mycol=UISpreadsheet.getColumnById("Email"); get column with tag name
‘Email’ and save in variable
‘mycol’
myrow=UISpreadsheet.getRow(1); get row #1 from UI
Spreadsheet and save
resulting array in variable
‘myrow’

How to get access to the currently selected Column or currently selected Row?

As we already mentioned that the UI Spreadsheet Collection Object allows user to


select all the cells in a specific column or a row. So the selected column or the
selected row is saved in two different properties of he UI Spreadsheet
‘selectedColumn’ and ‘selectedRow’, which provide the same resulting array
containing path to each cell.
178

Stop a UI Spreadsheet using default values:

You must have noticed that there are some initial values in the cells before assigning
new values or editing. You can turn the default values OFF using function
‘setDefaultValues’, which accepts only one argument/parameter of Boolean type. If
you pass ‘false’ as argument the default values are set OFF (by default the default
values are set ON). You may open example file UICO_42.swi and run it, you will
notice that all the cells are empty by default. Here is the preview of the example
when ran:

The syntax:
UISpreadsheet.setDefaultValues(false);

Note: this function should be called before adding any columns and/or rows, after
this function has been added to code (with false value as argument), the cells of
next added rows and columns will be empty.

Creating a Borderless cells UI Spreadsheet:

You can also hide the border of the cells using function ‘setBorderless’, which does
not take any parameter/argument. After this function is called, the cells of next
inserted columns and rows are border less, as shown here (preview of example
UICO_43.swi):

Syntax:
UISpreadsheet.setBorderless();

Creating a UI Spreadsheet with no top heads and left tags:

Use function ‘showCellsOnly’ to have the UI Spreadsheet without head and left tags.
So that, it looks like (preview of example UICO_44.swi):

There are 4 (four) more advanced functions for UI Spreadsheet Collection Object
used to plot data as Pie Chart, Bar Graph, and/or line Graph, which will be discussed
at the end of this chapter

Additional event for UI Spreadsheet:


179

onColumnAdded event invoked/fired when a new Column is added


to the UI Spreadsheet
onRowAdded event invoked/fired when a new Row is added to
the UI Spreadsheet

UI Form Dialogue

UI Form Dialogue acts as a usual forms/dialogues used in almost all applications of


modern operating systems. Form is the basic unit of almost every visual application.
Forums in Microsoft Windows operating systems are usually with 3 (three) buttons
minimize, maximize/restore/close, a Titlebar with caption over it, and the form view
area (where every component/input is shown). UI Form Dialogue is also dragable as
well as resizable at runtime as other forums of an operating system.

Preview of a usual form dialogues of Microsoft Windows 98:

Preview of a usual form dialogues of Microsoft Windows XP:


180

Preview of a usual form dialogues of RedHat Linux 8:

Preview of a usual form dialogues of Linspire (Lindows) OS 4.5:

Preview of our UI Form Dialogue:

Above preview is taken from example file UICO_45.swi. Test the example in player,
try dragging the Form Dialogue, try resizing it from left, right, and bottom corners,
and test maximize/restore option by clicking on the button in middle of the buttons
on top-right corner of form. Automation of minimize and close options, will be
demonstrated in upcoming discussion.

What is a Form used for?


181

A Form itself does not perform any important operations, but used as a stage
combining several sub components to perform a specific task. So, a UI Form
Dialogue has a specific part where it may contain sub components or load an
external movie from outside.

An Extra feature (auto percentage preloader):

When an out resource is loaded into UI Form Dialogue, it automatically adds an


accurate percentage preloader just under the Titlebar.

How to insert/add a UI Form Dialogue to my SWiSHMax project?

Open any of the example files, copy sprite ‘UIForm’, paste it in your SWiSHMax
project file, and move it to desired position.

Setting Title/Caption of a UI Form Dialogue:

Use function ‘setCaption’ to set Title/Caption of a UI Form Dialogue, as:


UIForm.setCaption("My new UI Form Dialogue Title");

Loading external SWF movie in the Form area:

Function ‘loadResource’ is used to load external SWF movie or JPEG image within the
forum stage area. Open example file UICO_46.swi, export the SWF file to the
examples folder, then test in player, and press button ‘Load Resource’. This is the
preview of the movie when an external image has been loaded into it:

Script used in button’s event ‘on(release)’:

on(release) {
UIForm.loadResource("UICO_46.jpeg"); function ‘loadResource’ of UI Form
Dialogue accepts only one
argument of string type as
absolute path to external resource
file to be loaded, either an SWF or
JPEG file. As we passed
‘UICO_46.jpeg’ name of JPEG file.
}
182

Now, let us try loading an external SWF file ‘external1.swf’, open example file
UICO_47.swi, and test in player. We loaded an SWF file through same function
‘loadResource’, see the script used for button:

UIForm.loadResource("external1.swf");

Review of event ‘onReady’:

This event is invoked/fired automatically, when a UI Form Dialogue is fully loaded


into memory and is ready to perform further actions. So, you have you implement it
as an handler within the timeline’s ‘onLoad’ event handler, as it is implemented
within almost all the examples.

Setting width and height of the UI Form Dialogue at startup:

You may not want the default size height and width of the UI Form Dialogue when
movie starts. In this case you will be using function ‘resize’, to resize the forum to
desired height and width. open example file UICO_48.swi, and run it, you will see
the following preview (setting width and height both to 300 pixels):

Script in main timeline to set UI Form Dialogue custom size:

onLoad() { event handler ‘onLoad’ of main timeline


UIForm.onReady = function() { event handler ‘onReady’ of UI Form
Dialogue
UIForm.resize(300,300); use function ‘resize’ to resize form to
custom width and height, where , first
argument is width in pixels, and second is
height in pixels of the UI Form Dialogue.
};
}
183

Setting a UI Form Dialogue non-resizable:

Function ‘setResizable’ used to set a UI Form Dialogue resizable and non-resizable.


Function ‘setResizable’ accepts only one argument of boolean type, either true or
false. To set it non-resizable (static) pass value ‘false’ to this function, and to re-
enable the resizing pass ‘true’. Open file UICO_49.swi, test it in player; you will
notice that the UI Form Dialogue is no more resizable, and the middle button
(maximize/resize) has also been disabled and user is not anymore able to resize it,
see preview:

Syntax to use function ‘setResizable’:

UIForm.setResizable(false); set resizable functionality OFF


UIForm.setResizable(true); set resizable functionality ON

Disable or Enable the UI Form Dialogue:

UIForm.disable() disable the UI Form Dialogue, so that, it is not


operatable by the user anymore, nor even
clickable
UIForm.enable() enable back the UI Form Dialogue

Additional Functions for UI Form Dialogue:

UIForm.setMaxSize(w,h) set the maximum size of resizing width and


height, where ‘w’ I width and ‘h’ is height.
UIForm.isDisabled() returns ‘true’ if form currently disabled and ‘false’
otherwise
UIForm.maximize() maximize the form through script
UIForm.restore() restore the form to original width & height
through script
UIForm.getX() current X coordinates
UIForm.getY() current X coordinates
UIForm.getWidth() get width of the form (don’t use _width property)
UIForm.getHeight() get height of the form (don’t use _height
property)
UIForm.topOnFocus() after calling this function, the UI Form Dialogue
swaps and becomes on top when dragged.
UIForm.moveTo(x,y) move to specific X and Y coordinates on screen
UIForm.getCaption() returns current Title/Caption of the UI Form
Additional Events for UI Form Dialogue:

onMaximize event invoked when a UI Form Dialogue is maximized


onMinimize event invoked when a UI Form Dialogue is minimized
onRestore event invoked when a UI Form Dialogue is restored to
original width and height
184

onClose event invoked when close button of UI Form Dialogue is


clicked by the user
onResize event invoked when a UI Form Dialogue is resized
onDrag event invoked when a UI Form Dialogue is Dragged
onDrop event invoked when a UI Form Dialogue is Dropped
onDisable event invoked when a UI Form Dialogue is disabled
onEnable event invoked when a UI Form Dialogue is enabled

Customizing the event ‘onClose’ and ‘onMinimize’:

You can implement custom handler for ‘onClose’ and ‘onMinimize’ events according
to your needs, as:

UIForm.onClose = function() {
take_some_action
};
UIForm.onMinimize = function() {
take_some_action
};

Forms within Sprites (Encapsulation/Nested forms):

You have already tested the UI Form Dialogue’s maximize and restore features. You
must have noticed the UI Form Dialogue is maximized onto the whole movie area,
WHY? Because a UI Form Dialogue sprite inserted in the _root is always maximized
according to the movie/stage width and height. If a UI Form Dialogue is embedded
into a normal sprite, it will maximized according to the width and the height of the
sprite ‘pan’ in parent path. Open file UICO_50.swi, that demonstrates UI Form
Dialogue within the sprite.

Explaining the file UICO_50.swo structure:

Open the file, it contains a sprite ‘mySprite’ which contains further two sub-sprites
in. 1. a UI Form Dialogue sprite ‘UIForm’, 2. Sprite ‘pan’ (contains red rectangle).
Run the example and try maximize the form. You will notice that the form has been
maximized exactly to the width and height of the sprite ‘pan’ in parent path. So, you
must have a sprite named ‘pan’ in the same path where sprite ‘UIForm’ is, if you
wish to embed the form sprite within other sprite.

Here is the preview of the above example before and after maximizing:
185

Before Maximize After maximize

Forms within Forms (Encapsulation/Nested forms):

You can load several UI Forms within a UI Form Dialogue. To do that, you will need
to make another SWiSH movie (e.g. ’xyz.swi -> xyz.swf’), embed forms in it and
load ‘xyz.swf’ in form using function ‘loadResource’. Example files xyz.swi and
UICO_51.swi have been created for instance.

Preview of nested form from above example:

Preview of same example of the loaded form maximized within form:

Graphs and Charts

Best solution to present statistics big organization/sites (that maintain a huge


amount of data), is through Graphical shapes called Graphs or Charts, instead of
186

showing data in figures & tables and loosing much more bandwidth. For this type of
users and developers we have developed 3D type Pie Charts, 3D Bar Graphs, and
Line Graph Collection Objects (within your favorite environment of SWiSHMax),
which do not only save your time but provided you a big ease to draw dynamic
charts and graphs at runtime and integrate them with any server-side script.

See the preview of three type of Graphical Charts:

All of above three types of charts/graphs can easily be used within your SWiSHMax
environment, and can easily be integrated with your data (even generated through
user/movie or fetched from some server-end database such as MS-SQL, MySQL).
You can also plot a 3D Pie Chart, 3D Bar Graph, and/or a Line Graph by reading data
from plain text file, where you do not need to call and wait for data arrival, these
Collection Objects have their own functions to load, calculate/manipulate data and
plot the graphs/charts.

UI Pie Charts

Pie Chart is the most used type of Graphical presentation of data. Many of the
organizations/sites use 2D pie charts as well, to show data in a most simpler way
(alongwith saving bandwidth and storage space in view of users flood). But most eye
catching type of a pie chart is 3D pie chart. Our UI Pie Charts Collection Object is
187

developed directly 3D, in a view to provide best output/printing results and lesser
use of resources (memory and space).

How to insert/add a UI Pie Charts in my SWiSHMax project file?

Simply copy the sprite ‘UIPiechart’ from any of the example files provided for this
Collection Object, and paste into your SWiSHMax project file. Then you can position
it by dragging with mouse or moving it using arrow-keys.

First example of UI Pie Charts:

Our first example demonstrate the simplest example of a UI Pie Charts. Open
example file UICO_52.swi and test in player. You will see something like this:

Short note on Array before going through the script of above example:

In previous chapters we have discussed the use and manipulation of Arrays. Here, I
introduce you a new and simplest way to create an Array without using object ‘Array’
in definition/declaration as ‘new Array()’.

How?

You simply type the comma ‘,’ delimited values within the square brackets ‘[’ and ‘]’,
and assign it to some variable. The variable assigned to such structure will
automatically become an array, such as:

values = [10, 100, 3, 515]; create new array of 4 (four) integer


elements in, and name it’s variable
‘values’

Function UIPiechart.plot()

Function ‘plot’ of UI Pie Charts is used to populate/plot a UI Pie Charts with custom
values, labels, and colors. It basically requires 3 (three) array type
arguments/parameters, where first argument is array of values, 2nd is array of
labels/captions, and last 3rd array of colors (hex values with ‘0x’ in start). This
function calculates the percentage and required area automatically according to the
values.
188

Note: number of elements for a UI Pie Charts are determined from the number of
values in the first argument of array type passed to function ‘plot’.

Now, see the script in main timeline, used to plot the UI Pie Charts (explanation):

onLoad() { event handler ‘onLoad’ of main timeline


UIPiechart.onReady = function() { implementation of handler for event
‘onReady’, which is invoked/fired when a
UI Pie Charts is fully loaded into memory
and ready to operate the data and
perform further operations.

values = [1000, 400, 200, 100]; array containing values


labels = ['Flash MX', 'SWiSH',….. array containing labels/captions
colors = [0x336699, 0xFF660….. array containing colors for each element
sequentially
UIPiechart.plot(values, labels, colors); sad populate and plot the UI Pie Charts
}; closing block of event handler ‘onReady’
} closing block of event handler ‘onLoad’

Which are the labels/captions actually? Used in above example:

Answer, encircled ones in the following screenshot:

Direct Method:

You can do the same example, by passing the arrays directly to the function ‘plot’,
instead of defining array variables first, such as the following example (taken from
file UICO_53.swi):
189

Can I use UI Pie Charts sprite multiple times with different values, labels, colors, and
different number of values each time?

Absolutely yes, you can use a single UI Pie Charts sprite to plot the Charts (with
completely different values, labels, colors, and number of values) unlimited times.
Open the example file UICO_54.swi, consists of a UI Pie Charts sprite and 2
buttons. In this example, we have populated the chart with initial values immediately
as the movie is loaded. Then the two buttons ‘plot 1’ and ‘plot2’ are used to plot the
chart with different values, labels, and colors. Test the example in player, and click
the buttons. You will see the same sprite producing different results each time. Here
is the preview of all three steps you will take:

This way you can reduce the size of final output SWF file as well as save the load
time for the client browser and save bandwidth of your server.

UI Pie Charts Loading Data from text file:

This is also not static, you can load and plot the pie chart from several text files on
server. For this purpose, we have a function ‘plotFromFile’, which accepts only one
190

argument/parameter of string type as name of the file to be loaded data from. The
file may be in current path where the movie is loaded from, or on some other site. If
the data file is in current path (where the SWF movie is loaded from) of server, then,
simply pass the filename to the function, otherwise, if it is on some other site/server,
then, you will have to use the absolute path/URL to the file. Open the example file
UICO_55.swi, export SWF to the examples folder where it will load the file
UICO_55.txt. And run the example SWF now. If the UI Pie Charts cannot read the
file in specified path, it displays an error such as ‘ERROR loading UIPiechart data file
– UICO_55.txt’.

Script used to plot UI Pie Charts from text file:

UIPiechart.plotFromFile("UICO_55.txt"); call the function ‘plotFromFile’ of UI


Pie Charts and pass it the filename
to loaded data from, as parameter.

How to get a pie chart data from a server-side PHP script?

It is as easy as the loading of data from a text file. The same function ‘plotFromFile’
is used to call the script and get data from it. Now your server-end PHP script must
be strong enough to response back with full data (values, labels, and colors).

In example file UICO_56.swi we have used a PHP script to give us data to plot a UI
Pie Charts. This example loads the file UICO_56.php the same way we loaded text
file in previous example, as:

UIPiechart.plotFromFile("UICO_56.php");

Now let us have a view over the PHP script:

In following PHP script we have used some assumed data. We have assumed this
data has been fetched from a database and then sent back to our movie.

<?

$data = "&values=150,35,15,10&
&labels=Flash MX,SWiSH,Swift 3D,K.Moves&
&colors=0x3366FF,0x00ff00,0xFF0000,0x000000&";

echo $data;
?>

Note: remember to run this script on server not local computer.

Additional functions for UI Pie Charts:

UIPiechart.setAlpha(new_alpha_value) function used to set custom alpha /


opacity / visibility value of the UI Pie
Charts, accepts only one argument of
numeric type, value from 0 (zero) to 100
191

(one hundred), see example file


UICO_57.swi.
UIPiechart.setWidth(newW) change width of the 3D pie slices area in
pixels
UIPiechart.getWidth() get current width of the 3D pie slices area
in pixels

UI Bar Graphs

Colors and design of the UI Bar Graphs can only be set/modified within SWiSHMax
environment and cannot be altered or set at runtime. UI Bar Graphs Collection
Object also works almost the similar way of the UI Pie Charts, where you pass the
values and labels (not colors) to its function ‘plot’ and you UI Bar Graph is ready. It
is also capable of picking up entries from a plain text file as well as communicate
with a server-side script (PHP, asp, cfm, pearl etc).

First UI Bar Graphs example:

Our first example of UI Bar Graphs is implemented in file UICO_58.swi. Open the
file and test in player for browser, you will see the following preview:

Let us view the script in main timeline, used to plot UI Bar Graphs:
This script is contained within the ‘onLoad’ event handler of main timeline.

UIBargraph.onReady = function() {
values = [50, 30, 20, 60];
labels = ['Swift 3D', 'Flash MX', 'SWiSH', 'Others'];
UIBargraph.plot(values, labels);
};
Explanation:

As you can see, its script is not much different from the one we used for UI Pie
Charts. The function with same name ‘plot’ is used to plot/populate a UI Bar Graphs.

UIBargraph.onReady = function() { implementation of handler for event


‘onReady’, which is invoked/fired when a
192

UI Bar Graphs is fully loaded into memory


and us ready to operate.
values = [50, 30, 20, 60]; Create new array ‘values’ for UI Bar
Graphs entries
labels = ['Swift 3D', 'Flash…. Create new array ‘labels’ for UI Bar
Graphs labels
UIBargraph.plot(values, labels); plot the UI Bar Graphs using function ‘plot’
}; closing block of event handler ‘onReady’

Reading values for a UI Bar Graphs from text file:

The same function ‘plotFromFile’ is to be used to read entries from text file. Open
example file UICO_59.swi, export it to examples folder so that, it can read the text
file UICO_59.txt from that folder, and then run it in the player.

Script in main timeline:

UIBargraph.plotFromFile("UICO_59.txt"); use function ‘plotFromFile’ to read


a text file that contains comma ‘,’
values and labels

Text in the text file UICO_59.txt:

&values=50,35,15,10& comma ‘,’ delimited values


&labels=Flash MX,SWiSH,Swift 3D,K.Moves& comma ‘,’ delimited labels

Is it possible to use UI Bar Graphs sprite multiple times?

Yes, it is possible. Use the same functions ‘plot’ or ‘plotFromFile’ to populate the UI
Bar Graphs with different values and labels. The UI Bar Graphs is automatically
updated when you call any of these two functions.

Loading data for UI Bar Graphs from a PHP script:

Follow exactly the same method we used to load the data from text file, pass the
PHP script file name which will process data either from text and/or MySQL database
and response back and variables. Example file UICO_60.swi is implemented for this
purpose, see and manipulate yourself (because we already demonstrated the
procedure in previous topic of UI Pie Charts). Do not forget to upload the PHP
module as well.

Note: remember to run this script on server not local computer.


What to do, if I do not want to show the labels?

Simply turn the labels OFF through function ‘setLabels’, by passing it a boolean value
‘false’, but remember to call this function before calling the function ‘plot’. Open file
UICO_61.swi and test it in player. You will see the following preview:
193

Here is the additional script we used before plotting UI Bar Graphs:

UIBargraph.setLabels(false);

Now, if you need to turn the labels ON, pass boolean value ‘true’ to this function and
re-plot the UI Bar Graphs.

How to insert/add a UI Pie Charts in my SWiSHMax project file?

Simply copy the sprite ‘UIPiechart’ from any of the example files provided for this
Collection Object, and paste into your SWiSHMax project file. Then you can position
it by dragging with mouse or moving it using arrow-keys.

How to modify the design and layout of the UI Bar Graphs?

Open sprite ‘UIBargraph’, then sprite ‘item’ and change the design of following
encircled sprites:

He is the example of UI Bar Graphs in cylinder style:


Preview taken from example UICO_62.swi:
194

UI Line Graphs

UI Line Graph work exactly the same way as the UI Bar Graphs. UI Line Graph has
exactly same data gathering and plotting functions.

How to insert/add a UI Pie Charts in my SWiSHMax project file?

Simply copy the sprite ‘UIPiechart’ from any of the example files provided for this
Collection Object, and paste into your SWiSHMax project file. Then you can position
it by dragging with mouse or moving it using arrow-keys.

First example of UI Line Graph:


Preview of example file UICO_63.swi (has same code used for UI Bar Graphs):

How to set custom line color and thickness?

Use function ‘setLineStyle’, which accepts two arguments/parameters, 1st thickness


of line in pixels, and 2nd parameter color of the line (a hex value). Open example file
UICO_63.swi where we set the line thickness 5 pixels, and color (red = 0xFF0000),
see the preview:
195

Script used to set the line style (function ‘setLineStyle’):

UILinegraph.setLineStyle(5, 0xFF0000);

Connecting UI Spreadsheet with UI Pie Charts, UI Line Graphs, and UI Bar


Graphs:

The most wanted/requested functionality of the charts and graphs is to have them
connected with the spread sheet (UI Spreadsheet) type data. Here, we introduce you
some additional functions of the UI Spreadsheet that enable the developer to
connect their UI Spreadsheet with any of the graphs or charts Collection Object.

There is are some specifications to connect UI Spreadsheet to graph or chart:

1. Only a single row of UI Spreadsheet can be connected to any of the graphs or


charts.
2. Row must contain numerical data in start of the string in each cell.
3. Any of the values of cells in the row must be greater than zero.
4. You must have the sprite of specific type of graph/chart within the movie to
connect to UI Spreadsheet (e.g. you are to plot UI Pie Charts, the, you must have
UI Pie Charts sprite within the movie alongwith the UI Spreadsheet sprite).

Following discussed four functions are used to plot a graph/chart based on the values
obtained from a row of UI Spreadsheet.

Note again: these functions are specific to UI Spreadsheet.

Plot a UI Pie Charts using UI Spreadsheet:

Use function ‘plotUIPiechart’ to plot a UI Pie Charts based on the values obtained
from a specific row of UI Spreadsheet. It automatically fetched the fetches the labels
from the head tags of a UI Spreadsheet. This function accepts only two arguments,
the first argument is the absolute path of the UI Pie Charts sprite (usually
‘UIPiechart’), and 2nd argument is the row id (e.g. row number 1, pass 1) a numeric
value.
Open example file UICO_64.swi, test in player or browser, and click button ‘Plot
from row 1’. You may also change the values of the cells of UI Spreadsheet by
clicking over the cells and modifying them and then re-click the button. For example
I change the value o the first cell to ‘1003’ and click the button, the chart seems to
be like this:
196

Let is view the code that we used to populate the UI Spreadsheet (in main timeline):
Only the part where initial data has been set:

for(i=1; i<=4; i++) {


mycell = UISpreadsheet.getCell(i,1);
mycell.value=i*100;
}
};
means:
get each cell (1-4) one by one of row #1 and set its initial value.

The script in button’s event ‘on(release)’ (used to plot UI Pie Charts from UI
Spreadsheet):

UISpreadsheet.plotUIPiechart(UIPiechart,1);

Explanation:

Call the function ‘plotUIPiechart’ of UI Spreadsheet, and pass the two


arguments/parameters, first the path of UI Pie Charts sprite ‘UIPiechart’ (which is in
current path so need to add prefix path to it such as ‘_root.UIPiechart’), and 2nd
argument is the row number (1) in the UI Spreadsheet.

How come the colors are set automatically?

There are some default color values used by this function, but it has a limitation.
Note: you can use this function only with maximum 10 cells/values.

If the row contains more than 10 (ten) columns/cells, this function will show a small
warning and will not plot the UI Pie Charts. In this case you will have to use other
function ‘plotUIPiechartCC’, which allows you to set custom colors. Function
‘plotUIPiechartCC’ accepts 3 (three) arguments/parameters. 1st and 2nd arguments
are same as used in previously discussed function, and the last argument is the
array containing color values (in hexadecimal), where number of values must be
equal or more than the number of columns/cells of the row.

Example Syntax:

mycolors = [0xFFFFFF,0xFF0000,0x000000, 0xEEEEEE,…………………];


UISpreadsheet.plotUIPiechart(UIPiechart, 1, mycolors);

Plot a UI Bar Graphs using UI Spreadsheet:


197

Open example file UICO_65.swi,test in player and click the button ‘Plot from row 1’.
You will see the following preview after you click the button. You may also change
the values in the UI Spreadsheet and plot the UI Bar Graphs with different values by
clicking the button.

Script used in button’s event handler ‘on(release)’:

UISpreadsheet.plotUIBargraph(UIBargraph,1);

Explanation:

Use function ‘plotUIBargraph’ of UI Spreadsheet and pass two arguments to it.


Where first argument is the path of the UI Bar Graphs sprite and second argument is
the row id/number to get data from.
Plot a UI Line Graph using UI Spreadsheet:

Open example file UICO_66.swi, test in player and click the button ‘Plot from row
1’. You will see the following preview after you click the button:
198

Usage:

Use function ‘plotUILinegraph’ to plot a UI Line Graph based on values obtained


from a row of UI Spreadsheet. This function takes only two arguments same to the
function in previous example. Where first argument is the path to the UI Line Graph
sprite and second argument/parameter is the row id/number to fetch data from.

Syntax:

UISpreadsheet.plotUILinegraph(UILinegraph,1);
199

Chapter 7

Preloaders, Scrollers, Dynamic Drawing,


and External MP3

ƒ Additional utility functions for creating Preloaders


ƒ Scroller for Dynamic and Input text objects
ƒ Creating new Sprites at runtime
ƒ Direct Drawing Methods in SWiSHScript
ƒ Scripted Preloaders
ƒ Loading external mp3 sounds & Audio Streaming
200

We have already discussed many of Sprite and Text Object properties and functions
in previous chapters. But some of the functions and properties are brought to this
chapter to understand them separately. This chapter demonstrates you how to add
fully functional Preloaders to your existing SWiSHMax project files, Text Scrolling
methods and pre-built simple control, creating container (empty) Sprites at runtime,
some script methods that allow the developer to draw lines & shapes with custom
color and gradient, and creating light and fully functional preloader with loaderBar
and accurate percentage, built up of only and only script.

Additional utility functions for creating Preloaders

There are 3 (functions) which give us the exact size of the SWF movie being loaded,
the remaining part of the SWF movie to be loaded (in bytes), and percentage of the
loaded SWF movie size.

The preloader I am to demonstrate here, can be added to your main movies as well
as to the externally loaded movies. Many of the users create preloaders, but they
face unpredictable results when they embed those preloaders within the externally
loaded SWF movies. Then why not to create a prefect preloader that fits all the
needs either used to preload main movie and/or sub movies that are loaded as
external movies.

Get, Set, Go

Function ‘getBytesTotal’:

‘getBytesTotal’ is one of the built-in functions in SWiSHScript that returns the total
movie size in bytes. E.g. we can obtain the main movie size in bytes, as:

moviesize = _root.getBytesTotal();

Where ‘moviesize’ is a new variable which is assigned the value returned from the
function ‘getBytesTotal’. Note, we have used ‘_root’ as prefix path to the function,
which will always return the size of the movie running in main timeline (main movie).
Most of our SWiSHMax users do the same in externally loaded movies as well which
is logically wrong. Because, the preloaders are always in main timeline of each
movie, and when a movie is loaded externally ‘_root’ does not refer to the current
timeline but the main movie loader priorly. What to do? Use ‘this’ as prefix path in
each and everywhere you create the preloader. So that

moviesize = _root.getBytesTotal(); is LOGICALLY WRONG, and we won’t use


it anymore
moviesize = this.getBytesTotal(); is PERFECT (or simply ignore ‘this’)
‘this.getBytesTotal()’ or ‘getBytesTotal()’will always refer to main timeline of the
movie currently being loaded and return the total size of it in bytes, not the actual
main movie loaded priorly.
201

Function ‘getBytesLoaded’:

‘getBytesLoaded’ is also a built-in functions of SWiSHScript that returns the number


of bytes loaded currently. E.g.

loadedsize = this.getBytesLoaded();

where ‘loadedsize’ is the variable assigned the number of bytes loaded from the
current SWF movie being loaded.

Now, we can obtain the percentage of the loaded movie, by dividing the loaded bytes
over total bytes and then multiplying it with 100 (one hundred), as:

moviesize = this.getBytesTotal(); // or getBytesTotal();


loadedsize = this.getBytesLoaded(); // or getBytesLoaded();
percentage = (loadedsize/moviesize)*100;

BUT, why to use initializations and calculations in 3 (three) lines, when SWiSHScript
provides us a built-in function to obtain percentage.

Obtain percentage of a loaded SWF movie:

Use function ‘percentLoaded’ to obtain the percentage of the loaded movie size. E.g.
percentage = this.percentLoaded();

I already contributed many more tutorials and quick tips to create preloaders in
online community forums, which make so easy for a developer to add a perfect
preloader to the SWiSHMax project file. Here, I do quote the same steps to create a
good preloader for your movie.

Note: if you don’t bother to read this topic simple open file 033.swi, copy scene
‘preloader’, paste it in your SWiSHMax file and bring this scene over the top of all
scenes.

Steps to create perfect preloader:

1. Create a borderless rectangle of 100 pixels wide, and put it in the middle of
screen (color desired)
2. Copy the rectangle, paste it, and move it to the same position where previous
rectangle is, set its border line (thickness 0 of desired color), and there should be
no fill in it (select None).
3. Group each rectangle as separate sprite.
4. Name the sprite ‘border’ (with rectangle of border only) or (skip this step)
5. Name the sprite ‘bar’ (with rectangle with fill, we created first)
6. Create a dynamic text box, name it ‘_msg’ and attach Target variable ‘msg’ from
advance text properties.
7. go into main timeline’s script Panel and paste the following code:
onLoad() {
stop();
}
onEnterFrame() {
bar._width = pl = percentLoaded();
202

msg = pl +"% Loaded";


if(pl == 1000) {
play();
delete this.onEnterFrame;
}
}

8. Finally, Remember to put a stop action in your next scene’s timeline, so that, the
movie does not come back to preloader scene once played.

Explanation of script used in step 7:

onLoad() { ‘onLoad’ event handler of main timeline of


preloader scene.
stop(); stop the movie immediately as it starts
loading
} closing block of ‘onLoad’ event handler

onEnterFrame() { ‘onEnterFrame’ event handler of main


timeline of preloader scene.
bar._width = pl = this.percentLoaded(); get percent loaded of current movie
(referring through prefix path ‘this’)
through function ‘percentLoaded’, assign it
to new variable ‘pl’, and then assign it to
the width of sprite ‘bar’ as well, so that,
the width sprite ‘bar’ is changed to
percent loaded.
msg = pl +"% Loaded"; add a string ‘% Loaded’ with value of
variable ‘pl’ that contains the percentage
of loaded movie, and assign it to variable
‘msg’ which is attached with a dynamic
textbox (so that, it is displayed).
if(pl == 1000) { Now, check if percent loaded is 100 (full),
then,
play(); play the current timeline, so that it goes
to the next scene directly
delete this.onEnterFrame; job has been done, now delete the event
handler ‘onEnterFrame’
} closing block of ‘if’ statement
} closing block of ‘onEnterFrame’ event
handler
203

Scroller for Dynamic and Input text objects

Almost 20 to 25% of the topics in almost every SWiSH community, are asked about
text scrollers. We have developed a scroller to meet all of your needs. This scroller
can be attached to any type of textbox either dynamic or input. It appears and
disappears automatically when text is enough to show the scroller or empty. It is
also invisible until it is not attached to any textbox. We have named it ATBS (All
Times Best Scroller). ATBS is also capable of drawing custom color border around the
textbox.

Adding ATBS in my SWiSHMax project file:

Open example file 034.swi or any example file of this resource, copy sprite ‘atbs’,
and paste I anywhere (on any position) in your SWiSHMax project file. Why paste
anywhere? Because when ATBS is attached to a textbox it automatically resizes and
moves itself to the absolute position.

How to attach ATBS to a textbox?

Open example file 034.swi, which contains an input textbox ‘_msg’ and ATBS sprite
‘atbs’. Test it in player. Remember: the ATBS does not show until there is not
enough text in textbox to add scroller. Type some text lines more than the text area,
so that, the ATBS is automatically visible. Here is the preview:

Script in main time line of example:

onLoad() { ‘onLoad’ event handler of main timeline


atbs.onReady = function() { implementation the handler for event ‘onReady’
which is invoked/fired when the ATBS is ready to
be attached and operate.
atbs.attachTo(_msg); use function ‘attachTo’ of ATBS to attach the
ATBS to any textbox, and pass it the absolute
path of the textbox instance
}; closing block of ‘onReady’ event handler
} closing block of ‘onLoad’ event handler

Attaching ATBS to the left side of the textbox:

Use the function ‘attachLeftTo’ and pass it the path + name of the of textbox object.
Open example file 035.swi, and see the different line in script in main timeline:
atbs.attachLeftTo(_msg); use function ‘attachLeftTo’ to attach the ATBS on
the left side of the textbox.
204

Preview of the example:

Set custom color border of the attached textbox:

Use function ‘makeObjBorder’ and pass it the color value (as hexadecimal), you will
see a border with custom color is shown over the textbox. See the script in main
timeline of example file 036.swi.

Note: the border will only be visible when ATBS is visible.


Here is the preview of the example:

Script we used to draw border:

atbs.makeObjBorder(0xFF0000); 0xFF0000 is the value of red color in hex

Creating new Sprites at runtime

A function ‘createEmptyMovieClip’ of SWiSHScript, which is exactly same in Flash MX


ActionScript, is used to create a new sprites at runtime. This function is capable of
creating new sprites within any defined path.

What is the use of empty sprites?

Mostly, the sprites created at runtime, are used to load external SWF movies and/or
custom drawing through SWiSHScript.
Open example file 037.swi, and see the code in main timeline:
205

createEmptyMovieClip("newSprite",1); create new sprite using function


‘createEmptyMovieClip’, which accepts two
arguments/parameters; 1st argument is
name of the new sprite being created, and
2nd parameter is the new depth of the
movie. Remember when assigning depth,
if there are some other objects already in
current path then assign the new depth
(n+1) where ‘n’ is number of existing
objects.
newSprite.loadMovie("external1.swf"); load movie external1.swf using function
‘loadMovie’ within the newly created sprite
‘newSprite’

You can treat the newly created sprites exactly as the physical sprites we usually
create within SWiSHMax environment.

Now, if you wish to create a new sprite within another ‘xyz’ sprite, then, use the
sprite name ‘xyz’ as prefix path to this function, as

xyz.createEmptyMovieClip("newSprite",1);
then access the sprite through ‘xyz.newSprite’.

Direct Drawing Methods in SWiSHScript

SWiSHScript also provides almost all functions for drawing at runtime that are
available in Flash MX ActionScript. We will be discussing some of the functions (not
all) that allow the develop to draw normal shapes through SWiSHScript.

lineTo

Function ‘lineTo’ accepts two arguments of numeric type. It draws line from current
position (usually x:0, y:0) to the passed positions as arguments. This function is also
available in Borland Graphics Interface Library (BGI).

Example:
this.lineTo(100,100);

moveTo

Function ‘moveTo’ accepts two arguments of numeric type. It moves the current
pointer to specific position specified as arguments, to start next drawing from. This
function is also available in Borland Graphics Interface Library (BGI).

Example:
this.moveTo(100,100);
this.lineTo(200,200);

lineStyle
206

Function ‘lineStyle’ is used to set line thickness and color. This function accepts two
arguments. The first argument is the line thickness in pixels and 2nd as color (hex
value).

Example:
this.lineStyle(5,0xff0000);
this.lineTo(100,100);

beginFill, endFill

Function ‘beginFill’ is used to fill and bordered area. This function must be called
before starting the drawing with line borders. This function accepts two arguments,
first as the color value (in hex), and 2nd as the value of alpha/opacity/visibility 0 to
100. Function ‘endFill’ is used when you have finished drawing border and wish to fill.

Example:
this.beginFill(0xFF0000,100);
this.lineTo(100,100);
this.lineTo(50,150);
this.lineTo(0,0);
this.endFill();

preview:

Scripted Preloaders

We have written a cut-n-paste preloader script for you, by combining all the scripts
from this chapter (dynamic drawing methods and preloader methods). What you
have to do is, simply copy the following script and paste in the main timeline of
preloader scene (no need to insert any object or draw anything in the preloader
scene).

Here is the script (also available in CODE VAULT of www.scriptsector.com) taken


from file 038.swi:

//CODE STARTS HERE


onLoad() {
207

stop();
/*
+-------------------------------------------------+
| change following hex value to desired colors |
+-------------------------------------------------+
*/
_global.bar_color = 0xDDDDDD;
_global.text_color = 0x000000;
_global.border_color = 0x666666;
_global.bar_height = 10;

//Calculate screen's center


if(this == _root) {
_global.CX = int((Stage.width/2)-50);
_global.CY = int((Stage.height/2)-(_global.bar_height/2));
} else {
_global.CX = int((_parent._width/2)-50);
_global.CY = int((_parent._height/2)-(_global.bar_height/2));
}

//Create loaderBar sprite 'bar'


this.createEmptyMovieClip ("bar", 1);
with (this.bar){
_x = CX;
_y = CY;
beginFill(bar_color,100);
lineStyle (0, bar_color, 100);
moveTo (0, 0);
lineTo (100, 0);
lineTo (100, bar_height);
lineTo (0, bar_height);
lineTo (0, 0);
endFill();
}
bar._width=0;
//Create loaderBar border sprite 'border'
this.createEmptyMovieClip ("border", 2);
with (this.border){
_x = CX;
_y = CY;
lineStyle (0, border_color, 100);
moveTo (0, 0);
lineTo (100, 0);
lineTo (100, bar_height);
lineTo (0, bar_height);
lineTo (0, 0);
}

//Create percentage text display


this.createTextField("mytext",3,CX,CY+bar_height,100,20);
mytext.border = false;
myformat = new TextFormat();
myformat.align = "center";
208

myformat.color = text_color;
myformat.font = "Verdana";
myformat.size = 10;
tData = "0% Loaded";
mytext.variable = "tData";
mytext.setTextFormat(myformat);

/*
+------------------------------------------+
| Copyrights ® www.swishclimax.com |
| Don't remove without permission |
+------------------------------------------+
*/
this.createTextField("copyright",4,CX-50,CY+bar_height+20,200,20);
copyright.border = false;
copyright.text = "Powered by www.scriptsector.com";
copyright.setTextFormat(myformat);

//Implement onEnterFrame to check


//percentage until it is 100%...
this.onEnterFrame = function() {
pl = int(percentLoaded());
tData = pl+"% Loaded";
mytext.setTextFormat(myformat);
bar._width=pl;
if(pl == 100) {
bar.removeSprite();
border.removeSprite();
mytext.removeTextField();
copyright.removeTextField();
play();
delete this.onEnterFrame;
}
}
}
//CODE ENDS HERE
209

Loading external mp3 sounds

SWiSHScript provides a scripting object ‘Sound’ to control the embedded as well as


external sounds perfectly.

Create new Sound object to loaded external MP3 file:

s = new Sound(); allocate new Sound object ‘s’


s.loadSound(“somefile.mp3”); use function ‘loadSound’ of ‘Sound’ object
to load an mp3 file from outside, pass it
the name of mp3 file alongwith absolute
URL.

Start playing the loaded MP3 file:

Use function ‘start’ to play an mp3 loaded through ‘Sound’ object, as:

s.start();

Stop a playing sound:

Use function ‘stop’ to stop a playing sound under ‘Sound’ object, as:

s.stop();

Obtain the Total bytes, loaded Bytes, total Duration, and current Position of sound:

s.getBytesTotal() function returns the total file size in bytes


s.getBytesLoaded() function returns the total bytes loaded so far
s.duration property returns the duration of a sound in
milliseconds.
s.position property returns the number of milliseconds a
sound has been playing

Set the volume percentage:

Use function ‘setVolume’ to set percent (0-100) volume, as

s.setVolume(50);

onSoundComplete:

Event Invoked when a sound stops playing (has completed playing). E.g.
implementing it as handler will look like this:

s.onSoundComplete = function() {
msg = “Sound has completed playing”;
//restart it
s.start();
};

Simple Method for streaming:


210

Here is a simple example of audio streaming:

onLoad() {
playonmaximum = 50; // when 50% sound loaded start playing
s =new Sound();
s.loadSound(“somefile.mp3”);
this.onEnterFrame = function() {
percent = (s.getBytesLoaded() / s.getBytestotal())*100;
if(percent >= playonmaximum) {
s.start();
delete this.onEnterFrame;
}
};
}
211

Chapter 8

Core Practice / Source Code / Details


ƒ Study of MySQL with PHP
ƒ Creating Interactive Polling System using UI Collection Objects
ƒ Online Resources / Help
212

Study of MySQL with PHP

MySQL is a powerful database engine that works with PHP by default. This engine
can handle a huge amount of connections at a time/flood as well has a big amount
data. It uses SQL Standards with some additions in data types.

The structure of the MySQL Engine:

Structure of MySQL engine can easily be understood from following picture.

Hierarchical structure of the MySQL engine is like the folders and files in the
Microsoft Windows Explorer. That, there should not be two or more folders of same
name (regardless capital letters), and there should not be two or more files of the
same name (including extension) in same path. MySQL acts same, two are more
databases cannot be of same name under one MySQL engine, similarly two or more
tables of same name cannot be created under one database.

Mostly the database for a specific use is created by the hosting companies
themselves and a lot the user a username and a password, through which user
connects to MySQL engine and runs the queries.

If a hosting company provides you MySQL database as well as the web space within
same server, the engine is considered local host (although it is not running on local
PC). But, when you have web space (PHP scripts) and MySQL database on two
separate hosts, the connection to the engine will be established through the IP or
URL granted by the hosting company.

There are dozens of built-in functions in PHP that enable the developer to manipulate
data in a database of MySQL engine. Here we go to discuss some of the most used
functions. Remember: The name of each and every function that is to be used for
MySQL starts with prefix ‘mysql_’.
213

How to connect to MySQL engine?

Use function ‘mysql_connect’ to connect to the MySQL engine.

Syntax:

mysql_connect( host_name, username, password);

Where ‘host_name’ is the host (if script and MySQL both are on same server use
‘localhost’ otherwise the granted IP or URL), username and password the same one
we discussed above.

How to know, either I am connected to MySQL engine or not?

Call the function ‘mysql_connect’ same way (mentioned above) and assign it to some
variable. Function ‘mysql_connect’ returns a boolean values after executed. If it
returns true, it means you are successfully connected to MySQL, and if it returns
false that means some error has occurred and connection could not be established.
See following example code:

$myVar = mysql_connect(“localhost”, “Ali”, “Imran”);


if($myVar == false)
echo “ERROR: cannot connect to MySQL”;
else
echo “Successfully connected”;

Showing the errors generated by the server:

Usually the errors come up automatically, but some of the hosts set the errors OFF
because of some reasons. In this case, if you wish to see the actual error generated
by the system, use function ‘mysql_error’ (which returns error string), as:

$myVar = mysql_connect(“localhost”, “Ali”, “Imran”);


if($myVar == false)
echo mysql_error();

Setting MySQL generated errors OFF:

May be (in some scenario) you wish the system not to display errors automatically.
So that you can display custom error to the user. To do this, you simply put a ‘@’
(sign : at the rate of) before the function name, see the following code:

$myVar = @mysql_connect(“localhost”, “Ali”, “Imran”);


if($myVar == false)
echo mysql_error();

Now, you must have been granted a database name that you are allowed to use. To
work on tables in a MySQL database, you must select the database first.

Selecting a database:
214

Use function ‘mysql_select_db’ to select an allowed database from MySQL engine,


and pass it the database name as string (name of database) or a variable containing
string valued as name of database; as:

mysql_select_db( “alis_database”);

This function also returns true on success.

So from now on, remember to call both of the above discussed functions to establish
a connection with MySQL database:

First connect to MySQL engine mysql_connect(“localhost”, “Ali”, “Imran”);


Then select the database mysql_select_db( “alis_database”);

DML Operations:

What is DML? DML stands for Data Manipulation Language. It has 3 (three) major
functions:
Data Insertion Inserting data into tables
Data Deletion Deleting specific data from a table
Data Modification Modifying existing data in a table

To perform above three DML operations, we run queries; First, we need to know
what is a query.

Query:

Query is a statement (set of several MySQL keywords and user data) that is
executed by the MySQL engine and data is altered. Query is written following the
MySQL syntax. Here are the examples of queries to be used to perform DML
operations. If you have to execute multiple queries use semicolon ‘;’ on the end of
each MySQL statement.

Insertion:

INSERT INTO ‘my_table’ VALUES (‘Ali Imran’, ‘news@SWiSH-DB.com’)

Whenever you need to insert data in to table, start query with ‘INSERT INTO’, next is
the table name ‘my_table’ to insert data in. the last part of the insertion query is the
new values (encapsulated in brackets) to insert as new row, where ‘VALUES’ is a
keyword of MySQL.
Deletion:

DELETE FROM ‘my_table’ WHERE email=‘news@SWiSH-DB.com’

A query for deletion starts with keywords ‘DELETE FROM’, next table name
‘my_table’ to delete data from, then keyword ‘WHERE’ where you put the condition,
which is matched with all the rows in the table, on match found the row is deleted.
In above example we checked if field ‘email’ is equal to ‘news@SWiSH-DB.com’ then
delete the row, this query will delete all the rows containing email ‘news@SWiSH-
DB.com’. If ‘WHERE’ clause is not implemented, all the rows will be deleted and table
will be emptied.
215

Review on MySQL operators:

Note : The comparison operator ‘=’ and assignment operator ‘=’ both are same in
SQL, as compare to SWiSHScript the comparison operator is ‘==’ and assignment
operator is ‘=’.

Similarly another comparison operator ‘!=’ (not equal to) is used in SWiSHScript
whereas in MySQL it is used as ‘<>’ as well as ‘!=’.

Logical ‘and’ or ‘&&’ in SWiSHScript is same as used ‘AND’ or ‘&&’ in MySQL.


Logical ‘or’ or ‘||’ in SWiSHScript is same as used ‘OR’ or ‘||’ in MySQL.
Logical ‘!’ (NOT) in SWiSHScript is same as used ‘!’ or ‘NOT’ in MySQL.

So combining more than one condition in MySQL query is done as:


WHERE email=‘news@swishclimax.com’ OR username=‘Ali’

Modification:

UPDATE ‘my_table’ SET email=‘abc@123.com’, age=27 WHERE username=‘Ali’

Query for alteration/modification in row(s) of a MySQL table starts with keyword


‘UPDATE’, next is table name ‘my_table’ to alter data of, then keyword ‘SET’ and
following alterations/assignments (as we are making two changes in specific rows
email=‘abc@123.com’ changing email, age=27 changing age [separated with
comma]), then the keyword ‘WHERE’ (implementation of ‘where’ clause) and last
part is the conditions of ‘WHERE’ clause. After running this query the MySQL engine
will check all the rows where username is ‘Ali’ and change the email and age to
specified values. If ‘WHERE’ clause is not implemented, all the rows effected, and the
corresponding fields will be modified to specified data.

Table of MySQL:

A table of MySQL database is similar to the one created in Microsoft Access or the
Microsoft Excel Sheet, based on columns and rows. Where columns are called fields
of a MySQL table. Each field of the MySQL table is specific for the data type it is
created to hold. Where our requirements are 3 (three) data types, so, we will discuss
only 3 (three).

Running the query from PHP?

Function ‘mysql_query’ (of PHP) is used to execute a query on MySQL engine. It


requires only one argument of string type where you will pass the MySQL query. This
function returns different types of values on each situation. If the query could not be
executed either due to MySQL syntax error or any other error occurrence, the
function will return false. If the query was executed successfully it returns true or the
resource pointer (which will be discussed in upcoming topic of Fetching/Retrieving
Data from MySQL tables)

Example:
216

$result = mysql_query(“DELETE FROM ‘my_table’ WHERE age=27”);


if(!$result) //same to if($result == false)
echo “Error occurred while executing query”;

Data types of the fields of a MySQL table:

As we already mentioned that, we have concern with only 3 (three) of the types, so
we go with those only.

VARCHAR

This type is set for a field to contain text only data. Text may include any of the
characters. A field defined to be of type ‘VARCHAR’ can contain maximum 255
characters. You have to specify the maximum length of the filed you require.

INT

When a filed of MySQL table is defined to contain integral numeric data, we use
‘INT’. You have to specify the maximum length of the filed you require.

BLOB

‘BLOB’ is the type defined for the MySQL tables’ fields to contain unspecified length
of text data. This filed allow you to store text data of any length. The MySQL engine
shrinks and grows the row size itself.

Creating new table in MySQL Database:

CREATE TABLE ‘my_table’ (


username VARCHAR(20),
age INT(3),
bio BLOB
)

Bring above SQL code to minimum lines query string:

CREATE TABLE ‘my_table’ (username VARCHAR(20), age INT(3), bio BLOB)

To run a query that creates a table in currently selected MySQL Database, start it
with ‘CREATE TABLE’ then table name ‘my_table’, then starting bracket ‘(’ where you
will define the fields and their types. To define a new field use ‘field_name type’ as
‘username VARCHAR(20)’ and separate multiple fields with comma ‘,’.
‘VARCHAR(20)’ means a field of type ‘VARCHAR’ of maximum length 20 (twenty)
characters. Then the 2nd field ‘age’ is defined as ‘INT(3)’ which means the field is of
numeric type and can hold maximum 3 digits (which is maximum value 999). Last
field is of type ‘BLOB’ which tells the type of field is capable of holding unlimited
number of characters in (length not specified). At end close the bracket ‘)’. So that,
to run this query we use:

mysql_query(“CREATE TABLE ‘my_table’ (username VARCHAR(20), age INT(3), bio BLOB)”);


217

Note: the filed name selection is almost same to variable name in SWiSHScript.
Which must not start with a number or punctuation, may contain underscore letters
and numbers, etc.

Fetching/Retrieving Data from MySQL tables:

‘SELECT’ keyword is used to implement a query that fetches/reads data from a


MySQL table.

Syntax:

SELECT username FROM ‘my_table’ WHERE age=27

A query to be used to fetch data from MySQL table starts with keyword ‘SELECT’,
then the fields ‘username’ to fetch data from (to get data of multiple fields put more
field names separated with comma ‘,’ as: ‘username, bio’), then keyword ‘FROM’,
then the table name ‘my_table’ to fetch data from, at last the implementation of
‘WHERE’ clause (condition(s)). Now after this query is executed, will get all the rows
where value of field ‘age’ is equal to 27 (twenty seven) .

If you wish all fields if the row as return use ‘*’ instead of specifying the field names,
as:

SELECT * FROM ‘my_table’ WHERE age=27

If ‘WHERE’ clause is not implemented, the query will result in returning all rows with
data of only one field ‘username’.

To execute this query from PHP we use:


$result = mysql_query(“SELECT * FROM ‘my_table’ WHERE age=27”);

If query was not successful and some error occurred the function will return false.
Otherwise it will return a pointer to resource from which we can fetch rows one by
one (we will have to fetch rows either resource contains one or multiple rows).
Before fetching rows one by one, first, we need to know if the resource is not empty,
for this purpose we use function ‘mysql_num_rows’, where we pass the resource to it
as parameter/argument and it returns an integer value (number of rows in the
resource).

Syntax:

$result = mysql_query(“SELECT * FROM ‘my_table’ WHERE age=27”);


$num = mysql_num_rows($result);
if($num == 0)
echo “No data returned by the query”;

Where ‘$result’ is the variable used as resource pointer obtained from function
mysql_query after running the query

Now, if number of rows in the resource pointer was more than 0, we implement the
else block in our above code, and fetch the rows one by one using function
218

‘mysql_fetch_array’ which returns each fetched row as an array of PHP. This function
requires only one argument as the resource pointer. as:

Note: structure of the ‘for’ loop in PHP is exactly same to the one used in
SWiSHScript.

$result = mysql_query(“SELECT * FROM ‘my_table’ WHERE age=27”);


$num = mysql_num_rows($result);
if($num == 0)
echo “No data returned by the query”;
else {
for($i=0; $i<$num; $i++) {
$single_row = mysql_fetch_array($result);
echo “$single_row[username] <br>”;
}
}

Explanation:

$result = mysql_query(“S… run the query using function


‘mysql_query’, and save the
resulting resource pointer in PHP
variable ‘$result’
$num = mysql_num_row… get number if rows from resource
pointer ‘$result’ and assign it to
new variable ‘$num’
if($num == 0) if returning number of rows are
equal to ZERO, then,
echo “No data returned b… display the message ‘No data
returned by the query’
else { otherwise if the number of rows
was greater than ZERO, then,
for($i=0; $i<$num; $i++) { start ‘for’ loop to run ‘$num’ times
$single_row = mysql_fetch_array($result); fetch a row out of the resource and
assign the resulting array to
variable ‘$single_row’
echo “$single_row[username] <br>”; display the data in index
‘username’ of currently fetched
array, where indexes of the array
are same to the names of the fields
in the table as well as the data
type is also same.
} closing block of the ‘for’ loop
} closing block of the ‘else’

Which will result something like this on the browser screen:

Ali Imran
Charly Pixels
Ali Roman
Eddie_k

DROP:
219

‘DROP’ in MySQL means to erase a database of a table permanently.

Query Drop a database:

DROP DATABASE ‘my_database_name’

There is also a function ‘mysql_drop_db’ of PHP which may be used to drop


Databases, which returns true on success and false otherwise.

Syntax:
mysql_drop_database(“my_database_name”);

Query Drop a table:

DROP TABLE ‘my_table’

Creating Interactive Polling System using UI Collection Object

We will be creating a polling system using UI Collection Objects (UI Radio and UI Pie
Charts) where we will show the statistics using UI Pie Charts. This poll works with
MySQL database accessed through PHP. There is an installer file 039_install.php
included with examples. What you have to do is, change some values in the file, as:

Making amendments (Installation):

mysql_connect("localhost","u","p") replace the “u” with your database


username, and “p” with the database
password

mysql_select_db("test") replace the “test” with your database


name you are allowed to work with

Now, upload the file and run it on the server, which will drop the table ‘sc_polls’ if
already created, then recreates the table ‘sc_polls’. After you have run the page, it
will show you a message ‘SWiSH Climax MySQL Polling System successfully
installed.’, which indicates that it has been installed successfully. Now, open file
039_poll.php and make same changed you made in installer file. Upload it in the
desired folder where you wish to run the polling system. Export the 039_poll.swi to
html so that an html file as well as an SWF is created, upload both files to same
folder. And try running the polling system by typing the URL in your browser.

Explanation of the swi resource file created for poll:

Objets in the main timeline:

There are two static text, three dynamic text objects, three sprites, and one button
object. where
220

ƒ Dynamic Text Object ‘_msg’ (attached variable ‘msg’) is used to display different
messages at each point.
ƒ Dynamic Text Object ‘_total’ (attached variable ‘total’) is used to display total
number of votes submitted so far.
ƒ Dynamic Text Object ‘_last’ (attached variable ‘last’) is used to display the date
of the last submitted vote.
ƒ Rest of the two static text objects are used as simple labels
ƒ Sprite ‘bar’ contains the progress bar (simple animation sprite)
ƒ Sprite ‘UIPiechart’ is the UI Pie Charts sprite used to show statistics as pie chart.
ƒ Sprite ‘options’ contains further five sub-sprites (v1, v2, v3, v4, and v5) of UI
Radio, and a static text object as label.
ƒ And a button object ‘submit’ used to submit data to the PHP script.

Now move onto script in the main timeline:

function setOption(opt) { create new function ‘setOption’ that will be


accepting one argument/parameter which
will be then assigned to global variable
‘option’
option=opt; assign the variable ‘option’ the value of
passed argument as ‘opt’
} closing block of function ‘setOption’

onLoad() { ‘onLoad’ event handler of main timeline


options._visible=false; set the ‘_visible’ property of the sprite
‘options’ to false, so that it becomes
hidden at startup
submit._visible=false; set the ‘_visible’ property of the button
object ‘submit’ to false as well
option = 3; create new variable ‘option’ and assign it
new integer value 3 (three)
pid="swish_climax"; create a new variable ‘pid’ and assign it
string value ‘swish_climax’ which is to be
passed as poll id to the PHP script for the
poll identification, because there may be
more than one polls in the MySQL table.
When we ran the installer file we inserted
a new poll with ‘pid’ as ‘swish_climax’.

options.v1.onClicked = function() { implement handler of the event


‘onClicked’ invoked by the UI Radio sprite
‘v1’ which is sub-sprite if ‘options’, when it
is invoked, then,
setOption(1); pass 1 (one) to function ‘setOption’ which
will set the value of variable ‘option’ to 1
(one)
}; closing block of the event handler
‘onClicked’ of UI Radio ‘v1’
options.v2.onClicked = function() { implement the handlers for event
‘onClicked’ the same way for other UI
Radio sprites within sprite ‘options’
setOption(2); and set the value of the variable ‘options’
};
221

options.v3.onClicked = function() {
setOption(3); - do -
};
options.v4.onClicked = function() {
setOption(4); - do -
};
options.v5.onClicked = function() {
setOption(5); - do -
};

response=0; create new variable ‘response’ and assign


it integer value ZERO (0)
this.loadVariables("039_poll.php","POST"); load PHP script file 039_poll.php from
server, and send it data through http
method ‘POST’ (to send data
transparently), so all the variables priorly
defined in current path are dispatched to
the script.
this.onEnterFrame = function() { implement event handler ‘onEnterFrame’
within ‘onLoad’ event handler (block
starts)
if(response==1) { if value of variable ‘response’ is equal to 1
(which is returned back by the PHP
script), then,
if(cookie==1) { if value of variable ‘cookie’ (returned from
PHP script) is equal to 1 (one), then,
prepare to initialize pie chart data to plot
labels = ['Not Bad', 'Good', create new variable ‘labels’ of type Array,
'Excellent', 'Bad', and assign it 5 (five) elements of string
'Worst']; type

colors = [0x00ff00,0xFF0000,0x000000, define a new variable ‘colors’ of type Array


0x3366FF,0x993399]; and assign it five elements of type
Hexadecimal

//_values coming from server comments


values = _values.split(","); split the value variable ‘_values’ (returned
from PHP script) with delimiter ‘,’
(comma) among a new array and assign
the resulting Array to new variable
‘values’
UIPiechart.plot(values, labels, colors); plot the UI Pie Charts by passing it
argument variables ‘values’, ‘labels’, and
‘colors’
msg="Results"; change the value of variable ‘msg’ to
string ‘Results’, so that , it is displayed in
text object ‘_msg’
} else { if value of cookie was not 1 (one), then,
options._visible=true; set the sprite ‘options’ to visible
submit._visible=true; set the button ‘submit’ to visible, so that
user can select from UI Radio buttons and
submit vote
222

} closing block of ‘if’ statement used to


check value of variable ‘cookie’
bar._visible=false; set the sprite ‘bar’ invisible
response=0; set the value of variable response to ZERO
delete this.onEnterFrame; delete the event handler ‘onEnterFrame’
because the job has been done for now.
} closing block of ‘if’ statement used to
check value of variable ‘response’
}; closing block of event handler
‘onEnterFrame’
} closing block of event handler ‘onLoad’

Understanding the functionality and Scenario:

On startup, we set the property ‘_visible’ of sprite ‘options’ and button ‘submit’ to
‘false’ (to set them invisible). Why? Because our script will start working just after it,
so that, we do not allow user to submit vote until our movie does not receive the
variable ‘response’ with value ‘1’ (one). Then we set the value of variable ‘response’
to ZERO by default, why? Because the event handler ‘onEnterFrame’ is checking its
value continuously, so it remains ZERO until it is not received from the script with
value ‘1’. Why did we set the value of variable ‘option’ to 3 (three)? Because we set
the default selected the third UI Radio option. Then we loaded the PHP script using
function ‘loadVariables’ and sent it the variable ‘pid’ (where variable ‘option’ is also
sent, but it does not effect because we did not pass variable ‘a’ as querystring to the
URL). Now if the variable ‘a’ I passes alongwith the loadVariables, the script assumes
it is vote submission not just data retrieval.
Now, in event handler ‘onEnterFrame’ we check the value of variable ‘response’, if
the value of variable ‘response’ is 1 (one), it means the PHP script has responded
fully. Now check the value of variable ‘cookie’, if it is 1 (one) which means the cookie
has already been written in client computer, that indicates that the user has already
submitted the vote, so directly display the statistics through UI Pie Charts,
otherwise, if value of variable ‘cookie’ (received from PHP script) is ZERO it indicates
the user has not submitted the vote yet, so, display him/her the sprite ‘options’ (UI
Radio buttons) and button ‘submit’ by setting their ‘_visible’ property to ‘true’. After
it process has been done set back the value of variable ‘response’ to ZERO and
delete event handler ‘onEnterFrame’ to save the CPU usage, and set the sprite ‘bar’
invisible.

Now See the script contained within event handler ‘on(release)’ of button ‘submit’:

Code is almost same as of main timeline, but only one thing is different in line:

this.loadVariables("039_poll.php?a=x","POST");

that is ‘?a=x’

Note: Anything passed after the URL+ ? is called query string passed through http
method 'GET'

Explanation:

We passes a variable ‘a’ through http method ‘GET’ methods to the PHP script,
whereas all other variables of SWiSHScript are dispatched through http method
223

‘POST’. The PHP script checks for availability of the variable ‘a’, if it is available to the
PHP script (as we have passed, so it will be available) the PHP script assumes the
vote is submitted.

Short review on PHP script in file 039_poll.php:

$r=mysql_query("SELECT * FROM sc_polls WHERE pid='$pid'")


or die("s:".mysql_error());

Run MySQL query that fetches the row containing our poll with poll id ‘pid’ coming
from SWiSHScript in to PHP variable ‘$pid’, and assign the result to variable ‘$r’

$row = mysql_fetch_array($r);

Get the row out of the resource pointer ‘$r’ and assign it to new variable ‘$row’

if(!$row)
die(report("msg","POLL NOT FOUND - $pid, rows:".mysql_num_rows($r)));

If row is not fetched then stop the execution at this point use function ‘die’ which
halts the execution wherever called. It accepts on argument of string type as the
message to display and break execution.

$cookie_name = "swish_climax";
$cookie_path = "/"; //do not change value of it
$cookie_domain = ""; //use ".yourdomain.com" if not localhost
$cookie_time = (3600*24)*7; //on week cookie, 3600 = 1 hour

set cookie information in 4 (four) variables.

if(!isset($a)) {

if variable ‘$a’ is not received from SWiSHScript.

if(!isset($_COOKIE[$cookie_name]) or $sum==0) {

check if cookie is not set in client browser or the number of total votes is ZERO, then

report ("total",$sum);

send variable ‘total’ to SWiSHScript

report ("last",$row['timer']==0?"":date("m-d-Y",$row['timer']));

send variable ‘last’ to SWiSHScript and its value the date of last vote if votes more
than ZERO or send empty string if no field timer is ZERO (which is by default ZERO
when installed)

report ("cookie", 0);

send variable ‘cookie’ to SWiSHScript and its value ZERO


224

report ("response",1);

send variable ‘response’ to SWiSHScript with value ‘1’ (one), which indicates the
SWiSHScript that process is complete and data ahs been received.

} else {
otherwise, if cookie is set

$temp = Array();
for($i=0; $i<count($values); $i++) {
$cval = intval($values[$i]);
$temp []= $cval==0?1:$cval*10;
}
report("_values",implode(",",$temp));
report ("total",$sum);
report ("last",date("m-d-Y",$row['timer']));
report ("cookie", 1);
report ("response",1);

process and calculate data and send to SWiSHScript through function ‘report’

if(isset($a)) {

now, if variable ‘$a’ is received from SWiSHScript, then

mysql_query("UPDATE sc_polls SET _values='$vals', lastip='$ip', timer=$tm


WHERE pid='$pid'")
or die("e:".mysql_error());

update the existing poll and

setcookie($cookie_name,_ip(),$cookie_time,$cookie_path, $cookie_domain);

set the cookie in client computer

report ("cookie", 1);


report("_values",implode(",",$temp));
report ("last",date("m-d-Y",$row['timer']));
report ("total",$sum);
report ("response",1);

then response back to SWiSHScript.

function report($var,$val) { echo "&$var=$val&"; }

create new PHP function ‘report’ that is used to send variables back to SWiSHScript.
It accepts two arguments two arguments 1st variable of SWiSHScript and 2nd value of
the variable being sent to SWiSHScript.

function _ip() { return $_SERVER['REMOTE_ADDR']; }


225

create new PHP function ‘_ip’ which returns IP address of the client computer
obtained from array $_SERVER and index REMOTE_ADDR which is automatically
available in the PHP environment.

Online Resources / Help

There are many community forums for SWiSH 2 an SWiSHMax help. The forum we
are currently running (is open for everyone) can be found on www.swish-db.com,
and for customers (of this book) support visit www.swishclimax.com.

On swish-db.com we have a huge download center full of SWiSH 2, SWiSHMax, PHP,


Flash MX, and other scripting and design resources.

Our newly established community can be found on www.scriptsector.com

Official site of SWiSHMax is www.swishzone.com, and their community forum for


help and updates is, www.swishzone.com/forums.
226

Chapter 9 SWiSHMax integration with


ASP and MS-Access
Note: This chapter does not teach you the core ASP,
But the integration of ASP with SWiSHMax, and
some useful methods which can give you good
start for writing ASP + SWiSHMax Database
driven applications.

ƒ What is Microsoft Access?


ƒ Creating Database and Tables with Microsoft Access
ƒ What is ASP?
ƒ Adding comments in ASP code
ƒ Tracking variables obtained through GET and POST method in ASP
ƒ Sending back Response to SWiSHMax movie
ƒ Sample SWiSHMax application with ASP
ƒ Connecting ASP with MS-Access
227

What is Microsoft Access?

Access is a database creation/manipulation tool that comes alongwith the set of tools
in Microsoft Office, product of Microsoft Corporation. There are many versions of the
Microsoft Office available in the market. The one we have to choose is, the one which
will be compatible with all the Office Software, so that the users do no need to worry
about the backward compatibility of the files you deliver to them. Similarly, the user
of Operating system Linspire can also alter the files through Sun Microsystems’ Star
Office easily. So, we will use Access 97 (comes alongwith Microsoft Office 97) to
make our database alterable from within all version of Microsoft Office. If you do not
have setup/installer of Microsoft Office 97 you still may continue with higher version,
but next topic (Creating Database and Tabl…) is not of much interest to you, because
it is written only for Access 97. You may find some tutorials or Demonstrations about
creating database and tables in specific version of your Microsoft Access, through
search engines (such as www.google.com)

Creating Database and Tables with Microsoft Access

Here are steps to create a database in Microsoft Access.


Note: All the steps and screenshots are taken from Microsoft Access 97.

When you start Microsoft Access, a form Dialogue appears as shown below:
228

Select the Radio Button ‘Blank Database’ and click the button ‘OK’. After you have
clicked the button, another common dialogue appears, to save the database file, as
show here:

After entering desired name of the database file to save, click button ‘Create’ visible
in the top-right corner of the above shown form Dialogue.

I the previous for dialogue does not appear at the startup, click the left most icon
under the menus, as shown here:

It will display a dialogue of a bit different type, Select ‘Blank Database’ icon and click
button ‘OK’, as shown here:
229

After you are done with saving the database file (.mdb), next dialogue appears,
where you do not need to bother about many options and tabs, simply select tab
‘Tables’ and click the button ‘New’, as shown here:

Now another Dialogue appears which allows user to select the way s/he wishes to
create new table. You simply select ‘design View’ from the list on right side and click
button ‘OK’, as shown here:

The last step is to create structure of the table, as shown below. A dialogue appears
with title ‘Table1 :Table’, that allows you to insert desired names of the fields in first
column (on left) and type of the field in 2nd column (on right) where it allows you to
select the type of field through a sophisticated combo. See the screenshot:
230

Note: type ‘Number’ in Access is almost alternate to ‘INT’ in MySQL, where ‘Text’ to
‘VARCHAR’

Now your table has been created, if you wish to set more custom options, they are
available under the editing table area as tabs ‘General’ and ‘Lookup’, as shown
above; you are recommended to use ‘General’ tab options not the options available
in tab ‘Lookup’.

Now it is time to save the created table in the database file we created. To do this
simply click the save icon available in the toolbar under the top menu, as shown
here:
231

Access will prompt you asking the new table name to write to database, you simply
type the desired table and click button ‘OK’, as shown here:

Furthermore, if another dialogue appears, simply click button ‘NO’, if you are
unaware of Primary Key, as shown here:

This was the complete step by step procedure of creating new database and a new
table in Microsoft Access.

If you need to add more tables to the created database simply close currently open
table, you will see the exactly same dialogue you used a while ago, appears,
containing the name of the table already created, you simply click button ‘New’ and
follow the same procedure to create new table as we priorly defined. Screenshot is
here:

Now, when we are successful in creating a new database and table with Microsoft
Access, let us see the integration of this database with ASP.
232

What is ASP?

Word ‘ASP’ stands for Active Server Pages. This technology was introduced by
Microsoft Corporation a couple of years ago, to provided an ease to user to create
his/her dynamic web pages using Visual Basic Language like syntax ‘VBScript’ or
Java Language like syntax ‘JavaScript’. For writing ASP applications you may use any
of VBScript and JavaScript languages. I myself use VBScript to write Active Server
Pages which is much easy and flexible for the developer as well as for the Beginners
or Moderate Level developers of Microsoft Visual Basic, to directly jump onto ASP
without problems.

A Database created with Microsoft Access is accessible directly through ASP (Active
Server Pages, the server-end script). Where all the standard SQL commands are
applicable over the Access database through ASP.

Code of an ASP application is enclosed in <% and %>, means script of active server
page starts with <% and ends with %>. And ASP script files as usually saved with
extension ‘.asp’. Since we will be using normal ASP not ASP .Net (the latest version
of ASP), we will save files with extension ‘.asp’, not ‘.aspx’ etc.

Adding comments in ASP code

Since we will be using VBScript in our ASP script, comments are styled the same
used in VBScript, QBasic and/or Visual Basic, as shown here:

<%
‘I am comment text line
‘I am comment text line 2

myVar = 10
%>

Tracking variables obtained through GET and POST method in ASP

ASP has built-in objects interact with client application.

Object ‘Request’ (discussing POST Method)

This is the object available on server which provides the data alongwith variable
names sent from client application through http method POST. We can access each
individual variable (coming from client application e.g. SWF), sent through http
methods POST, from this Object, as:

userName = Request(‘Name’)
userEmail = Request(“Email”)

you must have noticed that, in first line, I used single quotes (‘ and ’) and in second
line I used double quotes (“ and ”), this is just to make you sure that both of the
quotes can be used.
233

Explanation:

userName = Request(‘Name’) get the value of variable ‘Name’ coming


from client application (e.g. SWF) via http
method POST, and assign it to a new
variable ‘userName’. It is equivalent to
PHP statement:
$userName = $_POST[‘Name’];

userEmail = Request(“Email”) get the value of variable ‘Email’ coming


from client application (e.g. SWF) via http
method POST, and assign it to a new
variable ‘userEmail’. It is equivalent to
PHP statement:
$userEmail = $_POST[“Email”];

Note: there is no semicolon at the end of VBScript statements.

You may also obtain the values of variables coming through http method POST, as:

userEmail = Request.Form(“Email”)

because, logically, the variables coming from POST method are always sent through
a form.

Object ‘Request.QueryString’ (discussing GET Method)

What is Query String?

Simple definition: Query String is a string following to the URL + ? with variables and
values.
E.g. http://www.swishclimax.com/myscript.asp?Name=Ali&Email=news@SWiSH-DB.com

‘Name=Ali&Email=news@SWiSH-DB.com’ is the query string, where ‘Name’ and ‘Email’


are the variables (sent through http method GET) assigned value using ‘=’ and
assignments separated with ‘&’.

Example and explanation:

userName = Request.QueryString(‘Name’)
equivalent to PHP statement: $userName = $_GET[‘Name’];

userEmail = Request.QueryString(“Email”)
equivalent to PHP statement: $userEmail = $_GET[“Email”];

You already know that the server side scripts are called/loaded through SWiSHMax
function ‘loadVariables’ or the ‘loadVars’ object’s function ‘load’. Assume we have a
variables ‘age’ already in SWiSHMax. Now if we pass the above mentioned URL to
this function as:

this.loadVariables(“http://www.abc.com/myscript.asp?Name=Ali&Email=news@abc.com”, “POST”);
234

we will receive the variable ‘age’ through POST, where ‘Name’ and ‘Email’ through
http method GET, as:

ASP PHP

userAge = Request(“age”) $_POST[“age”];


‘or //or
userAge = Request.Form(“age”) $_POST[“age”];
‘and //and
userName = Request.QueryString(“Name”) $_GET[“Name”];
userEmail = Request.QueryString(“Email”) $_GET[“Email”];

So far we have learnt to receive the variables (coming through http methods GET
and POST) in our ASP script, question is:

How to send information back to client application (e.g. SWF)?

Answer is contained in next topic.

Sending back Response to SWiSHMax movie (Object ‘Response’)

Object ‘Response’ is used to send response back to client application, that might be
an SWF (SWiSH or Flash generated), standard browser page. Where response may
be in plain text, standard html, XML, and/or any kind of data that is build up of
characters. Function ‘Write’ if object ‘Response’ is used for this purpose, which acts
almost same to ‘echo’ or ‘print’ the functions of PHP.

e.g.

Response.Write(“&msg=Response from ASP”)


or
Response.Write “&msg=Response from ASP” Note: brackets are not
necessary, in VBScript.

Is equivalent to PHP script as shown here:

echo “&msg=Response from PHP”;


or
print “&msg=Response from PHP”;

where ‘msg’ is the variable of SWiSHScript.

Sample SWiSHMax application with ASP

Open 040.swi that is dummy of example 014.swi, and uses to load script file
040.asp, then the 040.asp response back the data for SWiSHScript variable
‘myVar2’ which is attached with a textbox in our SWiSHMax movie.
235

See the code of 040.asp:

Note:‘&’ is used in VBScript as concatenation operator similar to the one in PHP as ‘.’

<%
'we have recieved variable myVar as ASP variable Request("myVar")
'now we will send back the myVar2 containing data of my myVar we recieved.

myVar2 = "Hello " & Request("myVar") & " from ASP&"


Response.Write myVar2
‘or
‘Response.Write(myVar2)
%>

equivalent PHP script:

<?
//we have recieved variable myVar as PHP variable $myVar
//now send back the myVar2 containing data of my myVar we recieved.

$myVar2 = "Hello " . $myVar . " from PHP&";


// or
// $myVar2 = "Hello $myVar from PHP&";
echo $myVar2;
?>

Connecting ASP with MS-Access

Connecting MS-Access from within ASP is done through objects, but the procedure is
easier than in PHP. What you have to do is, create an object to establish connection
with Microsoft Access file. Then run the standard SQL query and perform desired
DML operations. The interestion operation is the data retrieval, which is performed
by a resource object that is created after connection has been established with
engine.

Establishing connection to load MS-Access Database file:

Create connection object (use as it is):

Set connection = Server.CreateObject("ADODB.Connection")


connection.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=abc.mdb"
connection.Open

Creating Record-Set pointer to fetch data from:

Now, when connection has been established with the specific Driver, let us move
towards create recordset object and run the desired query, as:

Set record = Server.CreateObject("ADODB.Recordset")


record.Open ("SELECT * FROM myTable", connection)
236

or use variable created connection object ‘connection’, call its function ‘Execute’ and
save the resulting resource in new variable for ‘record’, as

Set record = Server.CreateObject("ADODB.Recordset")


Set record = connection.Execute ("SELECT * FROM myTable")

Fetching the resulting rows from Record-Set pointer ‘record’:

After the query is ran and we are expecting some results in the variable ‘record’ used
as recordset. To do that we will process rows in record-set one by one within a loop.
In ASP, we move the internal pointer in a record-set and record-set itself acts as a
row. So that to fetch ‘age’ from current row we use record("age"), see detailed
example here:

Do While Not record.EOF


Response.Write ( record("userName") & "-" & record("Email") )
record.MoveNext
Loop

Explanation:

Do While start VBScript loop with keywords ‘Do While’

Not record.EOF while record not reaches to End Of File (EOF)

Response.Write ( send back response to client application, as


record("userName") data of field ‘userName’ from current row
& "-" concatenate ‘-’ with output
& record("Email") ) concatenate data of field ‘Email’ from current row

record.MoveNext move the internal pointer of record-set to next


row using function ‘MoveNext’ of record-set
object we created priorly

Loop closing block of loop ‘Do While’

Note: loop ‘Do While’ of VBScript acts as the loop ‘while’ in PHP.

Closing the connection:

After the job is done, and we have utilized/processed the data, we free up the
variable ‘record’ holding record-set information, and then close the established
connection, as:

record.Close
connection.Close

Encoding special characters with VBScript:

I you remember, we already encoded special characters before sending back to our
SWiSHMax generated SWF. VBScript provides us a easy way to do that, through
function ‘URLEncode’ of object ‘Server’. See example:
237

Example:

myURL = “&swfurl=<b>http://www.swishlimax.com/script.asp?name=Ali Imran&email=a@b.c</b>&”


enURL = Server.URLEncode(myURL)

Response.Write( enURL )

Where ‘swfurl’ is the variable in the client SWF movie.

So the final code becomes:

<%

Set connection = Server.CreateObject("ADODB.Connection")


connection.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=abc.mdb"
connection.Open

Set record = Server.CreateObject("ADODB.Recordset")


record.Open ("SELECT * FROM myTable", connection)

Set record = Server.CreateObject("ADODB.Recordset")


Set record = connection.Execute ("SELECT * FROM myTable")

Do While Not record.EOF


Response.Write ( record("userName") & "-" & record("Email") )
record.MoveNext
Loop

record.Close
connection.Close

%>

You might also like