Professional Documents
Culture Documents
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
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
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
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
Using Line tool you can draw a straight line in any direction.
Note: straight line not curved
Example:
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.
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).
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
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
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.
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
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.
“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.
“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.
Insert
“Insert Frame” menu is used to insert frame in between existing filled frames or
inserting new empty frame.
“Delete Frame” menu works opposite to “Insert Frame”. It deletes currently selected
frame. After deleting frame the timeline becomes like this
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
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.
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.
“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).
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
1.Guided
2.Expert
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:
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.
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
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.
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:
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.
/*
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
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
*/
Chapter 2
Getting Started
I would like to give you much more practice (instead of writing bundles of theory), so
lets get a GO.
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.
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:
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:
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:
myVar = 10;
Define a variable with name ‘myVar’ to hold numeric data (floating point/ with
fractions):
myVar = 10.34;
or
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
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;
}
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
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:
on(press) {
MyTempVar = myVar;
}
Concatenating / Joining
myVar = myVar + “This is my new value”;
or
myVar = myVar add “This is my new value”;
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.
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
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
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.
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.
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 / 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.
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.
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.
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’ is a variable of type String and holds a text value of ‘this is my Text’.
46
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.
varname = true;
varname = false;
myBoolVar = false;
Remember: Variable myBoolVar can hold only two kinds of value either true or false.
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.
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).
myBVar = true;
myIVar = int(myBVar);
myIVar now contains 1 (one), because value obtained from Boolean variable
‘myBVar’, was true.
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.
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
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;
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.
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”;
or
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.
So simple:
Use either of the Addition operators to join String value with a Numeric value. See
example:
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).
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
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
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.
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:
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
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;
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++;
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;
So this is the difference, which may be applied the same way using Decrement
Operator ‘--‘.
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
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):
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.
Now let us have a look over first control structure if-else that allows us to take
decisions in our SWiSHScript.
55
if ( condition_block ) {
code_to_execute
}
speed = 10;
if( speed == 10 ) {
message = “You are too slow”;
}
where
message = “You are too slow”; is the code to be executed when condition is true.
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.
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”;
}
But if you use brackets where they are not necessary, it does not harm your script
such as:
if(V == 10) {
H = 0;
}
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
if( condition )
…….
else if( condition )
…….
58
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 )
or
or
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.
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 ‘&&’.
IF A equals 10 OR B equals 12
or
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”;
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
Example PSEUDOCODE:
BLOCK ENDS
61
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 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.
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’.
so we can say
62
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;
Loop Structures
What is a Loop?
‘while’ loop
Example:
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:
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++;
}
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.
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.
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
‘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.
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:
let us implement the example using ‘for’ loop; the example we used for ‘while’ loop:
X = 0;
while(X<5) {
trace(X);
X++;
}
66
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:
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).
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.
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:
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
‘I+=2’ is the short form of expression of ‘I=I+2’, which has already been discussed
in previous topics.
68
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”;
}
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).
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.
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”;
}
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.
What is a function?
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).
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);
}
}
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.
This was the simple way of creating your own functions, now we move to a bit
advanced techniques involved in writing functions.
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);
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:
Example:
72
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(release) {
myFunc2(5);
}
Take previous example, and let us implement it different way, so that it can return
back value (we changed the function name as well).
function mySQR(myNum) {
myNum *= myNum;
return myNum;
}
after running this example within SWiSHMax environment, the result is:
Click this button when you run it
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.
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).
useHandCursor
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:
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:
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
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;
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.
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
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:
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:
code = Key.getCode(); Get Key code of the last key pressed and
assign it to variable ‘code’
};
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:
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.
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
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;
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).
play()
Play a specific sprite, from frame currently stopped at. Syntax as follows:
sprite_name.play();
_root.play();
_level2.play();
stop()
Stop the sprite, _root, or any level playing the timeline. Follow the syntax as below:
sprite_name.stop();
_root.stop();
_level2.stop();
gotoAndPlay()
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
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);
sprite_name.gotoAndStop(“some_label”);
_root.gotoAndStop(“some_label”);
_level2.gotoAndStop(“some_label”);
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:
onFrame()
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()
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):
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
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
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)
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”;
}
}
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, _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.
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
on(press) {
_root.myVar = "This is new Value";
}
_parent
onFrame(1) {
_parent.v = "parent accessed";
}
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";
}
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.
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.
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:
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:
or
Use of ‘tellTarget’
Explanation:
Note : ‘tellTarget’ is used only to point paths/levels not variables or scripting objects.
_root.mySprite.spriteVar = 1;
_root.mySprite.gotoAndPlay(”lable2”);
Answer:
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.
or
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.
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
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:
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");
}
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&
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.
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.
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
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
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:
&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
&done=1&
onLoad() {
this.loadVariables("data2.txt");
current=1;
done=0;
}
What is onLoad()?
So we put onLoad() event handler in our main timeline, and put 3 lines of code as:
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.
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)”.
on(release) {
if(current < 3) {
current++;
done=1;
}
}
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
This was the method to send data variables to server-side scripts (to process).
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.
<?
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.
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.
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&";
?>
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.
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.
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";
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>";
That was all for creating your E-Mail contact form, and sending mail through PHP.
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");
fwrite($f,$myText);
fclose($f);
?>
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.
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");
fclose($f);
echo $data;
?>
Details
$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
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();
}
l.onLoad = function(success) {
if(success) {
take_action_file_loaded_successfully
} else {
handle_error_occured
}
}
111
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).
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;
}
This is the method used to clone an existing sprite object in our SWiSHMax
movie.
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.
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.
on(release) {
spr.duplicateSprite("newSpr",2);
newSpr._x += 50;
newSpr._y += 50;
}
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.
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
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).
What is Array?
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.
Example:
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
arrLen = myArr.length;
Where ‘arrLen’ is new variable, we assigned it the length of the Array ‘myArr’ (which
is 4 - four).
Very simple.
Creating variable once:
myArr = new Array(); create empty array variable
Now we show the std_site item of the student record Array in internal debugger of
SWiSH using trace() function.
trace( myArr[‘std_site’] );
You can also pass Integer or String variables instead of constant indexes, as:
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);
}
Chapter 5
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.
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");
}
};
}
&myName2=Ali Imran&
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;
}
}
};
}
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).
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
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
};
}
function myFunction() {
xyz.onEnterFrame = function() {
take_some_action
};
}
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.
What to do, when I want to deactivate an event handler 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
}
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
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.
onLoad() {
mySprite.onAnimationEnded = function() {
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:
onLoad() {
mySprite.onMousePress = function() {
msg = "Mouse is pressed";
};
mySprite.onMouseRelease = function() {
msg = "Button of Mouse is Released";
};
}
on(press) {
onMousePress();
}
on(release) {
onMouseRelease();
}
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.
Here we need to know a new built-in function typeOf() before we move forward:
msg = typeOf(mySprite);
So this is the type of a sprite object, you may pass any object name and obtain its
type as string name.
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:
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.
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;
}
};
}
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();
}
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.
onLoad () {
onEnterFrame = function() {
if(_framesLoaded == _totalFrames) {
_parent.onFullyLoaded(this._name);
delete onEnterFrame;
}
};
}
onFrame (1) {
stop();
}
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
}
};
}
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’.
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:
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.
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.
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:
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’.
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:
else otherwise,
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:
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:
else otherwise
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.
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.
Game preview:
Timer.ticks()
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:
onLoad() {
Stage.onResize = function() {
take_some_action
};
}
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 < to display ‘<’ and > 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
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.
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.
However, using URL encoding to replace the + character the original text:
Cost=%2b85
Will result in Flash displaying 'Cost= +85' correctly.
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
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
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
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.
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.
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.
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
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.
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”;
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.
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.
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.
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’.
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();
};
}
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();
};
}
onLoad() {
150
x.onRadioReady = function(radioID) {
take_some_action
};
}
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.
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:
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
Explanation:
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:
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
or
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
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):
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.
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:
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.
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:
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:
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).
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:
NOTE: Disabling a top-level menu means to disable entire drop down items list as
well.
159
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
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);
};
}
Simply copy the sprite ‘UICombo’ from any of the UI Combo examples and paste in
your SWiSHMax project on desired position.
Explanation:
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.
Repeated Example:
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.
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:
Note: You can also get the last clicked/selected item using variable ‘selected’, as:
if(UICombo.selected == p1) ……
UICombo.expand();
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
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:
UICombo.getItem(1).caption = "CHANGED";
or
UICombo.getItemById("item1").caption = "CHANGED";
Disabling mean, stop user access to click the item. Combo level Functions
‘disableItem’, ‘disableItemById’ and ‘enableItem’, ‘enableItemById’ are used for this
purpose.
1.Direct methods:
UICombo.disableItem(1);
UICombo.disableItemById("item2");
UICombo.enableItem(1);
UICombo.enableItemById("item2");
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.
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:
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:
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.
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.
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).
Copy the sprite ‘UIToolbar’ from any o the relevant examples and copy in your
SWiSHMax project.
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.
Separator
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.
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.
After running it, you will notice that the width of the UI Toolbar is large by default.
As shown here:
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.
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:
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.
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:
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:
Open any of the examples of UI Spreadsheet, such as UICO_36.swi, copy the sprite
‘UISpreadsheet’ and paste in your SWiSHMax project file.
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.
Note: It does not matter, if you add Rows before adding Columns.
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’
}
UISpreadsheet.getCell(1,1).value="Ali";
174
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?
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:
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);
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.selectedCell.value = 1500;
176
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:
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.
}
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
on(release) {
myArray = UISpreadsheet.getRowValues(2);
msg = myArray;
}
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
How to get access to the currently selected Column or currently selected Row?
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.
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();
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
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.
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.
Open any of the example files, copy sprite ‘UIForm’, paste it in your SWiSHMax
project file, and move it to desired position.
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:
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");
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):
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
};
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.
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
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.
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.
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).
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.
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:
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):
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.
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’.
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");
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;
?>
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).
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.
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.
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.
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.
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
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.
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.
Open sprite ‘UIBargraph’, then sprite ‘item’ and change the design of following
encircled sprites:
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.
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.
UILinegraph.setLineStyle(5, 0xFF0000);
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.
Following discussed four functions are used to plot a graph/chart based on the values
obtained from a row of 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:
The script in button’s event ‘on(release)’ (used to plot UI Pie Charts from UI
Spreadsheet):
UISpreadsheet.plotUIPiechart(UIPiechart,1);
Explanation:
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:
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.
UISpreadsheet.plotUIBargraph(UIBargraph,1);
Explanation:
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:
Syntax:
UISpreadsheet.plotUILinegraph(UILinegraph,1);
199
Chapter 7
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.
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
Function ‘getBytesLoaded’:
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:
BUT, why to use initializations and calculations in 3 (three) lines, when SWiSHScript
provides us a built-in function to obtain percentage.
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.
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
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.
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.
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.
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:
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
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.
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
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’.
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).
stop();
/*
+-------------------------------------------------+
| change following hex value to desired colors |
+-------------------------------------------------+
*/
_global.bar_color = 0xDDDDDD;
_global.text_color = 0x000000;
_global.border_color = 0x666666;
_global.bar_height = 10;
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);
Use function ‘start’ to play an mp3 loaded through ‘Sound’ object, as:
s.start();
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.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();
};
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
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.
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
Syntax:
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.
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:
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:
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:
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
mysql_select_db( “alis_database”);
So from now on, remember to call both of the above discussed functions to establish
a connection with MySQL 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:
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:
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
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 ‘!=’.
Modification:
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).
Example:
216
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.
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:
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.
Syntax:
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:
If ‘WHERE’ clause is not implemented, the query will result in returning all rows with
data of only one field ‘username’.
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:
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.
Explanation:
Ali Imran
Charly Pixels
Ali Roman
Eddie_k
DROP:
219
Syntax:
mysql_drop_database(“my_database_name”);
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:
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.
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.
options.v3.onClicked = function() {
setOption(3); - do -
};
options.v4.onClicked = function() {
setOption(4); - do -
};
options.v5.onClicked = function() {
setOption(5); - do -
};
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.
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
if(!isset($a)) {
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);
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 ("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)) {
setcookie($cookie_name,_ip(),$cookie_time,$cookie_path, $cookie_domain);
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.
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.
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.
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)
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.
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
%>
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:
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.
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
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
So far we have learnt to receive the variables (coming through http methods GET
and POST) in our ASP script, question is:
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.
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
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.
<?
//we have recieved variable myVar as PHP variable $myVar
//now send back the myVar2 containing data of my myVar we recieved.
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.
Now, when connection has been established with the specific Driver, let us move
towards create recordset object and run the desired query, as:
or use variable created connection object ‘connection’, call its function ‘Execute’ and
save the resulting resource in new variable for ‘record’, as
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:
Explanation:
Note: loop ‘Do While’ of VBScript acts as the loop ‘while’ in PHP.
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
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:
Response.Write( enURL )
<%
record.Close
connection.Close
%>