+ All Categories
Home > Documents > Swish Climax

Swish Climax

Date post: 17-Nov-2014
Upload: badminto
View: 2,823 times
Download: 15 times
Share this document with a friend
SWiSHClimax is the best reference guide for learning SWiSHMax hardcore scripting techniques, for both experts as well as the beginner designers.One of the best book to learn swishscript.
1 SWiSH CliMax Your best companion for learning SWiSH MAX Advanced Scripting with PHP and ASP That enables you to enhance your web applications meeting international market standards By Ali Imran (2004)
Page 1: Swish Climax


SWiSH CliMaxYour best companion for learning SWiSH MAX

Advanced Scripting with PHP and ASPThat enables you to enhance your web applications meeting international market standards

ByAli Imran


Page 2: Swish Climax


Table of Contents

Chapter 1 IntroductionFocusSWiSH MAX – An IntroductionSWiSHScript HistorySWiSHScript Vs ActionScriptUnderstanding SWiSH MAX IDEDesign tools OverviewUnderstanding Menus and ToolbarsApplying built-in effects on objectsAdding comments in Code

Chapter 2 Getting StartedMovie Physical ObjectsData types and VariablesType Casting or Type JugglingSWiSHScript BasicsMathematical and Comparison OperatorsTaking decisions in SWiSHScript using ‘if’Logical OperatorsTernary If-else structureLoop StructuresBreaking loops UnconditionallySkipping the code in loops, UnconditionallyTuning up code with ‘switch’ set statementWorking with FunctionsString manipulationButton and Sprite Object properties and event handlersMy first SWiSHScript applicationUnderstanding Levels_root, _parent, this, and _globalUse of ‘tellTarget’Use of and ‘with’Dragging the objects at runtime

Chapter 3 TEXT/JPEG File Management with SWiSH MAXLoading data from Text Files, loading external JPEG filesCreating static Address Book with images (without PHP)

Chapter 4 Interaction with PHPSending data to PHP scriptReceiving data from PHP scriptMy first text echo applicationCreating E-Mail Contact Form, mail in PHPWriting Text Files

Page 3: Swish Climax


Reading Text FilesIntroducing loadVars Object and its reliabilitySprite Duplication and accessing duplicated sprite’s propertiesArrays in SWiSHScript, more flexible and powerful than in ActionScript

Chapter 5 Advanced Events Handling and other Scripting ObjectsEvaluation/Access of Dynamic Objects/VariablesAdvanced Techniques of Events Handling (an Introduction)How to implement existing event handlers within functionsDeleting Event Handlers when job is doneDefining/Attaching new events handlers to Sprite object, and using themCreating Events to accept variables as ArgumentsConnecting Objects through eventsDefining Global functions to use anywhere without referenceCreating Sprite pointersCollision detection for games creationEncoding special characters before sending to SWiSH Movie

Chapter 6 Using UI Collection ObjectsIntroduction to UI Collection ObjectsUI CheckBoxUI Radio ButtonUI MenusUI Combo BoxUI ToolbarsUI SpreadsheetUI Form DialogueUI Pie ChartsUI Bar GraphsUI Line GraphsConnecting UI Spreadsheet with UI Pie Charts, UI Line Graphs, and UI Bar Graphs

Chapter 7 Preloaders, Scrollers, Dynamic Drawing, an External MP3Additional utility functions for creating PreloadersScroller for Dynamic and Input text objectsCreating new Sprites at runtimeDirect Drawing Methods in SWiSHScriptScripted PreloadersLoading external mp3 sounds & Audio Streaming

Chapter 8 Core Practice / Source Code / DetailsStudy of MySQL with PHPCreating Interactive Polling System using UI Collection ObjectsOnline Resources / Help

Page 4: Swish Climax


Chapter 9 SWiSHMax integration with ASP and MS-Access

What is Microsoft Access?Creating Database and Tables with Microsoft AccessWhat is ASP?Adding comments in ASP codeTracking variables obtained through GET and POST method in ASPSending back Response to SWiSHMax movieSample SWiSHMax application with ASP

Color Codes and File names

BLUE SWiSHScriptRED PHPGREEN Chapter Names/Notes and ASP CodeGRAY CommentsPINK MySQLBROWN Text

Page 5: Swish Climax

Chapter 1


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

Page 6: Swish Climax



This book focuses on salient features of SWiSHScript as well as throws lighton designing. There is no prior knowledge of SWiSHMax required to read this book. Ifyou already have some know-how of SWiSH 2 or SWiSHMax environment, that is aplus. Major focus of the book is on implementation of all level SWiSHScriptapplications alongwith implementation of User Interface Objects and standardreusable components.

SWiSH MAX – An Introduction

SWiSHMax is a complete Integrated Development Environment, and productof SWiSHZone PTY. Ltd. Using SWiSHMax, you can create from simple to mostcomplex animations and standard web applications. SWiSH renders your finalanimations or applications to SWF (swiff pronounced) file format. Macromedia Incintroduced SWF file format, for the very first time. Commonly SWF is taken asabbreviation of Shock-Wave-Flash, where ShockWave is another software product ofMacromedia Inc. The most widely used software tool of Macromedia, is Flash, whichrenders the application to final version SWF. An SWF file is the final publishableversion of your Rich Media Contents on the World Wide Web. So, what we meant tosay is, that SWiSHMax also renders/exports your final application/animation to SWFformat, which is recognized by almost all the browsers via Installable FlashPlayerplugin (ActiveX) for OS.

SWiSHScript History, SWiSHScript Vs ActionScript

SWiSHScript is a scripting language, derived from Flash ActionScript. What isFlash ActionScript? Flash ActionScript is a scripting language used in MacromediaFlash 4/5/MX. It enables the developer to control events and write runtime flow ofthe application. It uses almost same syntax for control structures as is used in C /C++ / Java / JavaScript / PHP etc. It also provides some Object Oriented techniquesand some built-in scripting objects to work with. So SWiSHScript cannot be saidcompletely same to Flash ActionScript but 95% same. So the SWiSHMax provides acomplete set of language syntax to write inter-structure code of the web application.

Page 7: Swish Climax


Understanding SWiSH MAX IDE

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

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

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

Page 8: Swish Climax


Design tools Overview

Design tools/Drawing tools are part of Layout window/Design window. As shownbelow. These tools contain

Select tool is simply used to select any object, drag and reposition it, and resize itas 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

Page 9: Swish Climax


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

Example:Before After

Fill Transform is the tool used to manipulate the gradient if a shape, or atiled/clipped image in a shape.

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


Pencil tool works almost same as in MS-Paint. But it may be said anenhanced version of that. Any object created with this tool becomes a shape asmatrix of pixels. So that, the drawn shape holds all the properties of a usual shape.Its big feature is, it automatically fills the drawn shape if it drawn shape’s startingand ending points are same.

Example:Auto Filled Unfilled

Page 10: Swish Climax


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


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


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

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

Page 11: Swish Climax


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 fromLayout/Design window. It is used to drag the entire movie area within the Layout. Itis useful especially when you have placed some object out of design area. It isautomatically unselected when you release the mouse button after dragging thedesign area to a specific position.

AutoShape tool provides variety of premade shapes available within SWiSHMax. Toselect desired shape, click in the icon and hold the moue button down for a while,then a set of tools appear to select from, as shown here:

Page 12: Swish Climax


Stretch and Screw tool defined within SWiSHMax as,

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


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

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

Distort transformation tool allows to apply a distort transformation to selectedshape, if it is a rectangle, this tool will act almost same as reshape tool, but if it is anellipse of a shape drawn using Bezier it will result differently. You may try it yourself.

Page 13: Swish Climax


After clicking this tool some gray lines do appear over the Layout Window. Theselines are called guides, which guide the designer to draw in a specific area. After ithas 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 logicalgrid. When this tool is clicked the dragging of the objects become jerky, because theobjects are dragged over the grid. You may try this tool by clicking it, then draw arectangle and drag it using mouse.

Page 14: Swish Climax


Toolbars and Menus

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


Before defining the menus and toolbars it is assumed that you have turned alltoolbars visible. The procedure for doing so is under. Select Menu “View” from mainmenus, 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 beusing the same style. Now we get started with Standard Toolbar.

Standard Toolbar

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

These are the traditional shortcut icons, which are available in almost everyapplication of windows. Cut, Copy, Paste, and Delete work the same way as in otherwindows applications, but in SWiSHMax these are used to perform equivalentoperation upon objects and/or script.

Page 15: Swish Climax


Bring Forward, Send Backward; These shortcut icons are used to change thedepth of objects. For example, you have two objects in your movie. Both arerectangles. One is colored blue and the other one is red. The red on is over the blueone (means some area o blue is under the red one). Now you want to bring the bluerectangle 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 blackarrow”.

Bring to Front, Send to Back; Bring to Front is completely different from Bringingobject Forward. Bring to Front is used to bring desired object on Top (on front of allobjects). For example, you have 5 rectangles in your source move, and you want tobring 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 yourmovie. For example, if you have deleted a rectangle by pressing delete button fromkeyboard, and you want to restore it. You will click undo icon (blue curvy arrow toleft) or press key Ctrl+Z from keyboard. Similarly, blue curvy arrow to right is usedto repeat the last operation (Redo).

Grouping Toolbar

These tools are used to Group, Ungroup objects and Convert several type of objectsto other types. The first icon from left is used to combine one or more objects intoone group, and name it default as “Group”. Further more, groups can be combinedinto single group as well (you can group by using Ctrl+G from keyboard as well). Thesecond 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 whichhas its own timeline). We will discuss Sprite in upcoming chapters. The 4th icon isused to merge many shapes into single shape. By default an emerged shape isnamed as “Merged shape” or “Shape”. But if you combine more shapes with samecolor, the connecting area will become transparent automatically. This can beconsidered as a feature. The last icon from left, is used to ungroup any type ofgrouped objects. Whether they were grouped as “Sprite” or simple “Group”.

Page 16: Swish Climax


Conversion toolbar (part of Grouping Toolbar)

These tools are used for conversion. For example you have a rectangle and you wantto convert it to Button (Button will be defined in detail in upcoming chapters). Whatwill you do? You just select the rectangle by single click and click the left most buttonshown above. It will automatically convert your rectangle to button (if more than oneobjects are selected, this command will convert each to button individually). Next,second one from left is used to convert single or multiple selected objects toseparate “Sprites”. For single object it works same as “Group as Sprite”. The thirdone from left is used to break single or multiple selected objects among sub shapesand group then into separate “Groups”. In case of text, when you select a text objectand click this icon, all the text characters will be converted to shapes and grouped insimple “Group”. It is an advantage when you are using different fonts, than thedefault fonts used by operating system. The 4th icon (convert to letters) is used withtext object only. It is useful when you need to ungroup a text object in separatecharacter objects. Select you text object and click “convert to letters” icon, all thetext will be separated in letters and will be grouped automatically. The last icon isused 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) withbreak style and number of shapes.

Page 17: Swish Climax


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 scenein it, named as “Scene_1”. You may insert as many scenes as you want in yoursingle movie. It is a modular approach to divide major parts of your movie amongdifferent scenes (further detailed discussion can be found in upcoming chapters). Thefirst icon on left side of toolbar is used to insert new empty scene. Second one fromleft the “T” shaped is used to insert text object in your movie. It will insert new textobject by using fonts, colors, direction etc used last time movie edited. The third iconfrom left, green icon is used to insert a BITMAP image into your movie (for nowsupported image formats are BMP, JPEG, GIF, PNG, DIB). The fourth one “InsertContent” or “Import” is used to import WMF (Windows Metafile), EMF (EnhancedMetafile), sound files MP3 and WAV, SWF file, text file, extract SWF from EXEprojector, or even SWI files priorly created with SWiSH 2 or SWiSHMax. The fifthone/second last icon (similar to “Convert to button” icon) is used to insert an emptybutton with light blue color, which is by default 26 pixels wide and 26 pixels tall.Where you can draw desired shapes and text in it.

Movie Control toolbar

Shortcut Icons in this toolbar are used to control your playing movie (withinSWiSHMax). When you play the movie within SWiSH 2 or SWiSHMax interface, thesebuttons are used to control the playing SWF. First two are Stop and Play (no need todefine them I hope). Third one is Play current Scene. Fourth one is used to Playcurrently 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 movieto first frame (frame 1 in SWiSHMax and frame 0 SWiSH 2). Sixth one (two arrowsleft) 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 thistool you can view your movie frame by frame. Just click it and drag it over the effectin 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 themovie). 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 Microsoftvideo file AVI. The fifth icon “Export HTML to Clipboard” is used to copy the htmlcode of the movie to system’s clipboard, which may be then pasted anywhere usingCtrl+V. Next two icons are used for testing your movie. You have two options, either

Page 18: Swish Climax


to test in Browser or in FlashPlayer. The third last icon is used to test your movie inBrowser (latest version of FlashPlayer PLUGIN must be installed on your system). Orif you test it in FlashPlayer by clicking on last icon, there must be Flashplayer EXEavailable 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 withcomplete information of each and every part of the movie and objects holdingspecific number of bytes, see the preview of a normal report:



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

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

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

Page 19: Swish Climax


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

“Samples” menu contains premade samples (by SWiSHZone official designers). Youcan 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 designwindow (Layout Panel).


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 becauseit is not just a copy of any sprite but use to contain all of the peculiarities of thesprite from which it is copied. So “Make Instance” is used to make further Instancesof an existing instance (best way in movie optimization, especially when using sametype of Sprites more than once; further discussion can be found in upcomingchapters).

“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 moviescene. And “Deselect All” is used to selected any selected item(s).

Page 20: Swish Climax


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

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


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

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

Page 21: Swish Climax


“Rulers” menu, which is unchecked by default. It is used to show rulers in designwindow, when checked. The design window looks like below, when it is

selected/checked/turned on:

“Zoom In” and “Zoom Out” menus. If you movie is zoomed 100% and you click on“Zoom In” menu, it will increase 50%. On next “Zoom In” clicks the percentage (ofZooming in) will increase gradually e.g. on second click it will increase movie sizewith 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 thandefault design window size. “Zoom Out” has opposite functioning than “Zoom In”. Itdecreases current movie size to last corresponding size. But remember these do notincrease 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 LayoutPanel or not.

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

Example to clear it: Before Fit (100 or 108%) After Fit (36%)

Page 22: Swish Climax


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


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

Example: After “Show Grid”

Page 23: Swish Climax


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

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

“Show All images” menu, which is turned on by default. If you turn it off it effectswhen you insert images. If it is turned off/unchecked and your image object is notselected, 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 showactual image and all other images (which are not currently selected) will be shown asred 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 isjust to change the view, there will be no effect on exported movie.

Example: Turned on / by default Turned off / unchecked

Page 24: Swish Climax



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

Example Before Inserting frame After Inserting frame

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

Example After Deleting frame

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


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

Page 25: Swish Climax


“Transform” menu is used for rotating, flipping, and resetting (bring to originalposition and angle) the selected object. “Reset” submenu is used to reset theselected object to its actual size and position. What is actual size and position? Forexample you have created a rectangle, and you have stretched / resized or replacedit. 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 usedcommon word processors like Word Pad or MS-Word. Which allow you to Alignyour text on the page. A text object in SWiSH is different from the one inFlash. 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 Boldand Italic. All of these functions are specific to the text objects. First one in last fouris “LR-TB Flow”, which is selected by default. You can select only one direction at atime. The default one is normal direction as the English styled text uses. “TB-RLFlow” is same to one of the functions used for rotating object. If you rotate anyobject on 90 it will work same as said menu function. “RL-TB Flow” menu writes yourtext object in Arabic/Urdu/Persian writing format (right to left). If you use thisfunction with single line text, then it has no same effect as “TB-RL Flow”. But if youselect it with multiline text, it rearranges all the text line. Means, The text flow goesfrom bottom to top.

Page 26: Swish Climax



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

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

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

1. Removing hot key from “File” -> “AVI” menu.2. Select “File” from the Category combo3. Select “AVI” from Commands listbox4. Click in “Current Key” listbox5. Last click on Remove button, and press close button

Hot key / shortcut key is removed for AVI export menu.Now we re-assign a new hot key to it. Follow the above mentioned four steps.

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

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 youhave assigned before. Click “Assign” and then close. New key has been assigned.

Page 27: Swish Climax


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

“Options” tab has four functions. First one is “Show ScreenTips on toolbars”, which isset 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 itsname. If “Look 2000” is checked, it displays flat buttons on interface, otherwise thebuttons are shown using traditional win32 button style. This is turned on / checkedby default.

“Keyboard Map…” menu shows all the shortcut keys assigned and one linedescription of each function of any menu. When you click it, it shows you a dialoglike this one:

Page 28: Swish Climax


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


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

Important panels of SWiSHMax to start working with are “Layout”, “Timeline”,“Outline”, and “Script; and basic property tabs “Object”, “Debug”, and “Export”.

“Layout”, which I have been calling design window. If this is unchecked/unselected,you won’t be able to draw anything. Because when layout is not present you cannotuse design tools.

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

Page 29: Swish Climax


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

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

Applying built-in effects on objects

In this topic we will learn how to insert a normal effect to a text object and arectangle. 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 thetext object is selected. Now right click on the first frame of the timeline (in front ofthe text object), and select custom effect, as shown in the following image:

Page 30: Swish Climax


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. Sincethere are hundreds of built-in effects in SWiSHMax, you can test them yourself. Youcan apply more than one effects on single object, by putting effects in the sametimeline one after each.

Page 31: Swish Climax


Scripting Modes

As we already mentioned that, SWiSHMax has its own complete languagesyntax dictionary for writing SWiSHScript, as well as a sophisticated Script Editor.The built-in Script Editor provides you a big ease by allowing you to work in twodifferent modes.


As Shown in following Screenshot.

Guided Mode Expert Mode

Using Guided Mode you are bound to use the given script syntax, which isuseful for the beginners and intermediate level developers (to start learningSWiSHScript). Further, it provides you a big ease by showing you input fields, whichfulfil the requirements of the specific script. As well as Using Expert Mode you arefree to write anywhere and align your scripts according to your coding style. Whilereading / practicing this book, I would recommend you to use Expert Mode to LearnSWiSHScript properly.

Page 32: Swish Climax


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

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

Very Simple! The Outline Panel contains all of your movie objects in ahierarchical (tree) presentation. More Simple is, all movie objects are listed in theOutline Panel. Now the script you write is always attached with the object currentlyselected in the Outline Panel, either that is a button, a sprite, or any other type ofobject, as shown in following screenshot. A selected object in Outline Panel isautomatically highlighted (as Button is highlighted in example), and then you canstart writing script for that selected object in the Script Editor/Panel. The script willbe attached to the selected object. After moving around other objects, when youreturn to object (you previously wrote script for) you will find the lastmodified/written script in it.

How to put my script/actions in timeline?

I am sure, you are familiar with Timeline Panel/Window. First I must give youthe 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 moredetails in chapter 2, topic 1). I think it is the most simplest/understandable definitionof 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 writeyour script in the Script Editor Panel. But when you select a sprite object fromOutline Panel and write script in Script Editor/Panel, the script goes into the timeline

Page 33: Swish Climax


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 withinthe Frame Event handler (onFrame(){ }). See following screenshot carefully.

Frame 1 (one) contains a stop action and frame 2 (two) contains play action. Bothframes contain separate script. There are two different scripts for both frames 1 and2. 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 asonLoad(){} 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), butreside in the timeline, see following screenshot:

Page 34: Swish Climax


Adding comments in Code

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

Adding comments to SWiSHMax Code (SWiSHScript)

For example we have code:mysprite.gotoAndPlay(15);

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

//go to frame 15 of sprite ‘mysprite’ and playmysprite.gotoAndPlay(15);

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

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

For multiline comments text we will use as follows:

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

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

Adding comments to PHP Code

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

<?//SWiSH MAX Style Comments 1

/*SWiSH MAX Style Comments 2*/

# PHP extra Style Comments

echo “This will be shown on browser”;?>

Page 35: Swish Climax


Chapter 2

Getting Started

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

Page 36: Swish Climax


Movie Physical Objects

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

In SWiSHMax the Movie objects are categorized as:1.Shape2.Text3.Button4.Group5.Sprite6.Instance

In this topic, we will be discussing Text Object, Button Object, Sprite Object,and Instance Object. I would like to concentrate upon core Objects, which will beused 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 isdependent upon the application/design requirements). It has 3 (three) types; eachtype of Text Object is used for different purpose. Before we continue to explore typesof Text Object, we must know how to create a Text Object in our movie.

How do I create a Text Object in my Movie?

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

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

Page 37: Swish Climax


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

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

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

(Note: object also visible in Outline Panel)

a. Static TextAs it is clear from title ‘Static’, it cannot be changed via script (assignment) atruntime. It may have all peculiarities (not properties) usually a text Object has, suchas fonts, color, size, direction, and angle. This type of Object is used for staticheadings, titles, and labels.

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

Page 38: Swish Climax


What Is a variable?

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

Better approach for creating variables is to define them in the start of yourSWiSHMax 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.


Defining a variable:

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

myVar = 10;

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

myVar = 10.34;

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

myVar = “Ali Imran”;


myVar = ‘Ali Imran’;

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

myVar = false;

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

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

Page 39: Swish Climax


How to set Name of a Text Object?

Select the Text Object; go to its properties Tab, and type name of the object inName 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 textproperty, see the following script.

on(press) {MyTempVar = MyObj.text;


on(press) {} the button event handlerMyTempVar a new variable, which will be assigned value of the Text Object ‘MyObj’MyObj.text accessing property ‘text’ of MyObj (Dynamic Text Object)

Moreover, a variable can be attached to Dynamic Text Object. By attaching a targetvariable with a Dynamic Text Object, it becomes easy to get and set value of theDynamic Text Object through that variable directly.

How to attach target Variable with a Dynamic Text Object?

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

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

Page 40: Swish Climax


So it looks like this

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

So we set/attached the variable ‘myVar’ with Dynamic Text Object ‘myObj’.Now we can directly access / modify value of the Text Object without using its ‘text’property, such as

on(press) {MyTempVar = myVar;


on(press) {} the button event handlerMyTempVar a new variable, which will be assigned value of the Text Object ‘MyObj’myVar Variable attached with the Dynamic Text Object(value in MyObj)

And to set new value, we will use it the same waymyVar = “This is my new value”;

Concatenating / JoiningmyVar = myVar + “This is my new value”;ormyVar = myVar add “This is my new value”;

add operator works same as ‘+’

Page 41: Swish Climax


c. Input TextThis type of Text Object has almost same properties as of Dynamic Text, inextension it is used for user input. By using Input Text Object, we can create inputfields, where users can type some value. The same way is used to attach variable toan Input Text object as is used for Dynamic Text Object.

Furthermore, we can restrict the user to input specific characters, by usingCharacter options available, as shown below:

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

Page 42: Swish Climax


Button object

Buttons are built-in structure of an SWF movie, so we can utilize buttonsmaking more and more options (available to user) in our applications (withinSWiSHMax environment). I hope you know how to create buttons (and Group asbutton) in SWiSH.

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

What is Event Handler?

A block of code, through which we can capture the (mouse clicks, keyboard keyspressed, etc) events and perform specific operation on each event occurrence. Forexample, we use on(press) for a Button. on(press) Event Handler is used to capturethe mouse single click (mouse key not yet released) over a button. We put all of ourcode 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, (onmouse click) will be

on(press) { gotoAndPlay(5);}

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

Sprite Object

Sprites are very easy to understand, as I already mentioned, “Sprites areSub-Movies within Main Movie”, which may contain further Sub Movies and differentObjects. A sprites uses to have its own timeline and frames.

How to group some of my objects in single sprite?

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

Page 43: Swish Climax


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 themovie using gotoAndPlay() function, for sprite we will be putting a prefix path to thesprite and then call the function. Assume we have a sprite named ‘xyz’ in maintimeline, and a button. When the button is clicked the sprite goes to frame 10 (ten)and play.

Button Event Hander and codeon(press) { xyz.gotoAndPlay(10);}

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

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

Assume we have Dynamic Text Object and its variable ‘myVar’ in the sprite xyz; andwe 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-spritenamed ‘cde’, and then cde contains a variable myotherVar. See how we haveaccessed 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 InstanceObject.

Instance Object

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

Page 44: Swish Climax


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

How to make a copied sprite Instance of other sprite?

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

Data types and Variables

Data / Information may be of any form. The Data usually processed by ourcomputer applications is of limited types, such as Text data, Numeric data, andlogical true/false (Boolean) data. So whenever we need to store and retrieve datainto/from computer memory we use variables to store it. Variables may be definedas ‘a name or textual representation, that identifies a specific location of memoryholding 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 uponour application requirement the type of data we will be holding in variables.

How to define a new variable?

Defining a variable in SWiSHScript is so easy, simply use new variable nameand assign it some initial value, variable is created, see below:

varname = some value;myVar = 10;

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 orvariable 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

Page 45: Swish Climax


myVar is the name of new variable and 10 (ten) is its initial (numeric) value. So ournew variable ‘myVar’ contains a numeric value 10 (ten), which may be changedanytime through script using same expression (e.g. ‘myVar=20’), that we used whilecreating 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 tovariable on left side of it. Which will be discussed in detail in upcoming topics.

Numeric type data (Integer/Float)

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

Integer type variable myVar = 10;Float type variable myVar = 10.43;

When value of an Integer type variable crosses number like 65535, isconsidered as Long type variable; as well as, there is a limit for Float values, whenvalue is more than that specific limit, it is treated as Double. For now, you don’tneed to worry about these extra types, because type is adjusted automatically, bythe Flash Player which runs our movie.

Textual/Text Data (String)

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

How to define a String type variable?

varname = “some text value”;myStrVar = “this is my Text”;

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

myStrVar = ‘this is my Text’;

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

Page 46: Swish Climax


True/False type data (Boolean)

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

Defining a Boolean type variable

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

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

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

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

Type Casting or Type Juggling

Type Casting is a terminology used in powerful languages such as C/C++ andalso in Flash MX ActionScript. It is also called Type Juggling in PHP language. Whichmeans, conversion from one data type to another data type. Let me quote an easyexample to make it more clear. For example: you have a variable ‘myFloatVar’ thatcontains a numeric value, and value type is Float (means, value has fractions), say13.25, and you want to get its Integer value through Type Casting, so that, it givesyou round value of 13 (thirteen), in stead of 13.25.

Assume myFloatVar is priorly defined as:myFloatVar = 13.25;

Type Casting, and putting result in another variable ‘myTCv’:myTCv = int(myFloatVar);

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

In previous example of Type Casting we did conversion between almostsimilar data types (Integer and Float both are numeric). Question is: What does aBoolean value (true/false) give back, when it is converted to Integer using TypeCasting method int()? Answer is so simple: if the value being converted is true, theresult will be numeric 1 (one), otherwise if it is false, the result will be 0 (zero).E.g.

Page 47: Swish Climax


myBVar = true;myIVar = int(myBVar);

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

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

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

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

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

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

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

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

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

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


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. Seeexamples:

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


myStr =”7.33xyz”;

Page 48: Swish Climax


myFloat = parseFloat(myStr);

In both cases, value of variable ‘myFloat’ will be having numeric value 7.33. Insecond example (of above two), the characters ‘xyz’ have been recognized as non-numeric, and ignored while conversion. So we can say, function parseInt() andparseFloat() 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 inNaN (Not a Number).

You can also obtain Integer or Float value out of Hexadecimal, Octal and Binary typedata, 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. FunctionparseInt() with 2 (two) arguments may not be supported by older builds ofSWiSHMax.

SWiSHScript Basics

There is no prior knowledge of scripting required in order to studySWiSHScript basics. This book guides you through all the levels of SWiSHScript. So,the key to learn SWiSHScript fully, is to pay full attention to each and every line ofthe book.

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


A = B + C;

Expression : B + C Add B to CAssignment : A = And save result in A

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

Let us get started with Mathematical Operators first.

Page 49: Swish Climax


Mathematical Operators

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

Addition or Concatenation Operator (+, add)

Addition Operator ‘+’ (plus) is used to sum/join two or more variables/values.Previous example shows how to sum two variables, I repeat it here

A = B + C;

Variable ‘B’ is added to ‘C’ using Addition operator and result has been assigned tovariable ‘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 bejoined/concatenated with each other the same way we sum Numericalvalues/variables. See example

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

Result = Str1 + Str2;


Result = Str1 add Str2;

Where ‘Str1’ and ‘Str2’ are String type variables, they are joined usingConcatenation/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) differentoperators for same purpose?

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

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

Page 50: Swish Climax


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

Str1 = “Ali Imran is of ”;myInt = 27;Result = Str1 add myInt;

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

Deduction/Subtraction Operator

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

So the expression will be:

A = B - C;

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

Multiplication Operator

For performing multiplication between two or more variables/values we useMultiplication Operator ‘*’ (steric). This operator is specific to Numeric operations.


A = B * C;

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

Division Operator

This operator ‘/’ (forward slash) is used to divide value on left side among thevalue on right side of the operator. Same to the Multiplication and SubtractionOperator, this operator is also specific to Numeric operations. See following exampleto 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

Page 51: Swish Climax


This is some unique operator to you, I hope. Remainder Operator ‘%’(percent sign), is used to divide the value of on left among the value on right andthen assign the resulting remainder obtained after division to another variable. Forexample:

See Division firstB = 5;C = 2;A = B / C;

Here Result is 2.5

But if we use Remainder Operator instead of Division Operator as:B = 5;C = 2;A = B % C;

Will result 1

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

Compressing the Mathematical operations code

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

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

Technique is so simple, please pay full attention, sew following code:V += 5;

This performs same operation as V = V + 5;

Technique is:

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

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

Page 52: Swish Climax


Increment and Decrement Operators

These are the useful operators that make your code more compressed andeasy to read. Increment ‘++’ (two consecutive plus signs) and Decrement ‘--‘ (twoconsecutive 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 alsouse the operator before (as prefix) the variable name, such as:

V = 5;++V;

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

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

V = 5;V--;


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 canbe used either as prefix (before variable name) or suffix (after variable name), thenwhat is the difference?

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

Value of ‘A’ is still 5 (five)

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

Page 53: Swish Climax


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

B = 5;A = ++B;

Value of ‘A’ is 6 (six)

In this example, value of variable ‘B’ is incremented by 1 (one) before it is assignedto variable ‘A’, because Increment Operator is used as prefix to the variable ‘B’.

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

Use of Brackets in mathematical expressions

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

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 givento multiplication and then Addition. I hope, we do not do any more mistakes nexttime, in numerical operations.

Comparison Operators

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


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

It is time to get started with Comparison Operators.

Page 54: Swish Climax


Comparison Operators

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

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

A != B To check Inequality (if A not equals to B - A may begreater or less than B, but not equal)

A > B To check if A is greater than B

A < B To check if A is less than B

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

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

(From now on all code color switches to blue)

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

Taking decisions in SWiSHScript using ‘if’

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

Page 55: Swish Climax


if-else Control Structure

It is a control structure which is used to take decision on a specific condition,and execute specific code. It is the easiest structure to implement in our script. Seethe syntax as follow:

if ( condition_block ) { code_to_execute}

Simple example of Numeric data comparison:

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


if is keyword (reserved word)

{ is start of block which contains code to beexecuted

speed == 10 is the condition to be checked

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

} is end of block which contains code to beexecuted

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 otherhand if value of variable ‘speed’ is not equal to 10 (ten), the code (within curlybrackets { 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”;}

Page 56: Swish Climax


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

Required and non-required curly brackets in SWiSHScript

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

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

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

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

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

So the code for last example of game shrinks down toif( speed == 10 ) message = “You are too slow”;if( speed == 80 ) message = “Ideal Speed”;if( speed == 120 ) message = “Slow Down, it is dangerous”;

There are some more Comparison Operators in SWiSHScript to be used forString data type comparison, they are:

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

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

Page 57: Swish Climax


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’ ata time. Better approach is; We must execute one of the ‘if’ blocks where condition istrue 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 beexecuted 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 endof if-else blocks chain.

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

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

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

So replace ‘i_am_executed_when_all_above_are_false’ with the statement you wishto execute, when all above conditions are false; so that, it becomes almost like this:

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

Page 58: Swish Climax


else if( condition ) …….else message = “All above conditions were false”;

Question (b): I have 3 (three) ‘if’ blocks, each has separate condition, but I want,when the conditions in first and second ‘if’ block (both) become true, execute singlestatement. 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 ofLogical Operators which join two or more conditions within single ’if’ block. So let usmove to Logical Operators.

Logical Operators

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

For joining more than two conditions:if( condition_1 logical_operator condition_2 logical_operator condition_3)

Logical Operators AND ‘and’ or ‘&&’

Following examples + figures will make you all clear.For Example, my conditions are (in pseducode not actual code):

Translating PSEUDOCODE it into SWiSHScript code:PSEUDOCODE : Normal Language words used to express the code.

IF A equals 10 AND B equals 12

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


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

Or conditions may be different from each other as:

IF A equals 10 AND B is greater than 12

Page 59: Swish Climax


if( A==10 and B > 12)


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

This Logical Operator ‘and’ or ‘&&’ is used when you need to take actions if allconditions 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 traditionalprogramming 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 andSWiSHScript, we have choice to use either.

Implementing code for Question (b) in previous topic:

if(A==10 and B>12)message = “Both conditions met”;

if(A==10 and B>12) if value of variable ‘A’ is 10 and value ofvariable ‘B’ is greater than 12, then,

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

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

Logical Operator OR ‘or’ or ‘||’

Another case is, we want to execute a statement (or set of statements in {and } block), when any of the conditions is true in a single if block. What do we do?Simply we join the conditions using Logical Operator.

Page 60: Swish Climax


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

Translating PSEUDOCODE it into SWiSHScript code:PSEUDOCODE : Normal Language words used to express the code.

IF A equals 10 OR B equals 12

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


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

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

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

if(A==10 or B==12) if value of variable ‘A’ is 10 or value ofvariable ‘B’ equals 12, then,

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

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

Nested if Blocks

Sometimes our application requirements are different, we need to keepfurther checks (check more conditions) after one condition is already met/true. Sowe implement nested ‘if’ structure (‘if’ blocks within ‘if’ blocks).



IF B is not equal to 10 THEN



Page 61: Swish Climax


Implementing above PSEUDOCODE example in SWiSHScript code:

if(A==10) {if(B!=10)

Message = “Both are not 10”;}

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

Ternary If-else structure

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

This structure is implemented within expressions. We know that there is nokeyword ‘THEN’ in SWiSHScript to use after ‘if’ statement condition part. As youmight already have used in Visual Basic / QBasic / Pascal Language / VBScript etc,such as


In SWiSHScript we don’t have this keyword ‘THEN’ and we directly write ourstatement 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 actas ‘THEN’, and an operator acting as ‘else’.

How to implement Ternary if-lese structure within expressions?Take the above example to implement it within expression (see example)

C = X<10 ? false : true;

X<10 if value of variable ‘X’ is less than 10,which is equal to code if(X<10)

? false THEN C is false: true else C is true

so we can say

Page 62: Swish Climax


? acts logically as THEN: acts logically as else

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

if(X<10) C = false;

elseC = true;

C = X<10 ? false : true;

Loop Structures

What is a Loop?

Loop means structure that implements a method of repeating / iterating astatement or set or statements while a condition is true. Loop may be used to iteratestatement(s) up to a specific number of times.

Let us get started with ‘while’ loop

‘while’ loop

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


while( condition ) { if this condition is true code to execute repeatedly execute this code again and again}

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

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

Page 63: Swish Climax


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

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

First part (initialization):Initialize the variable ‘X’X = 0;

Second part (condition):Implement loop structurewhile(X<15) {

Third part (change in value of variable used in condition):Now increase value of variable ‘X’ by 1 (one), each time loop executes the codeX++;

} closing the loop block

so it becomesX = 0;while(X<15) {



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

One thing more, as I already mentioned (while studying ‘if’), that, if we have morethan 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 createblock for it. The code becomes:

X = 0;while(X<15)

X++;Orwhile(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) {

Page 64: Swish Climax




it will result in debugger (within SWiSHMax) as:01234

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

Coding style and saving lines

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

‘do-while’ loop

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

Structure of ‘do-while’ loop

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

In do-while loop, either you have one or more statements to be executed, you willhave to create block using { and }. This is restriction of syntax which must befollowed, 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 comethe 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, thecondition is checked before the code is executed. But in ‘do-while’ loop, first the codeis 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. Thevalue of variable ‘X’ becomes 16 (sixteen) before the condition is checked. Whencondition 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.

Page 65: Swish Climax


It also has 3 (three) parts of implementation, 1.initialization, 2.change invalue of variable used in condition, and 3.check condition.

‘for’ loop

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

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

In previous topics we divided the ‘while’ and do-while’ loops in 3 (three)parts. Those 3 (three) part were:

1.Initialization2.Condition3.Change in value of variable used in condition

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

for( initialization ; condition ; change in value of variable) { code to execute repeatedly}

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

Example we used for ‘while’ loop was:

X = 0;while(X<5) {



Page 66: Swish Climax


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

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

for( keyword to start implementation of ‘for’ loopX=0; initialize the variable (acting as counter) with

value 0 (zero)X<5; check condition each time if value of variable ‘X’

is less than 5 (five), execute the code.X++ increase the value of variable ‘X’ by 1 (one), after

condition has been checkedtrace(X); built-in function to show flow of execution} close the block created for ‘for’ loop

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

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

for( I=1; I<=3; I++) { message = “value of I is “ add I;}

which will result as the change in value of variable ‘message’ 3 (three) times.First time value of variable ‘message’ will be value of I is 1Second time value of variable ‘message’ will be value of I is 2Third 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 byone so fast (if you are displaying on screen).

Breaking loops Unconditionally

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

To break a loop unconditionally, we use a keyword ‘break’ (which is notfunction) but acts as function get into the internal structure of the loop. Within theloop we call this functionality when we after checking some condition, see example:

Page 67: Swish Climax


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


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

for( I=0; I<1000; I++) {if(I >10) if value of variable ‘I’ is greater than 10,

break; break current loop}

Skipping the code in loops, Unconditionally

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

for( I=1; I<=100; I++) {if(I%2 != 0)



We used a new keyword ‘continue’ to skip the code ‘trace(I);’ to be executed,unconditionally. Why do we call it unconditionally, when we are implementingcondition for it? Because we ordered the loop to skip it at certain point, if we did nothave done this, the loop had continued with each number and displayed all thenumbers in debugger (even if they are not divisible by 2 (two)).

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

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

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


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

Page 68: Swish Climax


Tuning up code with ‘switch’ set statement

‘switch’ is also a powerful structure that is used in all most powerfulprogramming languages such as C/C++, Java, Flash MX ActionScript, SWiSHScript,PHP etc. In most cases, it provides an ease to get rid of much more if-elsestatements in your SWiSHScript code.

To understand ‘switch’ structure, first, we must implement an example of if-lese chain of conditions. After it, we will translate the chain of if-else into switch. Solet us have our previous example of ‘car speed on road’ which was:

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

Better implementation and use of ‘switch’ is, when your application needs to keepcheck on single variable (as it is in above example, variable ‘speed’). So afterconverting 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”;


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

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

For example, we want a statement to be executed when all the conditions becomefalse. As we did in if-else examples, we put an ‘else’ and joined new statement withexisting 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’ inprevious ‘switch’ example. Now we implement the last blue part of above example

Page 69: Swish Climax


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

Some addition to ‘switch’ will be

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

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

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

switch( speed ) { case 10:

message = “You are too slow”; break;

case 80: message = “Ideal Speed”;


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


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


The newly added code is styled BOLD.

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

Working with Functions

What is a function?

1. Function is a named routine in our code.2. Function is set/combination of several executable statements3. Function is set of statements to perform a specific piece of task.

Above are the 3 (three) simplest definitions of a function.Why do we create our own functions?

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

Page 70: Swish Climax


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

Creating your own Functions

We have seen many of the built-in functions we used within our SWiSHScriptcode. 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 todefine a function within an event handler (say onLoad()) or other function, we do itdifferent way:

onLoad () {function_name = function () {

set of statements to execute…………


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

Example:We will write a new function, which will display (in SWiSHMax internal

debugger) all numbers divisible by 3 (three) between and 10.

function myFunction() {for(I=1; I<=10; I++) {

if(I%3 == 0)trace(I);


we create a new button in our moviethen we call this function in event on(release) of the button, as:

on(release) {myFunction();

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

You can open example file function1.swi and test it yourself.So the code (within function) is executed, and results in debugger as like:

Page 71: Swish Climax


Click this button in example

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

Writing functions that accept arguments (accepting parameters)

What are arguments/parameters of a function?

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


‘12’ is the argument/parameter passed to function gotoAndPlay(). So we can saythis function accepts one argument. If any function accepts more than onearguments, we separate them with comma ,. Such as:

duplicateSprite(“xyz” , 2);

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

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

function function_name (arg1 , arg2 , ……) {}


Page 72: Swish Climax


following example is contained in file function2.swi.

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


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

on button action the code is

on(release) {myFunc2(5);


The result in debugger isClick this button

Creating functions which can return a value

In our previous examples of functions, we used to display the results (usingtrace()) from within the functions. Now our requirements have been changed. Wewant to write a function which will square the number passed to it (as argument),and return the square back, so that we can store that square value in some othervariable. Here, we introduce you a new keyword ‘return’, which allows a function toreturn value back to the caller.

Page 73: Swish Climax


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

Open file function3.swi, which contains:

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


on button action the script ison(release) {

tempVar = mySQR(4);trace(tempVar);


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

tempVar = mySQR(4); create new variable ‘tempVar’ and put thevalue returned from function ‘mySQR’ init.

trace(tempVar); display the value of variable ‘tempVar’ (indebugger), the value returned fromfunction ‘mySQR’.

This method is very useful, when we need to distribute the statements amongseveral 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 bewriting variety of functions/routines when we get into final chapters of this book. Fornow, this is just a description to give you start.

String manipulation functions

Page 74: Swish Climax


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

Function and expression Usage Result

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

Up to here, we have studied almost all of the Control structures of SWiSHScript.Now, we will move to most commonly used object (sprite, button) and their commonproperties and event handlers.

Button and Sprite Object properties and event handlers

Button Object properties

A button uses to have some properties which can be accessed throughSWiSHScript. Some of the properties are specifically for button object, and the restof the properties (we will discuss), are specific to the sprite object. Let us see thesome of the useful properties specific to the button object.


‘useHandCursor’ property of a button object is of type Boolean (true/false).this property is used to set the default had mouse cursor ON or OFF. A button objecthas default mouse cursor as a small hand (when mouse cursor is over the button),shown below:

Page 75: Swish Climax


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

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

button_name.useHandCursor = false;

You must set a name for button object button before modifying its useHandCursorproperty. When you create a new button or convert some shapes to button object inSWiSHMax, you can see it is unnamed and by default is set to Button, as shownbelow:

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

As I named it myBtn, so that it looks like

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

myBtn.useHandCursor = false;

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

myBtn.useHandCursor = true;


This property is also of type Boolean. By assigning false to this property of abutton object, will result in, the button will not function anymore. Means, any actionto be taken/associated with button object, will not work anymore. Simply, by settingit to false, means to disable the button object completely.


button_name.enabled = false;

Page 76: Swish Climax


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

myBtn.enabled = false;

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

myBtn.enabled = true;

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

Button Object Event Handlers

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

on(release) {take_some_action


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

on(press) {take_some_action


Page 77: Swish Climax


Some more event handlers can be implemented as:

rollOver when mouse cursor is rolling over the button objectrollOut when mouse cursor rolls out of the button object areadragOver when mouse button is pressed and moving (not released)dragOut when mouse button was pressed but taken out of button

boundaryreleaseOutside when mouse button pressed and taken out of boundary and


Implementing event handlers as functions

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

myBtn.onRelease = function() {take_some_action


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

Event Name Equivalent Event Handler

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

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

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

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

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

Page 78: Swish Climax


These are 15 (fifteen) keys to capture, already available in SWiSH max script editorevent 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 youwish 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), anybutton, sprite, etc. In following example of SWiSHScript we have implemented anevent handler ‘onKeyDown’ for _root (the root path of the movie), so, wherever thekey is pressed can be captured. And then we passed the _root object to a function‘addListener()’ of the ‘Key’ built-in object. See following example code from key.swi:

onLoad() { implement onLoad event handler in _root_root.onKeyDown = function() { implement onKeyDown event handler for


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


Key.addListener(_root); Add new listener for _root to built-inobject ‘Key’ for the


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

Page 79: Swish Climax


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

onLoad() { implement onLoad event handler in _rootmyBtn.onKeyDown = function() { implement onKeyDown event handler for

button object ‘myBtn’code = Key.getCode(); Get Key code of the last key pressed and

assign it to variable ‘code’ }; Key.addListener(myBtn); Add new listener for button object ‘myBtn’

to built-in object ‘Key’ for the}

Above example will show the Code of the last key pressed (on keyboard) in the textbox. Now, the next example captures Up and DOWN key press, using the built-infunction ‘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 thekey capture with any object and did not add any new Listener. So this is the bestmethod to capture key strokes in SWiSHScript.

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

Sprite Object properties

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


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


myVar = mySpr._currentFrame;

Page 80: Swish Climax


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

myVar = _root._currentFrame;

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

myVar = _level2._currentFrame;


This property ‘_totalFrames’ returns the total number of frames in a sprite,path, or level. Syntax for using this property is as simple as the previously discussedproperty, see example:

myVar = mySpr._totalFrames;

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


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


myVar = mySpr._framesLoaded;


myVar = _level2._framesLoaded;

Note: both of the properties (_currentFrame, _totalFrames) are of integer type. Sothe value obtained from these properties, must be treated as integer value. And bothare read-only properties which means, they cannot be assigned value, but, valuescan be obtained from them.

Page 81: Swish Climax


Properties that are available for both Sprite and Button Object

Let use put some light on physical properties of both button and spriteobjects._x get/set X coordinates of the object_y get/set Y coordinates of the object_width get/set Width of the object_height get/set Height of the object_alpha get/set Alpha/Opacity/Transparency of the object (minimum 0,

maximum 100)_rotation get/set rotation (rotate) angle of the object (0..360).

Frequently used functions available for sprites/movie control


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


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



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


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



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



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


Page 82: Swish Climax


This may also work with labels.

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

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


Page 83: Swish Climax


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



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


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


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


Some additional functions for movie control

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

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

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

nextSceneAndPlay() Go to next Scene (of movie) and playnextSceneAndStop() Go to next Scene (of movie) and stop

prevSceneAndPlay() Go to previous Scene (of movie) and playprevSceneAndStop() Go to previous Scene (of movie) and stop

Page 84: Swish Climax


Event Handlers for Sprite Object and Main Movie ‘_root’


This is most frequently used event handler in SWiSHScript. It is used toimplement a specific piece of code to be executed when a specific frame of a sprite /main movie is played. Syntax:

onFrame(15) {take_some_action


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

This event handler must be implemented within the timeline of specific object itrelates to. E.g. if it is required to be implemented for a specific sprite, then it mustbe 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 sameScript Panel area. This feature is not available in Flash MX ActionScript Editor; InFlash MX all frames’ actions cannot be put within one script area, you have to writecode for each frame separately. So, this is a big advantage in SWiSHMax.


This event invoked/fired/generated when a Sprite or _root is started loadingby the Flash Player. So this may be used as a Constructor in C++ class, to do initializations. Thisevent handler is usually implemented when we need to do initializations in the spriteor main movie. example may be of creating / defining new variables and assigningthem initial value, defining custom functions. Simple example:

onLoad() {myVar = 0;


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

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

Page 85: Swish Climax


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

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

onLoad() { onLoad() event handler of main moviemySpr.onLoad = function() { onLoad() event handler of sprite ‘mySpr’

myVar = 0; initialize variable of sprite ‘mySpr’};



I don’t want you to mess with this event handler name ‘onEnterFrame’. Justremember 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 whichiterates all the time”. Whatever code you put in it, is executed all the time, themovie/sprite is playing. This event handler can be implemented for every Sprite andMain Movie individually. By the Way: putting huge set of code in it will cause your movie slow downeven 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 timeand assign it value of the current frame (being played) of sprite ‘mySpr’. Use thesame way to implement for any sprite.

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

onLoad() {mySpr.onEnterFrame() {

myTxt = _currentFrame;};


Page 86: Swish Climax


My first SWiSHScript application

Please open file 001.swi before you continue reading.This file contains 4 (four) objects, Static Text, Dynamic Text, Input Text, and aButton Object. This simple application demonstrates how to assign a value to adynamic text Object. In this example, user will enter his/her name in the Input TextObject and that name value will be displayed in Dynamic Text Object by adding‘Hello’ as prefix.

Script for the button object

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

Page 87: Swish Climax


Understanding Levels

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

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

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

How to load an external Movie in Sprite?

Please open file 002.swi before you continue reading.onFrame(1) { mysprite.loadMovie(“external1.swf”);}

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

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

How to load an external Movie in Higher Levels?

Please open file 003.swi before you continue reading.This time we are loading the same ‘external1.swf’ in Level 1, the code would be

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

Page 88: Swish Climax


Remember: If you load an external movie in Level 0, that will replace the actualmovie already in Level 0. So preventing from this conflict, always load movies inhigher 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 willhave to target the path first, or use _levelN prefix path before function (where N islevel number), e.g.

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


Targeting the path and then using function or putting some expressionon(press) {

tellTarget(_level1) {gotoAndPlay(10);

}}oron(press) {

tellTarget(_level1) {someVarInLevel1 =”some value”;


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

tellTarget(sprite_name) {someVarInSprite =”some value”;


For unloading/removing movies loaded in higher levels, use functionunloadMovieNum(N), (where N is level number) e.g.

Open sample file 004.swion(press) {


Same for unloading/removing movies loaded within sprites, use functionsprite_name.unloadMovie(),e.g.

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

Page 89: Swish Climax


_root, _parent, this, and _global

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

Variables Scope in SWiSHScript

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



Using _root object we can point the variables/sprites/text objects/buttons ofmain timeline directly. See 006.swi, contains following code (on button event):

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


Using _parent object we can point any variables/sprites/text objects/buttonsin parent path (which may be a sprite or _root). E.g. we have a sprite called ‘a’,which contains further sub sprite called ‘b’ (means ‘b’ is within ‘a’, and ‘a’ is within_root). Now the following script is in sprite ‘b’, which is assigning a value to variable‘v’ in its parent sprite ‘a’, Open 007.swi to see the following code.

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

Following screenshot will make clear it to you:

Page 90: Swish Climax


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

Screenshot of 008.swi making it more clear:

E.g. Targeting a variable ‘y’ defined in sprite ‘a’ contained in root. What should we doif 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’.


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

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

Page 91: Swish Climax


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

Why use _root, _parent, or this?

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


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

_global.myVar = 786; a new variable ‘myVar’ has been createdan global variable and has been assigneda new integer value of 786.

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

varInSprite = myVar; assumed local variable ‘varInSprite’ in anysprite is assigned value of global variable‘myVar’ directly without any prefix path,such as _parent.myVar.


myVar++; increase value of global variable by 1(one).

Use of ‘tellTarget’

Traditional way (followed from flash 4 up to now) of targeting specific pathand then accessing its properties/variables/sub objects/functions/etc directly withoutany prefix path, is using ‘tellTarget’ control structure. Example:tellTarget(_root.mySprite) {

spriteVar = 1;gotoAndPlay(“lable2”);


Page 92: Swish Climax


structure of ‘tellTarget’ is very simple to understand, “target a path/sprite/level anduse its inner things”.


tellTarget(_root.mySprite) { Target/Get into sprite ‘mySprite’ createdin main timeline ‘_root’.

spriteVar = 1; Assign value 1 (one) to variable ‘spriteVar’defined in the sprite we targeted‘mySprite’.

gotoAndPlay(“lable2”); Jump to Labeled frame ‘label2’ in spritewe targeted and play the sprite.


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

Why not to use this way directly as following?

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


As I already mentioned that, ‘tellTarget’ is the traditional way not compulsory/onlyway, so it is not compulsory to use it, you may use any of the ways seems easy toyou. But I will follow direct method and not using ‘tellTarget’ structure anymore innext upcoming examples and topics. It is being discussed here, just to give you ideaof almost complete control structures dictionary of SWiSHScript.

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

tellTarget(_level2) {take_some_action


Page 93: Swish Climax


Use of ‘with’

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

Use of ‘with’ with text object

with(myTxtObj) { point the text object ‘myTxtObj’ to accessits properties.

_text = “I am vale of myTxtObj”; assigning value of property ‘_text’ of textobject ‘myTxtObj’ (used in ‘with’structure).


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

with(mySprite) { point the sprite object ‘mySprite’ to accessits properties and functions.

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



with(mySprite) { point the text object ‘mySprite’ to accessits properties and functions.

spriteVar = 786; assign a new integer value to the variable‘spriteVar’ defined in as local variable ofsprite ‘mySprite’.


Dragging the objects at runtime

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


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

startDragUnlocked with constraints:

If same function ‘startDragUnlocked’ is passed the boundary of the drag area itmakes the object dragable within specified boundary. See example file drag2.swi.See code on button in sprite.

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

argument is 100 maximum bottom.

Page 94: Swish Climax



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 argumentsthat we used in previous example. But my personal observation is, users do not likethe Locked dragging because the object is automatically repositioned when drag isstarted, so it looks a bit jerky in start.


Stop the dragging, it is the single function to stop any type of dragging beingperformed.

Page 95: Swish Climax


Chapter 3

TEXT/JPEG File Management withSWiSH MAX

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

Page 96: Swish Climax


Loading data from Text Files, loading external JPEG files

This technique may be used on web as well as on local computer (withoutusing PHP). For example you are developing a huge presentation; you want its textbe loaded from text files and then process it according to the presentation needs.What will you do? You will maintain many text files and put text data in them.

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

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

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

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

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

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

this current pathloadVariables(); function used to communicate a script file or load data from

text file (its communication with scripts will be discussed inchapter 4)

When button is clicked in above example 009.swi, it loads the text file and changethe 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 TextObjects in it; their variables are ‘myName’, ‘myAge’, ‘myEmail’. This example loadsdata from text file ‘data2.txt’, which contains:

&myName=Ali Imran&&myAge=27&&[email protected]&

Each Variable assigned a value on separate line.

Loading external JPEG files

Page 97: Swish Climax


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

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

Open 010.swi that contains a sprite named ‘jpg_loader’ and a button, whichperforms 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 arectangular shape in it. That shape is aligned Top-Left (set from transform propertiestab) and is put on 0 (zero) as x, 0 (zero) as y, which means the JPEG’s (to beloaded) 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 setits Opacity/Alpha to 0 (zero) or Transparent, from Tint property Tab, as in examplefile 012.swi.

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

Creating static Address Book with images (without PHP)

At this point when we have not yet started learning PHP yet, we will be usingplane 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 JPGimage will be loaded), and two buttons to go to next and previous entry in theAddress Book. The best way of doing all this is to use ‘Dynamic variables’ andevaluation (use of eval() function), but as we are not yet familiar with this, wecontinue with direct method.

Page 98: Swish Climax


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

How to make a Dynamic Text Object multiline?

Make a Dynamic Text Object (as demonstrated before), and select ‘Dimensions’ fromdrop 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 shownbelow:

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

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

Page 99: Swish Climax


Preview of the Address Book

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

Date in our text file ’data2.txt’ is

&myName=Ali Imran&&[email protected]&&myAddress=Islamabad, Pakistan&&myPhone=not available&&myphoto=contact1.jpg&

&myName2=Ali Roman&&[email protected]&&myAddress2=Taunsa, Pakistan&&myPhone2=PPPPPPPPPPP&&myphoto2=contact2.jpg&

&myName3=James&&[email protected]&

Page 100: Swish Climax


&myAddress3=SWiSHZone pty, ltd. Australia&&myPhone3=OBTAIN FROM SITE 123&&myphoto3=contact3.jpg&


We receive following variables (in SWiSH movie) when ’data.txt’ is loaded:myName, myEmail, myAddress, myPhone, myPhoto, myName2, myEmail2,myAddress2, myPhone2, myPhoto2, myName3, myEmail3, myAddress3, myPhone3,myPhoto3, and done. Variable ‘done’ has already been defined, but rests of thevariables do not exist in our SWiSH movie previously. As we know that thesevariables exist in the text file, so we will 100% be sure that we have received themin our movie, after loading the text file.

Defining the code in 013.swi in main timeline:

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

What is onLoad()?

It is an event handler (or event procedure/function), that runs automatically when amovie starts loading. So whatever code you put in this hander, will execute whenmovie is run. This handler can also be put/attached with sprites, to execute someinstructions immediately when a sprite is loaded in FlashPlayer.

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

this.loadVariables(“data2.txt”) load variables from data2.txt in current pathwhich is _root (main movie timeline)

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

done=0; simple variable but working as flag, tells either toprocess entry or not. It is initially set to 0 (zero),because we do not want following code toexecute while text file is being loaded.

When we go forward reading the code we find:onEnterFrame() { if(done==1) { if(current == 1) { myPhoto.loadMovie(myPhoto); myName_v = myName;

Page 101: Swish Climax


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 codeall the time (either in _root or sprite)”. It is very useful when we need to keep checkon some variables, changed oftenly in the movie, such as variable ‘done’ we haveused.

if(done==1) a conditional block which executes when value of variable‘done’ is 1 (one)

if(current == 1) When variable ‘done’ is 1 (one), it means we have to processentry number ‘current’ (which is 1 (one) by default), and thenwe check the variable ‘current’, 3 (three) times. After thecondition is met and ‘current’ is 1 (one), we put newly receivedvariables’ values in Text Objects, and loaded image for thecontact in a sprite named ‘myPhoto’, as shown below:

myPhoto.loadMovie(myPhoto); myName_v = myName; myEmail_v = myEmail; myAddress_v = myAddress; myPhone_v = myPhone;

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

Buttons’ Actions defined:

Page 102: Swish Climax


Button used for next entry named ‘next’

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

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

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

Button used for previous entry named ‘prev’

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

if(current > 1) check variable ‘current’ if it is already on first entry, and cannotmove back. If it is not then,

current-- decrease value of ‘current’ by 1 (one).done=1 Tell the event handler onEnterFrame() to process previous


Two more objects Info_Area and Background are only to draw layout of our AddressBook.

Page 103: Swish Climax


Chapter 4

Interaction with PHP

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

Page 104: Swish Climax


Sending data to PHP script

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

How to add HTTP method as argument to function loadVariables(), if my server doesnot allow globals?

Send variables via POST method:Path.loadVaribles(“script.php”, ”POST”);

Send variables via GET method:Path.loadVaribles(“script.php”, ”GET”);

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

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

Receiving data from PHP script

Same function loadVariables() is used to send and receive data variablesto/from a PHP script. Then why we have split this information among two topics ofthis chapter? Only because, at this point we will be demonstrating the way ofsending variables from PHP back to SWiSH movie; For doing this, we must learnsome basics of PHP.

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

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

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

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



Page 105: Swish Climax


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

My first text echo application

In this topic we will demonstrate, how to create a small application sending avariable data to PHP script (script002.php), then send back the same data asdifferent variable to SWiSH MAX Movie (from PHP). Open 014.swi and have a look.

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

In button’s press event handler we have code as below:on(press) { this.loadVariables("script002.php", 'POST');}

this.loadVariables("script002.php" Sending all the data variables (available incurrent path) to the PHP script(script002.php).

'POST' Send data via POST method

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

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


&myVar2= Send response back to SWiSH moviein variable myVar2

$myVar is the PHP variable we sent fromSWiSH Movie.

Note: PHP variable ‘$myVar’ is within double quotes “ and “. Which means variablesare 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.

Page 106: Swish Climax


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 andrun 014.swf via typing its complete URL in browser (hint: try different name eachtime). You may also text it on local computer, if you already have installed PHP onlocalhost.

Creating E-Mail Contact Form, mail in PHP

This is the most wanted resource all over the net. Most of the people search for suchforms where users (or their clients) can contact them via a simple form; you wantusers 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) withrequired fields, and use function loadVariables() (in SWiSH MAX) to pass on theinformation to PHP. Where PHP will be using built-in mail() function to send emaildirectly to your (or you company) email address. THEN WHY NOT TO IMPLEMENTOUR OWN FORM? Because our major goal is to learn, not to copy.

Open 015.swi, before you continue further.This file contains total 10 (ten) objects, 4 (four) Static Text Objects to Show Caption,4 (four) Input Objects _myName, _myEmail, _mySubject, _myMessage (theirvariables myName, myEmail, mySubject, myMessage), a Dynamic Text object_response (variable response), and a simple Button.

In button’s event handler (release), we have following code:on(release) { this.loadVariables("script003.php", 'POST');}

this.loadVariables("script003.php", 'POST'); Send all the variables (in currentSWiSH MAX movie) to PHP script(script003.php).

Page 107: Swish Climax


Now, data variables have been dispatched to PHP script (script003.php), let us seehow 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 = "[email protected]";

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

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

$recipient_email = Change [email protected] to email addresswhere you will receive users’ emails

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

$mySubject, Variables received from SWiSH Movie$myMessage,$myEmail

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

<?$recipient_email = "[email protected]";$from = "From: ‘$myName’ <$myEmail>";

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

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

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

Writing Text Files

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

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

Page 108: Swish Climax


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


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

$myText = "This is my Text";




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

$f = fopen("myTextFile.txt" Open new file ‘myTextFile.txt’ and keep avariable $f for pointing it

"w" Create new file, if already existing,overwrite it

$myText = "This is my Text"; define new variable $myText and assignsome string value to it

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

fclose($f); Close the file we opened/created toread/write ($f is pointing variable).

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

Reading Text Files

We already have read the Text files through SWiSH MAX movie directly. Whenyou have practiced much with reading directly, and writing text files, let us movetowards reading Text files via PHP.

Page 109: Swish Climax


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


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

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

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


echo $data;



$f = fopen("myTextFile.txt" Open new file ‘myTextFile.txt’ and keep avariable $f for pointing it

"r" Open file for reading purpose only

$filesize = filesize("myTextFile.txt"); define new variable $myText and assignfile size (in bytes) to it

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

fclose($f); Close the file we opened to read ($f ispointing variable).

echo “&myData=$data&”; Send the data contained in variable $datato client movie. myData is variable in016.swiFor instance, variables of PHP directlywork within double quotes, as variable$data is enclosed in “ and “.

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


&myData=This is my Text&

Page 110: Swish Climax


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

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

Function loadVariables() has already been discussed in Chapter 3.This file is used to receive data from script007.php. The File 016.swi must beexported to SWF, first and then the SWF file must be uploaded in the same folderand ran. The 016.swf will display output as ‘This is my Text’ in Text Box, s shownbelow:

Introducing loadVars Object and its reliability

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

1.Example for loading data:

l = new loadVars(); create new instance of object ‘loadVars’l.load(“myFile.txt”); start loading data variables from file


l.onLoad = function(success) {if(success) {

take_action_file_loaded_successfully} else {



Page 111: Swish Climax


2.Example for loading data with knowledge of percentage of data loaded:Total, Loaded, Percent, msg are the variables attached to 3 (three) dynamic textboxes.

l = new loadVars(); create new instance of object ‘loadVars’l.load(“myFile.txt”); start loading data variables from file


l.onLoad = function(success) {if(success) {

take_action_file_loaded_successfully} else {


}onEnterFrame() {

Total = l.getBytesTotal();Loaded = l.getBytesLoaded();Percent = (Total/Loaded) * 100;


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

3.Example for Sending datal = new loadVars(); create new instance of object ‘loadVars’l.send(“script.php”, “POST”); send available variables (in current path)

to server script.php via POST method.l.onLoad(success) {

if(success) {take_action_file_loaded_successfully

} else {handle_error_occured


4.Example for Sending and Receiving data using function ‘sendAndLoad’l = new loadVars(); create new instance of object ‘loadVars’l.sendAndLoad(“script.php”, this, “POST”);send available variables (in current path)

to server script.php, receive them incurrent path current object ‘this’, via httpprotocol method POST.

l.onLoad = function(success) {if(success) {

take_action_file_loaded_successfully} else {



Page 112: Swish Climax


Open SWiSHMax file loadVars.swi which contains example of loading variables froma text file with accuracy. Export to SWF6 and upload SWF + myFile.txt to server andtest 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, assignvalue of received variable ‘msg’ tovariable ‘msg’ available in _root(attached to a dynamic textobject).

} else { _root.msg = "Error loading file!";

} }}onEnterFrame() {

Total = l.getBytesTotal();Loaded = l.getBytesLoaded();Percent = (Total/Loaded) * 100;


Sprite Duplication and accessing duplicated sprite’s properties

The better approach (used in standard applications) is sprite duplication,when we need to create objects of same structure / variables but with different data,size, colors, text(s) etc.

What is sprite Duplication actually?

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

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

Answer is too simple; the copied objects increase the size of your finalpublishable (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 becomesheavy (to load) and of course slow. Our major aim must be use of core features tohave full functionality within limited sized movie. We will move forward, keeping inmind that our applications will be using small amount of memory (by using less code,data, & objects) and producing 100% results.

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

A built-in function (duplicateSprite()) is used to clone / duplicate spriteobjects. It works exactly same as duplicateMovieClip() in Flash. For duplicating a

Page 113: Swish Climax


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

Easy example to duplicate sprite:Open 017.swi, select red button object and see its script that contains:

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

spr The actual/base sprite to duplicate/clone.

duplicateSprite The function used for duplication

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

3 The depth of duplicated sprite (remember:depth must be unique/higher number thanthe existing objects’ depths, otherwise theduplicate sprite will replace the existingone (if) in same depth)

newSpr._x += 50; Add 50 in the X coordinates of theduplicated sprite, so it moves to right 50pixels.

newSpr._y += 50; Add 50 in the Y coordinates of theduplicated sprite, so it moves to down 50pixels.

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, andthe top one has 2. So when you duplicate some sprite in same movie use higherdepth preferably 3.

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

Remember: If data/size/color/(or anything else that can be changed at runtime) of asprite, has been changed at runtime, and it is duplicated; the (new) duplicated onewill not be same to it, but as the base sprite was by default.

Now a question may be appearing in your mind, “if our sprite contains a dynamictext object that has a variable ‘xyz’, how to access xyz in duplicated sprite?”

Page 114: Swish Climax


Solution is so simple, in previous example we accessed _x and _y properties of theduplicated sprite. Use the same way to access variable ‘xyz’ as

newSpr.xyz = “some new value”;

See example file 018.swi, run it (in player or browser), you see a new sprite withtext ‘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 isduplicated or original which has already been discussed in chapter 2, topic: SpriteObject).

Arrays in SWiSHScript, more flexible and powerful than in ActionScript

What is Array?

I am writing two simplest definitions of Array:

1.Array is collection of different data elements handled by single variable name.2.Array is chain of sequential data items accessed under single variable name.

You know how to create variables. Variables use to hold single value at atime, either that is numeric, text, or logical data. But, Arrays can hold more than onedata items of different data types sequentially under single variable name.

Following is the example of a simple Array in SWiSHScript.


myArr = new Array(123, “Ali”, 3.15, false);

In above example, we created new Array of 4 elements , where each element is ofdifferent data type, and assigned this array to be accessed through variable ‘myArr’.

How to access item/element number 1 of the Array?

trace( myArr[0] ); function trace() is used to showsomething in internal debugger ofSWiSHMax.

You have to use square brackets to access elements of an Array. And pass it N-1 toaccess item number N. as in above example we had to access item number 1 of theArray. So N is 1 (one) and we passed N-1 is 0 (zero). Similarly if you need to accessitem number 15 (fifteen) you will pass 14 (fourteen) as myArr[14] within the squarebrackets. 14 is index of element in Array.

Page 115: Swish Climax


How to get length of and Array?

So simple! Use the built-in property ‘length’ of Array, as:

arrLen = myArr.length;

Where ‘arrLen’ is new variable, we assigned it the length of the Array ‘myArr’ (whichis 4 - four).

How to add elements to an Array at Runtime?

Very simple.Creating variable once:myArr = new Array(); create empty array variable

Add items at runtime:myArr[0] = 123;myArr[1] = “Ali”;myArr[2] = 3.15;myArr[3] = false;

How come, it is more powerful than in Flash MX ActionScript?

It is! Because SWiSHScript provides you a well managed way of handlingArray elements, by naming the indexes. SWiSHScript follows the same way used byPHP language to extend the use of Arrays. You can create names of the indexes ofthe elements in an Array. See example of a student record:

myArr = new Array();

myArr[‘std_name’] = “Ali Imran”;myArr[‘std_age’] = 27;myArr[‘std_marks’] = 315.90;myArr[‘std_email’] = “[email protected]”;myArr[‘std_site’] = “http://www.swish-db.com”;myArr[‘std_grade’] = ‘B+’;myArr[‘std_assist’] = false;

Now we show the std_site item of the student record Array in internal debugger ofSWiSH using trace() function.

trace( myArr[‘std_site’] );

open Array1.swi and run it within SWiSHMax, internal debug window.

Page 116: Swish Climax


The output in debug window will be

You can also pass Integer or String variables instead of constant indexes, as:

Through Integer variable as index:

myArr = new Array(12, “Ali Imran”);I = 1;trace( myArr[I] ); which will output ‘Ali Imran’ in debug window.

Value of variable ‘I’ is 1 so index number 1(element number 2) is accessed.

Through String variable as index:

myArr = new Array();myArr[‘std_name’] = “Ali Imran”;myArr[‘std_age’] = 27;

S = “std_age”;trace( myArr[S] ); which will output ‘27’ in debug window. Value of

variable ‘S’ is “std_age” so is index of array(element number 2) is accessed.

Another example of adding 10 (ten) random numbers to an Array and printing themone by one:

Assign:myArr = new Array();for(I=0; I<10; I++) {

myArr[I] = random(1000);}

Display in Debug Window:for(I=0; I<10; I++) {


Facility of named indexes is not available in Flash MX ActionScript, but is inSWiSHMax SWiSHScript. That is why I said, Arrays are more powerful inSWiSHScript than in ActionScript.

Page 117: Swish Climax


Chapter 5

Advanced Events Handling and otherScripting Objects

Before going forward, I would like to quote the name of the person who is anActionScript guru for me and who taught me almost complete events handlingthrough online chat. I learnt most of the events’ working from my honorable teacherMr.Gregory Baker (Nick Greg, AKA gsb on SWiSH/Flash community forums). I amproud to say that he taught me the most advanced techniques involved in eventshandling (which I have used while creating UI Collection Objects). Mr.GregoryBaker may be contacted at [email protected].

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

Page 118: Swish Climax


Evaluation/Access of Dynamic Objects/Variables

Let us get started without loosing time. Here (in topic title), I am using theword ‘dynamic’ for the objects created at runtime, means, the objects which are notactually part of your movie, but they are created at runtime through script (or clonedfrom 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 thispoint, most of the students ask a question “Variable means the identifier which canvary / change anytime, then how we call a variable being ‘dynamic’?”.

So simple answer to understand: The variables we define in our movie, are alwaysnamed, such as ‘myName’, ‘myEmail’, ‘x’, ‘y’, etc, now if our SWiSH movie isreceiving data from some text file or a PHP script, and that text or script responsesback with some new variable names such as ‘myName2’ or ‘myEmail2’ which are notalready in you movie, they are the dynamic variables actually.

Major question is: How to fetch value from dynamic variables, which are notalready 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 functionpulls 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 thesprite, and if the passed argument was variable name, then, eval function will pullout 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 ofdynamic 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 seeimmediate change in value of text object from ‘Default Value’ to ‘Ali Imran’.Complete code of 019.swi:

onLoad() {

Page 119: Swish Climax


l = new loadVars(); l.load("019.txt");

l.onLoad = function(success) { if(success) { myText = eval("this.myName2"); } };}

Understanding line by line:

onLoad() { Event Handler, that runs when a SpriteObject or main movie is started loading.(Works almost as constructor of a class in C++)

l = new loadVars(); Create new Instance of loadVars object inmemory

l.load("019.txt"); Load a simple text file (019.txt) thatcontains variables and data

l.onLoad = function(success) { Implement the onLoad event hander ofObject loadVars yourself, to check if datareceived successfully, and proceedfurther.

if(success) { If data received successfully (without anyerror in transfer)

myText = eval("this.myName2"); If data received successfully without error,then evaluate assumed variable name andassign its value to variable ‘myText’.

Where text file 019.txt contains

&myName2=Ali Imran&

Now, when we understand the procedure to get value from a dynamicvariable (which is not already in scope), let us move forward to learn advance use ofthis technique.

For example, you are creating an application for kids learning, which loads atext file at each specific point of runtime, and duplicates some sprite up to a specificnumber ‘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 ithas completely loaded, we start duplicating sprite ‘mySpr’ up to number N (which isreceived form the text file).See the code of 020.swi:onLoad() { l = new loadVars();

Page 120: Swish Climax



l.onLoad = function(success) { if(success) { cx = mySpr._x; for(i=0; i<this.N; i++) { mySpr.duplicateSprite("newSpr"+i,i+1); temp = eval("newSpr"+i); temp._x = cx; cx +=mySpr._width; } } };}

As we already have studied the sprite duplication and accessing duplicatedsprites’ variables, I will not be discussing it again in here.

In above example we have created a instance of Object loadVars() (atruntime), and loaded a text file 020.txt using its function load(). After the file issuccessfully loaded, we received a variable ‘N’, then we repeated a set of 4 linesinstructions within a ‘for’ loop, up to ‘N’. the 4 lines of instructions are:

mySpr.duplicateSprite("newSpr"+i,i+1); Duplicate Sprite mySpr

temp = eval("newSpr"+i); get reference of newly duplicated sprite,and put reference in new variable ‘temp’

temp._x = cx; Change X position of duplicated sprite tovariable ‘cx’

cx +=mySpr._width; Add width of base sprite ‘mySpr’ tovariable ‘cx’, and assign to variable ‘cx’

What I actually discussion is going for, is, that, you can also evaluate objects’names (“newSpr”+i); Put reference in other variables to point them, and access theobjects through pointing variables (which was ‘temp’ in above example).

Advanced Techniques of Events Handling (an Introduction)

We already have studied the basic events of button and sprite objects.Objective of this topic is to teach you how to customize existing events, passingthem variables, defining/attaching new events to a Sprite object, and using them. Inthis chapter we will also learn how to implement existing event handlers withincustom functions or other existing event handlers.

Page 121: Swish Climax


How to implement existing event handlers within functions?

As we already created our own functions within onLoad() event handler, we willfollow the same here. Implementing event handler ‘onEnterFrame’ of sub sprite xyz.

onLoad() {xyz.onEnterFrame = function() {



Implementing the same event handler ‘onEnterFrame’ within a custom function

function myFunction() {xyz.onEnterFrame = function() {



What is the use of implementing an event handler within function?

When we need to activate event handlers and want them not to take placeautomatically, we put them in functions, so that, they are activated when function iscalled.

In above example we implemented event handler ‘onEnterFrame’ of sprite‘xyz’ within our custom function ‘myFunction’. Now, when we call this function (asmyFunction()), the event handler ‘onEnterFrame’ of sprite ‘xyz’, is activated andstarts working.

What to do, when I want to deactivate an event handler when job is done,?

Deleting Event Handlers when job is done

E.g. You have event handler ‘onEnterFrame’ in so many paths/sprites, this willslow 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 jobdone 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 memoryresources in a proper manner, when event handlers / functions become useless tomovie, or no more required. E.g.

if( all_done ) {delete xyz.onLoad;//almost senseless, because sprite may have already been loaded


or Deleting custom function

Page 122: Swish Climax


if( all_done ) {delete myFunction;


Even you can delete an event handler or function from within itself. Such as:

onLoad() {xyz.onEnterFrame = function() {


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, onbutton press we have deleted this event handler ‘onEnterFrame’ so, all the actionstaken by this event handler are stopped immediately. Code we used for deletion is:

delete onEnterFrame;

Page 123: Swish Climax


Defining/Attaching new events handlers to Sprite object, and using them

There are many methods to attach events to sprite objects, but I willdemonstrate you the most easiest and efficient method. This can only be understoodthrough examples.

Our First custom event handler example:

onLoad() {mySprite.onAnimationEnded = function() {

msg = “Sprite Animation has ended playing.”;};


open 022.swi contains source of above example.Above code is in main timeline, means, we implemented new event handler‘onAnimationEnded’ of sprite ‘mySprite’ as function, in ‘onLoad’ event handler of_root (main timeline).

See the swi file structure:

New event handler ‘onAnimationEnded’ of sprite ‘mySprite’ must be generated fromwithin the sprite ‘mySprite’. See in above screenshot we simply called it (as a normalfunction onAnimationEnded()) on Frame # 50 of sprite ‘mySprite’, so it has beeninvoked/fired. Now, when it has been invoked/fired, it is immediately detected by theevent handler we implemented in _root and the code in that event handler‘onAnimationEnded’ is executed, which is

msg = “Sprite Animation has ended playing.”;

By the way, ‘msg’ is a variable attached to a dynamic text box ‘_msg’. So the valueof 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 buttonobject, ‘onPress’, ‘onRelease’ with ‘onMousePress’ and ‘onMouseRelease’.

Page 124: Swish Climax



Code in main timeline:

onLoad() {mySprite.onMousePress = function() {

msg = "Mouse is pressed"; };

mySprite.onMouseRelease = function() { msg = "Button of Mouse is Released"; };}

Code on button action:

on(press) {onMousePress();


on(release) {onMouseRelease();


NOTE: sprite name is same as above example.

Open 023.swi contains above mentioned source.

This was the most easiest way of attaching new event handlers to your sprites.Implementation and use custom event handlers is best when we create reusablecomponents such as UI Collection Objects (coming in next chapters). Especially,when, the users write functional sprites but they do even start to work because ofthe functions and event handlers not loaded into memory immediately. So users tryto put their initialization code in far frames such as on frame number 20.

Most frequently occurred problem with Intermediate level scriptors:

If I want to initialize and use functions of my object in ‘onLoad’ event handler ofmain movie, I do not get the desired results, although the code/script is 100%accurate. Now, when I put the same code in an ‘onFrame(20)’ event handler it worksperfectly. But it messes up with animations and other code of main timeline, and Iwant this code be within ‘onLoad’ event handler of main timeline. How to preventthese unwanted results, and how to implement to have it working within ‘onLoad’?Solution to above problem:

Page 125: Swish Climax


We will have to implement an event handler working as trigger. We will fire itwhen we know all the script and sub-objects have been loaded into memorysuccessfully. Let us have an example. Open 024.swi and see, it contains a sprite‘mySprite’ which contains further sub sprites ‘a’, ’b’,….., so on.

Structure of 024.swi (what users actually do):

Here we need to know a new built-in function typeOf() before we move forward:

Function typeOf() gives us the type of a movie object passed as argument. Itacts exactly same as in Flash MX ActionScript ‘typeof’. I we pass it a sprite name itwill return “movieclip”. See example code below, remember: in 024.swi ‘mySprite’is a sprite object:

msg = typeOf(mySprite);

it will show results in the movie as

So this is the type of a sprite object, you may pass any object name and obtain itstype as string name.

It returns following string results for different type of objects as:

Object type resulting TypeString stringSprite movieclipPath (_root/_parent/_level) movieclipButton objectText Field objectNumeric (integer/float) numberBoolean (true/false) boolean

Page 126: Swish Climax


Function functionEvent handler functionObject objectAnd the objects not yet loaded or not exist unknown

So we have no more concern with other return types; We will simply utilize thereturn type “unknown”. If we are sure we have an object and it function ‘typeOf’ isreturning ‘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 doesnot work.

If you see carefully the sprite ‘d’ contains a small animation which is stopped on firstframe. Now go to main timeline, it contains:

onLoad() { event handler in _rootmySprite.d.gotoAndPlay(2); go into sprite ‘mySprite’ then into sprite

‘d’, and play the stopped timeline.}

Generally it seems to work, but it does not, generate desired results. Because thetime when this code is executed, the sprite ‘d’ is not yet loaded into memory.

On other hand if you see code on button action (works perfectly):on (release) { mySprite.d.gotoAndPlay(2);}

Now open 025.swi where we will use the same example within ‘onLoad’ eventhandler using function ‘typeOf’ for sprite ‘d’. see the code in main timeline:

onLoad() { onEnterFrame = function() { if(typeOf(mySprite.d) ne "unknown") { mySprite.d.gotoAndPlay(2); delete onEnterFrame; } };}

operator ‘ne’ (not equal to - for String comparison) same as != in numericcomparison.

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 loadedinto 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 doesnot check and play again.

Page 127: Swish Climax


Now this is also lacking functionality, because we may need to implement eventhandler ‘onEnterFrame’ for further code execution, and we have deleted it. Let usimplement this event handler within sprite ‘d’ and generate custom event handlerfrom within ‘d’ and track it in main timeline. Open 026.swi which contains code inmain timeline:

onLoad() {mySprite.d.onFullyLoaded = function() {

mySprite.d.gotoAndPlay(2); };}

‘onFullyLoaded’ is the custom event generated by the sprite ‘d’, code in the timelineof sprite ‘d’ is below:

onLoad () { onEnterFrame = function() { if(_framesLoaded == _totalFrames) { onFullyLoaded(); delete onEnterFrame; } };}onFrame (1) { stop();}

Explanation of code in sprite ‘d’:

onLoad () { ‘onLoad’ event handler of sprite ‘d’onEnterFrame = function() { implement event handler ‘onEnterFrame’

in sprite ‘d’, as functionif(_framesLoaded == _totalFrames) if loaded frames of current path (sprite

‘d’) are equal to the total frames ofcurrent timeline, then

onFullyLoaded(); generate/fire custom event handler‘onFullyLoaded’, and

delete onEnterFrame; remove the event handler ‘onEnterFrame’of current path, we implemented, becauseevent ‘onFullyLoaded’ has beeninvoked/fired once.

Explanation of code in main timeline:

onLoad() { ‘onLoad’ event handler in main timelinemySprite.d.onFullyLoaded = function() implement the handler for the event

‘onFullyLoaded’ invoked/fired from sprite‘d’

mySprite.d.gotoAndPlay(2); now, event has been tracked, take therequired action, go to frame number 2(two) of sprite ‘d’ and play it.

Page 128: Swish Climax


Creating Events to accept variables as Arguments

Now, another question appears:If we have more than 1 (one) sprites same to sprite ‘d’ in our movie, do we have toimplement custom event handler ‘onFullyLoaded’ for each sprite separately? Such as

onLoad() {mySprite.d.onFullyLoaded = function() {

take_some_action };

mySprite.E.onFullyLoaded = function() { take_some_action };

mySprite.F.onFullyLoaded = function() { take_some_action };}

ANSWER IS ‘NO’, the code is errorless but not efficient neither compressed.

Then, what to implement?

We have to implement the same name custom event handler ‘onFullyLoaded’but with different approach, so that, it accepts a variable as argument and thatargument will be the id/name of the sprite that is ready and is fully loaded. Open027.swi and see following code is in any of the sprites ’d’, ‘e’, or ‘f’:

onLoad () {onEnterFrame = function() {

if(_framesLoaded == _totalFrames) { _parent.onFullyLoaded(this._name); delete onEnterFrame; } };}onFrame (1) { stop();}

And code in main timeline is:

onLoad() {mySprite.onFullyLoaded = function(sName) {

if(sName eq "d") { mySprite.d.gotoAndPlay(2); } else if(sName eq "e") { mySprite.e.gotoAndPlay(2); } else if(sName eq "f") { mySprite.f.gotoAndPlay(2);

Page 129: Swish Climax


} };}

Explanation of code in sprites ‘d’, ‘e’, and ‘f’:

onLoad () { ‘onLoad’ event handler within sprite ‘d’,‘e’, and ‘f’

onEnterFrame = function() { ‘onEnterFrame’ event handler within sprite‘d’, ‘e’, and ‘f’

if(_framesLoaded == _totalFrames) if loaded frames of current path (sprite)are equal to the total frames of currenttimeline,

_parent.onFullyLoaded(this._name); fire/generate the event ‘onFullyLoaded’ inparent path ‘_parent’ which is ‘mySprite’,so that. It belongs to parent path. Andpass it the name of current sprite usingsprite property ‘_name’.

delete onEnterFrame; delete event handler ‘onEnterFrame’ whenjob is done.

Explanation of code in main timeline:

onLoad() { onLoad event handler ofmain timeline ‘_root’

mySprite.onFullyLoaded = function(sName) { implement handler for eventfired in path ‘mySprite’,where ‘sName’ is thevariable receiving the valuepassed from the spriteswhen event was fired; Thevalue of sName will be thenames of sprites ‘d’, ‘e’, or‘f’, replacing this._name.

if(sName eq "d") { now when event is workingand sprites’ names havebeen received in variable‘sName’, let us compare itwith sprite names andperform the action requiredon each sprite fully loaded.

mySprite.d.gotoAndPlay(2); if value of variable ‘sName’is ‘d’, that means the eventis invoked/fired from sprite‘d’ , so play the sprite ‘d’

……..Note: type of property _name is String, you can use it with any pat, e.g. use parent._name toobtain name of parent path/sprite.

Connecting Objects through events

Page 130: Swish Climax


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 implementhandlers, you can easily connect more than one sprites to work together. E.g. ifsprite ‘x’ is fully loaded (which contains scroller), start loading the text file fromserver into sub sprite ‘y’ of sprite ‘x’.

Defining Global functions to use anywhere without reference

This is the important topic. Please pay full attention. In this topic, I willdemonstrate the method to write your own global functions which can be usedanywhere in any path without prefix reference. We already have studied the Object‘_global’, which will be used to implement such functions. See example below, open028.swi which contains code in main timeline as:

onLoad() { ‘onLoad’ event handler in main timeline._global.showMsg = function(myMsg) { implement a new function ‘showMsg’ in

‘_global’ object, so that it can be usedglobally. ‘myMsg’ is the variable used asan argument to be passed to the function.

_root.msg = myMsg; ‘msg’ is variable in _root attached with adynamic text box. So the value passed tothis function goes directly into the textbox.

}; close the function block} close the ‘onLoad’ event handler block.

How to call this function when needed?

Simply: showMsg(“this is my message”);

Now let us call it on a button action (button is in main timeline _root). See the scriptof 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 somesprite.

The same: showMsg(“this is my message”);

INVALID ONE: _root.showMsg(“this is my message”);No prefix path is required.

Now see the script on button ‘SBtn’ in sprite ‘mySprite’

Page 131: Swish Climax


So, you can see, we did not use any prefix path _root, _parent, _level or any spritename to call this function, because it has been declared global function and can becalled from anywhere. This type of functions are useful when you need to implementsome global formulas to be used in all the movie frequently.

Creating Sprite pointers

Some times, we need to point a sprite several times in our application, andwe usually use the absolute path to that sprite e.g. _root.xyz.abc.mySprite, whichneeds 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 thesprite or path without problem of big code lines and avoid use of prefix path. Oneway is to use ‘with’ structure which has already been discussed; Example:

with(_root.xyz.abc.mySprite) {take_some_actiontake_some_actiontake_some_action


And the second way is to create a globally accessible variable. This technique isuseful while creating games. I am sure you are familiar with ‘_global’ object, wehave been using in previous topics/chapters. The method is, simply assign the spriteor path to the variable in ‘_global’ object, as:

_global.pointer = _root.xyz.abc.mySprite;

Page 132: Swish Climax



‘pointer’ is the new variable accessible from anywhere which can be used to accessthe sub-sprite ‘mySprite’ wherever sprite is located. E.g. accessing the sprite throughpointer from within another sprite:

pointer.gotoAndPlay(1); go to frame number 1 (one) of sprite‘_root.xyz.abc.mySprite’ and play it.

Better is to use the assignment expression in ‘onLoad’ event handler of the maintimeline, as:

onLoad() {_global.pointer = _root.xyz.abc.mySprite;more_statementsmore_statementsmore_statements


So the variable ‘pointer’ is global now and is accessible from anywhere without prefixpath, to access the properties or functions of embedded sub-sprite ‘mySprite’.

Collision Detection for games creation

Collision Detection is the method to detect when some objects collide/crosseach other on a certain point/position. Simple definition, “To detect if 2 (two) objectsare on the same place in movie X/Y axis or near to each other, is called collisiondetection”. There are some built-in functions and properties in SWiSHScript to detectcollision, such as isNearThis(), isNearTarget(), _deopTarget, and _target.

Let us have an example here:

Let us create a drag drop game. We have two sprites ‘plane’ and ‘runway’.Sprite ‘plane’ is dragable and is to be dropped over the sprite ‘runway’ correctly. If‘plane’ is dragged and dropped over the sprite ‘runway’ a message is shown‘ACCURATE’ otherwise ‘WRONG LANDING’.

Open 029.swi. Open sprite ‘plane’, it contains one shape object and onebutton 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:

Page 133: Swish Climax



on(press) { button object’s event handler when leftmouse key is pressed

startDragUnLocked(); start dragging the current sprite ‘plane’,regardless the mouse click position overbutton


on(release) { button object’s event handler when leftmouse key is released up

stopDrag(); stop the dragging of current sprite (ifalready being dragged)

if(_dropTarget eq "/runway") when current sprite ‘plane’ is stoppedbeing dragged, now, if it is dropped oversprite ‘runway’ (sprite in _root, ‘/’ is usedfor _root, so /runway means spriterunway on _root), then

_parent.msg = "ACCURATE"; change the value of variable ‘msg’ inparent path, to, ‘ACCURATE’ (whereparent path to sprite ‘plane’ is _root,

else otherwise,

_parent.msg = "WRONG LANDING"; set the value of variable ‘msg’ to ‘WRONGLANDING’.

Where variable ‘msg’ is attached to a dynamic text object ‘_msg’.This was the first example where we used ‘_dropTarget’ property to get the name ofsprite where sprite ‘plane’ is dropped over. Property ‘_dropTarget’ returns theabsolute path to sprite over which current sprite is dropped. If you use prefixpath/sprite name to property ‘_dropTarget’, it will detect the collision for sprite usedas prefix, such as:if(mySprite._dropTarget eq “/Spri”) if sprite ‘mySprite’ is dropped over sprite

‘Spr2’ in _root.

Page 134: Swish Climax


Let us have a look over next example 030.swi. this example is implemented usingfunction ‘isNearThis()’. This is one of the core functions used for collision detection ingame development. 030.swi contains the same objects used in previous example,but the sprite ‘plane’ moves with keyboard keys ‘up’, ‘down’, ‘left’, and ‘right’ andbutton within sprite ‘plane’ is transparent. Here is the preview of this small game:

See the code on button to implement movement of sprite ‘plane’:

Code with Explanation:

on (keyPress("<Down>")) { if arrow key is pressed,_y++; increase the Y axis of current sprite by 1

(one), so it goes down on pixel}on (keyPress("<Up>")) { if arrow key is pressed,

_y--; decrease the Y axis of current sprite by 1(one), so it goes up on pixel

_rotation=0; rotate sprite ‘plane’ back to normal}on (keyPress("<Right>")) { if arrow key is pressed,

_x++; increase the X axis of current sprite by 1(one), so it goes one pixel right

_rotation=45; rotate current sprite ‘plane’ to angle 45degree

}on (keyPress("<Left>")) { if arrow key is pressed,

_x--; decrease the X axis of current sprite by 1(one), so it goes one pixel left

_rotation=-45; rotate current sprite ‘plane’ to angle -45degree


Page 135: Swish Climax


So the movement of sprite ‘plane’ is clear now. Let us see the code found in timelineof sprite ‘plane’:

onEnterFrame() { pointer = _parent.runway; if (pointer.isNearThis()) _parent.msg = "PLANE IS NEAR THE RUNWAY"; else _parent.msg = "WRONG LANDING";}


onEnterFrame() { implement event handler ‘onEnterFrame’in sprite ‘plane’ to execute followingstatements continuously

pointer = _parent.runway; create variable ‘pointer’ to point sprite‘runway’ in root directly without usingprefix path ‘root’

if (pointer.isNearThis()) if sprite ‘runway’ is near current sprite‘plane’, then,

_parent.msg = "PLANE I…….. change value of variable ‘msg’ in _root to‘PLANE IS NEAR THE RUNWAY’

else otherwise

_parent.msg = "WRONG…….. change value of variable ‘msg’ to ‘WRONGLANDING’

Now run the example and move the airplane using keyboard arrow keys, watch themessage just below the design, it changes when sprite ‘plane’ come near to thesprite ‘runway’, and does same when goes away from it.

Function ‘isNearThis()’ returns true when a sprite is near to another, otherwisereturns false. so we can say this function return Boolean value.

Now, let us have a bit more useful example where, there will be 2 (two)sprites, ‘ball’ and ‘box’. The moving sprite ball is to be caught and dragged withmouse and to be dropped over the box, If drop was accurate, the player gets 1point, player has to make maximum points in limited time 60 (sixty) seconds that’sequal to 1 (one) minute.

In this example we will be learning ‘Timer.ticks()’, ‘Math.randomRange()’,‘Stage.width’, and ‘Stage.height’ (Stage Object). Open 031.swi, and test the game.

Page 136: Swish Climax


Game preview:


This is alternate to function ‘getTimer()’ in Flash MX ActionScript, whichreturns the number of milliseconds that have passed since the Flash Player startedplaying movie. TIP: Dividing obtained value by 1000 (one thousand) returns thenumber of seconds passed.


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 numberbetween 5 to 100 we will use function ‘randomRange()’ of Math object, as:

MyVal = Math.randomRange(5,100); //returns random value between 5 (five)and 100 (one hundred)

Stage Object

Object available in SWiSHScript as well as in ActionScript gives us informationabout the physical Movie, where we can obtain width, height, alignment in browser,and information about current Scale Mode.

Stage.width Returns physical width of the movie in browser or player (inpixels).

Stage.height Returns physical height of the movie in browser or player (inpixels).

Stage.align Returns current alignment of movie on stage, as string.Stage.scaleMode Returns current Scale Mode as string “showAll”, “exactFit”, etc.

Page 137: Swish Climax


There is an event handler available ‘onResize’, which may be implemented accordingto needs (when movie has been resized), as:

onLoad() {Stage.onResize = function() {



Encoding special characters before sending to SWiSH Movie

Most of the times, when we load some text from outside resources (especiallyusing 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 Iwe put it in a text file as text, it is no recognized as a simple text character but aseparator to start reading value of new variable. The technique we will be using iscalled “URL Encoding in Flash”.

In some other cases when we have a dynamic text object and is htmlenabled, and we need to display <b> (as I said display not to make text bold butshow the bold html tag), in html we use to &lt; to display ‘<’ and &gt; to display ‘>’.I we do adopt the same way and send the values to back to swish movie htmltextbox it will no display anything at all, why?See the code e.g. text file contains

&myVar=&lt;b&gt; //which must display <b> in html file usually//and in flash player as well

what happens when this text is loaded? The second ‘&’ sign is just after the ‘=’ sign,so ‘lt;b’ is not being treated as data, similarly third after ‘&’ sign there is ‘ft;’ which isalso not being treated as data because both are right after the ‘&’ sign. If we wantthem be treated as data we must encode them before sending back to SWiSH movie.

like convert ‘&’ to %26so that the data of text file becomes:&myVar=%26lt;b%26gt;

Run the example 032.swi to test it yourself.

Reference Flash MX Help Manual

URL Encoding: Reading special characters from a text fileOne common technique used to load variables in Macromedia Flash is reading thedata from a text file on the server or CD. This works well in most situations.However, there are certain characters that cannot be read directly from text.

Entering these characters in a text file read by Macromedia Flash may cause unusualresults. These characters need to be URL encoded. URL encoding replaces thealphanumeric character with the hexadecimal combination which represents thatcharacter.

Page 138: Swish Climax


Note: Macromedia Flash MX adds full Unicode support to the Macromedia FlashPlayer. This may be helpful in encoding your data. For complete details see Workingwith Multiple Languages in the Macromedia Flash Support Center.

Use encoding to ensure that variables are passed correctlyThe example below illustrates how special characters can be retained using URLencoding:

A text file containing the following variable value:Cost=+85Will read into Flash as 'Cost= 85', dropping the + character.

However, using URL encoding to replace the + character the original text:

Cost=%2b85Will result in Flash displaying 'Cost= +85' correctly.

Use this URL Encoding table for special characters:

backspace %08tab %09linefeed %0Areturn %0Dspace %20! %21" %22# %23$ %24% %25& %26' %27( %28) %29* %2A+ %2B, %2C- %2D. %2E/ %2F0 %301 %312 %323 %334 %345 %356 %367 %378 %389 %39: %3A; %3B< %3C= %3D

Page 139: Swish Climax


> %3E? %3F@ %40A %41B %42C %43D %44E %45F %46G %47H %48I %49J %4AK %4BL %4CM %4DN %4EO %4FP %50Q %51R %52S %53T %54U %55V %56W %57X %58Y %59Z %5A[ %5B\\ %5C] %5D^ %5E_ %5F` %60a %61b %62c %63d %64e %65f %66g %67h %68i %69j %6Ak %6Bl %6Cm %6Dn %6Eo %6Fp %70q %71r %72

Page 140: Swish Climax


s %73t %74u %75v %76w %77x %78y %79z %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

Page 141: Swish Climax


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

Page 142: Swish Climax


Chapter 6

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


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 thisproduct may not be published/redistributed/resold in any case in any form withoutthe permission of respective author. This product purely belongs to author: Ali ImranKhan Shirani, and is created to enhance functionality of SWiSHMax Projects.

Page 143: Swish Climax


Introduction to UI Collection Objects

We are proud to introduce a huge enhancement in the SWiSHMax world. Thistype of collection is being launched for the very first time on web (although someother controls have already been introduced by individuals). This is the collection ofpre-made controls with higher functionality that enables you to enhance yourexisting SWiSHMax projects in an organized manner, and generate a professionallook of your web projects. This collection is made to facilitate the advance andmoderate level SWiSHMax users, to not to waste time on creating usual comboboxes, menus, radio, check, and almost all type of inputs, just use them via copy-n-paste easy technique. These are written keeping in view the higher functionalitywithin limited size of output publishable movies and higher speed to accommodateall type of internet connections, so that the dialup users do not need to worry aboutload-time of your application.

UI Collection Objects are very useful for business solutions with inclusion ofembedded Bar Graph, Line Graph, and Pie Chart Controls. In beginning, the code ofthese controls seems hard, but gradually a moderate level user can also go throughall of the controls and implement desired high level application after readingexamples and complete explanation included alongwith book. Best and easiestexamples do not let you mess with the actual code of controls but make you allunderstand easily and enable you to use them properly.

I am sure, after reading this chapter, you will be able to accept any webapplication challenge and will be able to write higher level web applications withinlimited duration easily and comfortably.

Page 144: Swish Climax


UI CheckBox

UI CheckBox works exactly as a normal Checkbox, you usually see in htmlpages or in windows applications. A CheckBox is used for input of Boolean type value(true or false). in other words, it acts like ON/OFF button, so we can say a CheckBoxcan contain only single Boolean value either true or false, If it is checked it means itis true otherwise false. See the screenshot of usual CheckBox in window applications,and UI CheckBox:

Open UICO_01.swi and test (either in browser or player). When it is running, clickthe checkbox, notice that, once it is checked and one second click it is unchecked. Itis the automatic functionality of UI CheckBox.

How to insert UI CheckBox in my SWiSHMax project?

Copy the sprite ‘UICheckBox’ from file UICO_01.swi, paste it in your SWiSHMaxproject, and move it to desired place in the movie surface. Make its copies as manyas required in your SWiSHMax project, but Remember: Name of each UI CheckBoxsprite must be unique, otherwise they will not function correctly.

See the code of file UICO_01.swi in main timeline:

onLoad() { UICheckBox.onReady = function() { UICheckBox.caption="This is my caption"; }; UICheckBox.onChecked = function() { msg="checked"; }; UICheckBox.onUnchecked = function() { msg="unchecked"; };}

Page 145: Swish Climax



Note: variable ‘msg’ is attached to a dynamic textbox in the example file, so, thedisplay of textbox is changed when value of variable ‘msg’ is changed.

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

UICheckBox.onReady = function() { implement handler for event ‘onReady’ ofUI CheckBox, which is automaticallyinvoked/fired when a UI CheckBox hassuccessfully been loaded into memory

UICheckBox.caption="This is….."; When it is assured that UI CheckBox hasbeen loaded into memory, change thecaption text of the CheckBox, byaccessing the ‘caption’ property of the UICheckBox.

}; Close ‘onReady’ event handlerimplementation block.

UICheckBox.onChecked = function() { implement handler for event ‘onChecked’of UI CheckBox, which is automaticallyfired when a UI CheckBox is checked(turned ON) by user click

msg="checked"; So, when it is checked change the value ofvariable ‘msg’

}; Close ‘onChecked’ event handlerimplementation block.

UICheckBox.onUnchecked = function() { implement handler for event‘onUnchecked’ of UI CheckBox, which isautomatically fired when a UI CheckBox isunchecked (turned OFF) by user click

msg="unchecked"; So, when it is unchecked change the valueof variable ‘msg’

}; Close ‘onChecked’ event handlerimplementation block.

} Close ‘onLoad’ event handlerimplementation block in main timeline.

There are some more events for a UI CheckBox such as ‘onClick’. You can takedesired action when a checkbox is clicked, this event is invoked/fired when a UICheckBox is clicked in no concern with checked or unchecked. You can implement itshandler as:

UICheckBox.onClick = function() {take_some_action


Page 146: Swish Climax


You can also turn a UI CheckBox ON(checked) or OFF(unchecked), through followingmentioned functions of a UI CheckBox:

UICheckBox.check(); check (set ON)UICheckBox.uncheck(); uncheck (set OFF)

Open UICO_02.swi, which contains the example of unconditional uncheck andcheck of a UI CheckBox at runtime; test it in player. After testing it see code ofbuttons ‘ON’ and ‘OFF’.

How to either a UI CheckBox is checked or unchecked?

Use function ‘getValue()’ which returns true if it is checked and false otherwise, as:

if(UICheckBox.getValue())msg = “It is Checked”;

elsemsg = “It is Not checked”;

Check example file UICO_03.swi, run it, check the checkbox and press button‘getValue’, now uncheck and press button ‘getValue’ again, see the value of variable‘msg’ has been changed.

To Enable or Disable a UI CheckBox control, use:

UICheckBox.enabled(false); Disable to UI CheckBox, so that it is nomore clickable

UICheckBox.enabled(true); Re-Enable if the UI CheckBox wasdisabled, so that it becomes clickableagain

How to either a UI CheckBox is enabled or disabled currently?

Use function ‘getState()’ which returns true if it is enabled and false otherwise, as:

if(UICheckBox.getState())msg = “Control is Enabled and is clickable”;

elsemsg = “Control is Disabled and is NOT clickable”;

Additional Events for UI CheckBox

onDisabled event invoked/fired when a UI CheckBoxis disabled through function ‘enable(false)’

onEnabled event invoked/fired when a UI CheckBoxis Re-Enabled through function‘enable(true)’

onResized event invoked/fired when a UI CheckBoxis resized through function ‘setWidth()’

Page 147: Swish Climax


Open file UICO_04.swi and test in player. Note, when it has been disabled, it is nomore clickable, and user can’t check or uncheck through click.

Utility Functions for UI CheckBox:

Following are the utility functions, that modify a UI CheckBox at runtime.

remove() Destroy the UI CheckBox controlsetCaption(newCap) Change text caption of UI CheckBoxsetBgColor(newCol) Set Background color of the UI CheckBoxsetSelectionColor(newCol) Set selection color when mouse is oversetWidth(newW) Set width (clickable pan area)moveTo(x,y) Alternate to change in _X= and _Y=moveBy(x,y) Alternate to change in _X+= and _Y+=getWidth() Get current (clickable pan width in pixels)getHeight() Get current (clickable pan height in pixels)getX() Current _X coordinates in parent pathgetY() Current _Y coordinates in parent path

Open and test file UICO_05.swi, that contains multiple UI CheckBoxes in.So, this was the quick and almost complete study if UI CheckBox, let us move toother UI Collection Objects.

UI Radio Button

Radio Buttons are also called Option Buttons. Radio buttons work collectivelyand perform the action within a group. These are used when we want our user tohave multiple (more than 1) options, where s/he can select one of them at a time,e.g.

• (2 radios group) Selection of Male and Female• (4 radios group) Married, Unmarried, Divorced, or Widow• (3 radios group) Age less than 18, More than 18 and less than 26, More than 26

Example of the third scenario in windows application may look like:

Page 148: Swish Climax


Open UICO_06.swi and test (either in browser or player). When it is running, clickany of the radio buttons, notice that, when you select any of them, the last selectedis automatically unselected.

How to insert UI Radio in my SWiSHMax project?

Copy the sprite ‘UIRadio’ from file UICO_07.swi, paste it in your SWiSHMax project,and move it to desired place in the movie surface. Make its copies as many asrequired in your SWiSHMax project, but Remember: Name of each UI Radio spritemust be unique, otherwise the Radio group will not function properly, because ofambiguity.

UI Radio Buttons use to have unique groups. E.g. there are 5 UI Radios in yourmovie, first 3 Radios are being used to let user select age, and other 2 UI Radios arebeing used to let user select Gender (male/female). So there will be 2 logical groups,first group will be ‘age’, and other one will be ‘gender’.

How to assign group to a UI Radio Button?

First 3 UI Radios in logical group ‘age’Radio1.group = “age”;Radio2.group = “age”;Radio3.group = “age”;

Last 2 UI Radios in logical group ‘gender’Radio4.group = “gender”;Radio5.group = “gender”;

I don’t think there is any complication in understanding the group assignment to UIRadios.

See the code of file UICO_06.swi in main timeline:

onLoad() { a1.caption = "Under 18"; a2.caption = "Exact 18"; a3.caption = "Over 18";

a1.group = "age"; a2.group = "age"; a3.group = "age"; onRadioReady = function(rID) { if(rID == a2) a2.select(); };}

Remember: there are three UI Radio Buttons in the file.

We have some more ease here; when we have only one group of UI Radio in ourmovie, there is no need to assign them group, because the UI Radio’s which are not

Page 149: Swish Climax


assigned group are considered of default unnamed group, and they work perfectly asone group. Grouping of UI Radio objects is used when we have many radios in themovie in same path but of different groups.

See the code of file UICO_08.swi in main timeline, which is almost similar to theone in file UICO_06.swi but only difference is, we did not assign the UI Radioobjects any group.

onLoad() { a1.caption = "Under 18"; a2.caption = "Exact 18"; a3.caption = "Over 18";

onRadioReady = function(rID) { if(rID == a2) a2.select(); };}

Explanation of above code:

onLoad() { event handler ‘onLoad’ of main timelinea1.caption = "Under 18"; Set caption of UI Radio named ‘a1’a2.caption = "Exact 18"; - do -a3.caption = "Over 18"; - do -

onRadioReady = function(rID) { event handler ‘onRadioReady’ for UI Radio’s, thisevent is invoked/fired when a UI Radio iscompletely loaded into memory and is ready totake any action. Where ‘rID’ is the variable(which may be of any name), which fetches outthe path of UI Radio became ready recently.

if(rID == a2) comparing variable ‘rID’ with UI Radio ‘a2’, ifthey are equal, it means UI Radio ‘a2’ Icompletely loaded into memory and ready tooperate. Now, if UI Radio ‘a2’ is ready, then,

a2.select(); select it within the group of UI Radio’s. this isalmost similar function to the one available for UICheckBox as ‘check()’, but operates differentlyaccording to the nature of object.

}; close code block of event handler ‘onRadioReady’.} close code block of event handler ‘onLoad’

Further study on event ‘onRadioReady’

This event is invoked/fired/generated/released by the UI Radio buttons in theirparent path only. E.g. there are 5 radio buttons (may of different groups) in a sprite‘x’, the event ‘onRadioReady’ will be available within sprite ‘x’ only. Furthermore ifyou wish to implement it within another path such as main timeline ‘_root’, you willdo as:

onLoad() {

Page 150: Swish Climax


x.onRadioReady = function(radioID) {take_some_action


Utility Functions to operate a UI Radio Collection Object

setCaption(newCap) change caption (display text) of UI Radio,where you can also change it using‘caption’ property.

enabled(true_false) disable or enable, so that, if UI Radio isdisabled, it is no more clickable by user.

select() select any UI Radio from a group, andunselect previously selected

unselect() remove selectiongetValue() to check either UI Radio is selected or not,

if it is selected the function returns trueand false otherwise.

getState() to check either UI Radio is enabled ordisabled, if enabled (by default), thefunction returns true and false otherwise.

setBgColor(newCol) change background color to ‘newCol’ ahex value

setSelectionColor(newCol) change the background color when mouseis over the object

getWidth() current physical width of the UI Radioobject

getHeight() current physical height of the UI Radioobject

getX() get current X coordinatesgetY() get current Y coordinatesmoveTo(x,y) move to specific location on stagemoveBy(x,y) increase X and Y coordinates and move on

stagesetWidth(newW) change background and selection widthremove() destroy the object from movie as well as

from memory.getGroup() get name of group the UI Radio is

associated with (function return string)setGroup(group_name) change or set group of a UI RadiogetId() get sprite name of a UI Radio (function

returns name as string data)

NOTE : to get height or width of the UI Radio or UI CheckBox object, use functiongetHeight() and getWidth() not usual properties _height and _width which mayreport wrong values.

Additional Events for UI Radio Collection Object

onDisabled event invoked/fired when a UI Radio isdisabled through function ‘enable(false)’

Page 151: Swish Climax


onEnabled event invoked/fired when a UI Radio isRe-Enabled through function ‘enable(true)’

onClicked event invoked when a UI Radio has beenclicked by user, regardless the informationeither it is selected or not.

See the example of multiple groups working at a time, implemented in fileUICO_09.swi. Here is the preview of the file running in player:

UI Menus

UI Menu Object is the most sophisticated source for runtime menu creation.Design and colors of the UI Menu can be altered only within SWiSHMax environment(not at runtime), but extension (adding main and sub menus) is done at runtime(through script). UI Menu Collection object does not allow to add hierarchical menus.It supports checked menu items (to work as checkbox), and option menu items (towork as radio buttons) as well. You can add unlimited number of main and submenus (at runtime) simultaneously. File UICO_10.swi contains first sample of UIMenu example. Here is the preview of the example:

How to insert UI Menu in my SWiSHMax project?

Open file UICO_10.swi, copy sprite ‘UIMenu’ and paste it in your SWiSHMaxproject; that’s it.Let us have a view over the code to generate menus at runtime. Following code isfrom example file UICO_10.swi:

onLoad() { UIMenu.onReady = function() { menu1 = UIMenu.addMenu("Menu 1","main1");

Page 152: Swish Climax


menu2 = UIMenu.addMenu("Menu 2","main2"); }; UIMenu.onMenuReady = function(menu) { switch(menu){ case menu1 : menu.addItem("I am Menu Item 1","item1"); menu.addItem("I am second Item","item2"); menu.addSeperator(); menu.addItem("Last Menu Item","item3"); break; case menu2 : menu.addItem("Item1","i1"); menu.addItem("Item2","i2"); menu.addItem("Item3","i3"); } };}


onLoad() { event handler ‘onLoad’ of maintimeline

UIMenu.onReady = function() { implement event handler ‘onReady’for UI Menu collection Object Sprite‘UIMenu’. This event isfired/generated automatically whena UI Menu object is 100% loadedinto memory and is ready tooperate. When it is confirmed thatUI Menu sprite is ready, then,

menu1 = UIMenu.addMenu("Menu 1","main1"); Create a top-level menu (mainmenu) using function ‘addMenu’ inour SWiSH movie. And create apointing variable ‘menu1’, throughwhich we will access the menulater. Where ‘Menu 1’ is the captiondisplayed and ‘main1’ is the uniquename/id of the top-level menu.

menu2 = UIMenu.addMenu("Menu 2","main2"); Create another top-level menu andto assign pointer ‘menu2’.

}; closing block for event handler‘onReady’

UIMenu.onMenuReady = function(menu) { implementation of event handler‘onMenuReady’ of UI Menu. This isanother event handler‘onMenuReady’ which isfired/generated/released when atop-level menu I ready to acceptfurther sub-menu items. Itprovides the absolute path of thetop-level menu item sprite (createdat runtime), which is ready toaccept further sub-menu items.

Page 153: Swish Climax


Path of the ready item is obtainedfrom the argument ‘menu’. Now,when it has been confirmed thatany of the top-level menus is readto accept sub-menus, then,

switch(menu){ keep a check on value of ‘menu’(which contains path to readyitem)

case menu1 : if ready menu is ‘menu1’ (that ispointer to first top-level Menu 1),then,

menu.addItem("I am Menu Item 1","item1"); add sub-menu/item to currentlyready top-level menu, usingfunction ‘addItem’. Where ‘I amMenu Item’ is the caption to bedisplayed, and ‘item1’ is the uniquename of the item added, throughwhich we can access it directly.Note : names of the sub-menus/items may be similar indifferent top-level menus.

menu.addItem("I am second Item","item2"); do the same, add new sub itemmenu.addSeperator(); add a separator, a normal line

under the last inserted sub-menu,so that the next menu seems to beseparated by a line from otheritems, using function‘addSeparator’.

menu.addItem("Last Menu Item","item3"); do add another sub menu.break; break the ‘switch’ statement so

that it does not execute codefollowing to current code.

case menu2 : Now, if top-level menu ‘men2’ isready, operate the same way, and

menu.addItem("Item1","i1"); and do add the sub menu items.menu.addItem("Item2","i2");menu.addItem("Item3","i3");} close the ‘switch’ block}; close ‘onMenuReady’ event handler

block.} close ‘onLoad’ event handler block.

How to know which item has been clicked?

Very simple, there is an event handler ‘onClick’ available for this purpose. Open fileUICO_11.swi and see only first 4 (four) lines of code, which are:

Code and explanation:

UIMenu.onClick = function(id) { implement event handler ‘onClick’, whichis fired/generated when a sub menu isclicked. This function also provides us the

Page 154: Swish Climax


id of the last clicked item, variable ‘id’ isused to track the clicked item id.

msg = "Item clicked " + id; ‘msg’ is a variable attached to a dynamictext box. So, change the value of variable‘msg’ to the “some text” and object id,which will directly be displayed on thetextbox.

}; closing block of event handler ‘onClick’.

Run the example in player yourself, click any of the sub menus, and see the textbeing changed in the textbox (through the event handler). When you click the lastitem 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?


In this case, you need to remember sub-menu items’ ids, or assign then to somepointing 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();


Direct method 3, through ID:menu1.getItemById(“item1”).disable();


Indirect method, through pointing variable:item = menu1.getItem (1);item.disable();

there are variety of ways you can access the sub-menu items. See exampleUICO_12.swi, where we are disabling a sub-menu item via button on(release)event handler. Code of button is:

on(release) { item1.disable();}

Page 155: Swish Climax


remember, id of sub-menu ‘item1’ was crated while creation of sub-menu items.See output before clicking button ‘Disable first item of Menu 1’:

And see the preview, after button has been clicked, and the menu item has beendisabled (after being disabled, first item is no more clickable via mouse):

How to enable a disabled sub-menu item?

Use the same method to adopt the id of the sub-menu item then use function‘enable’, here is the example:

on(release) {item1.enable();


Let us move to a bit advanced use of the UI Menu Collection Object. In next examplewe will create a top-level menu and add check items to it (to act as checkbox), usingfunction ‘addCheckItem’ instead of ‘addItem’. Open example file exampleUICO_13.swi, and see the code.

Here is the screenshot of above example:

Practically function ‘addCheckItem’ receives 3 (three) arguments as follows:

menu.addCheckItem( item_caption, item_id [,default_checked]);

where ‘item_caption’ is the string/text to be displayed, ‘item_id’ is the unique nameof the item, the last argument ‘default_checked’ is of boolean type and is optional. Ifyou do not pass this argument and let function work with 2 (two) arguments, welland good, the function will consider it false by default; And if you pass ‘true’ or anypositive integer value as last argument, the newly added sub-menu will be checkedby default (as shown above). So the code in file is:

Script and Explanation:

Page 156: Swish Climax


menu.addCheckItem("Check Item","item1",true); Add new menu item of typecheckbox, where ‘item1’ isits unique id, and lastargument ‘true’ is passedto have it checked bydefault.

menu.addCheckItem("Check Item2","item2"); add new item, the sameway, but keep it uncheckedby default. Note: weignored/did not pass thelast (third) argument, sothat, it is considered false.

Test the movie and note that items added using this function ‘addCheckItem’ act aas usual checkboxes and are once checked and unchecked on second click I they areenabled.

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 theimplementation 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 textboxwhen an item is unchecked:

Code to implement the event handlers ‘onCheck’ and ‘onUncheck’:

UIMenu.onCheck = function(id) {msg = "Item CHECKED " + id;

};UIMenu.onUncheck = function(id) { msg = "UNCHECKED " + id;};

I hope you understand it very clearly if you have read the previous topic onimplementation of ‘onClick’ event handler. This type of items are useful when youwant to allow the user to enable or disable specific options in your SWiSHMaxapplication (at runtime). NOTE: checkbox type items are disabled and re-enabled thesame way other items are dealt.

Adding Radio Type UI Menu sub-menu items:

Another advance use of UI Menu is to add Radio type sub-menu items (atruntime). As we previously studied the behavior UI Radio buttons, these act almostthe same but can contain single group under on top-level menu (where you cannotdefine group, group is automatically defined as default). So that, they act as radiobuttons’ group, when one item is selected the others remain unselected, similarlywhen some unselected is selected (by user click), the last selected is automatically

Page 157: Swish Climax


unselected. See the preview of radio type menu items (example from fileUICO_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 iscurrently with the second menu item:

After user click on second menu item:

Ok, how to add radio type sub-menu items? What is specific function to do this?

Use function ‘addRadioItem’ to add radio type menu item. This function takes3 (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’ orany positive integer value as third argument, turns the item to be default selectedunder the radio’s in current top-level menu. See the code:

menu.addRadioItem("Radio Item 1","item1",true);menu.addRadioItem("Radio Item 2","item2");

Now you must be thinking about tracking the behavior of this type of items, to knowwhich one is clicked and selected, and which one was previously selected (which iscurrently unselected).

Events to capture for radio type items:

For this purpose, we have two events ‘onSelect’ and ‘onUnselect’, which maybe implemented as handlers, according to our needs. Both of events do provide usthe id of the item as well. Open example file UICO_16.swi, and see the code wherewe have created two textboxes (and attached two variables ‘msg’ and ‘msg2’ tothem) 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";};

Page 158: Swish Climax


where ‘id’ is the name/id of currently selected/unselected item. And here is thepreview of movie when second item is clicked by the user:

NOTE: remember, item may be of any type (check, radio, or simple), it producesevent ‘onClick’ in the environment when it is clicked by the user, but two additionaltypes (check, radio) produce ‘onCheck’, ‘onUncheck’, ‘onSelect’, and ‘onUnselect’.

Additional functions for top-level menus to enable, disable, change width etc:

menu=UIMenu.getMenu(1); Create pointing variable for first top-levelmenu

menu=UIMenu.getMenuById(“meu1”); Create pointing variable for a top-levelmenu, obtain path by the id/name yougave it while creating.

menu_id.disable(); To disable a top-level menumenu_id.enable(); And to re-enable

menu.setHeadWidth(newW); change the width of the top-level menuheading area

menu.setPanWidth(newW); change the width of sub-menus containerarea

menu.incPanWidth(nNum); increase the width of sub-menus containerarea (by pixels)

menu.openMenu(); unconditional opening of the top-levelmenu

menu.closeMenu(); unconditional collapse of the top-levelmenu

menu.getX() obtain X coordinates of a top-level menumenu.getY() obtain Y coordinates of a top-level menumenu.getWidth() obtain width of a top-level menu (do not

use _width property)menu.getHeight() obtain height of a top-level menu (do not

use _height property)

NOTE: Disabling a top-level menu means to disable entire drop down items list aswell.

Page 159: Swish Climax


Test the example file UICO_17.swi in player; example is using functions‘setPanWidth’. Here is the preview o the movie:

Additional Events for top-level menus:

UIMenu.onClose(id) A top level menu has been closed, ‘id’ isthe menu id/name

UIMenu.onExpand(id) A top level menu has beenexpanded/opened, ‘id’ is the menuid/name

UI Combo Box

This object provides you a big ease to create drop down list (at runtime)within seconds. It has variety of functions to manipulate overall UI Combo object,and many more events to track behavior of UI Combo at each point of execution. UICombo works in two different ways, it is capable of working as a usual combo box aswell as a list box where user does not need to drop the list and select (all the itemsare visible to select from). UI Combo automatically become dragable when it isturned to list box style. You can switch between these two styles at runtime, evenallow user to switch to desired style. You can turn ON or OFF the dragging and styleswitching 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 thecombo):

You can copy and paste sprite ‘UICombo’ in your SWiSHMax project and utilize it.

Page 160: Swish Climax


Where code in the main timeline is:

onLoad() { UICombo.onReady = function() { UICombo.addItem("I am Item 1","item1"); UICombo.addItem("I am Item 2","item2"); UICombo.addItem("I am Item 3","item3"); UICombo.addItem("I am Item 4","item4"); UICombo.select(2); };}

How to insert a UI Combo in my SWiSHMax project?

Simply copy the sprite ‘UICombo’ from any of the UI Combo examples and paste inyour SWiSHMax project on desired position.


onLoad() { ‘onLoad’ event handler of main timelineUICombo.onReady = function() { implementation of handler for event

‘onReady’ of UI Combo, which isfired/generated when a UI Combo is fullyloaded into memory and is ready toaccept new items and furthermanipulations. So, when it is fully loadedinto memory and ready, then,

UICombo.addItem("I am …… Add new item to UI Combo using function‘addItem’, where first argument is thecaption/label of the new item and secondargument is the unique id/name of thenewly inserted item.

UICombo.addItem("I am …… do the same to add further item.UICombo.addItem("I am …… -do-UICombo.addItem("I am …… -do-UICombo.select(2); set default selected item number 2 (two)

in UI Combo list using function ‘select’.Number of an item is the physicalappearance of it in the list.

}; closing block for event handler ‘onReady’} closing block for event handler ‘onLoad’

You can add unlimited number of items to a UI Combo Collection Object (at runtimeonly). UI Combo allows some modifications in design and layout at runtime, rest ofthe design, color, layout, and/or font must be altered within SWiSHMax environment.

Page 161: Swish Climax


Now, a problem appears, e.g. you have 100 entries to be added to a UI Combo; ofcourse it will get larger in height and will not fit your design.

What to do in this regard?

We have a function ‘setSize’ available to fix the length of a UI Combo uptospecific number of items. This function accepts only one argument as number ofitems to be shown at once. After the size has been set, there is a scrollbar added toUI Combo automatically. Open file UICO_19.swi, which contains such example, inthis example, we order the combo to show only 3 (three) items at a time, so thatrest of the items are visible through scroll. The code of example contains only onedifferent line at almost end: ‘UICombo.setSize(3);’ which is used to set the constantsize of the UI Combo. So that, the preview will be as shown below (after expansion):

How to remove the size limitation?

Use function ‘removeSize’, as:UICombo.removeSize();

How to add new Items at runtime?

Use function ‘addItem’ to add new entries to a UI Combo.

Repeated Example:

UICombo.addItem(“Label of New Item”, “item1”);


Argument 1 (one) ‘Label of New Item’ is the caption/label/text of the new item,where argument 2 (two) ‘item1’ is the unique name/id of the new item to be added.

How to track the clicked item?

We have an event ‘onClick’ which is fired/generated when an UI Combo itemis clicked. We can implement this event as handler according to our needs. Event‘onClick’ gives us the id of the last clicked item’s complete path, through which wecan negotiate the item individually. Much better way to recognize the clicked item,we do create pointing variables for all items while adding them. Open fileUICO_20.swi, and see the code in main time line. We have only two UI Comboentries, 1.Play Animation, and 2.Stop Animation. There is a sprite ‘animation’ in ourmovie, which is played and stopped according to the UI Combo item select. First run

Page 162: Swish Climax


the example and test it through selecting UI Combo entries. Note that, the animationwill 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 theitems:

p1=UICombo.addItem("1.Play Animation","item1");p2=UICombo.addItem("2.Stop Animation","item2");now move onto the implementation of the ‘onClick’ event handler:

Code and Explanation:

UICombo.onClick = function(ID) { Implementation of event handler ‘onClick’of UI Combo, where ‘ID’ is the absolutepath of the item sprite recently clicked.

if(ID == p1) if path of the clicked item is equal to pathof item1 ‘1.Play Animation’, then,

animation.play(); play the sprite ‘animation’else if(ID == p2) else if the path of clicked item is

same/equal to path of item2 ‘2.StopAnimation’, then,

animation.stop(); stop the animation in sprite ‘animation’}; closing block of event handler ‘onClick’

Note: You can also get the last clicked/selected item using variable ‘selected’, as:

if(UICombo.selected == p1) ……

How to have a UI Combo default expanded/opened?

Use function ‘expand’ to have a UI Combo default opened, example implemented innext file:


How to get an item from a UI Combo to operate on?

There are two built-in functions ‘getItem’ and ‘getItemById’ when give you directaccess to an item individually. In next example, we will get access to first item andchange 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

Page 163: Swish Climax


‘CHANGED’ after the button click.

Code on Button Object found in example, that is used to change caption of first item:

on(release) { item = UICombo.getItem(1); item.caption = "CHANGED";}


item = UICombo.getItem(1); create pointing variable for item No. 1item.caption = "CHANGED"; assign new caption through property


which may also be implemented through function ‘getItemById’, as:

item = UICombo.getItemById("item1"); create pointing variable for item No. 1item.caption = "CHANGED"; assign new caption through property


Direct methods without use of pointing variable:

UICombo.getItem(1).caption = "CHANGED";orUICombo.getItemById("item1").caption = "CHANGED";

Disabling and Enabling a UI Combo item:

Disabling mean, stop user access to click the item. Combo level Functions‘disableItem’, ‘disableItemById’ and ‘enableItem’, ‘enableItemById’ are used for thispurpose.

Example from file UICO_22.swi:

1.Direct methods:UICombo.disableItem(1);UICombo.disableItemById("item2");

Use the same to enable the disabled items:


2.Disabling and enabling through direct access to an item:


Page 164: Swish Climax


Note: if you want to disable or disable an item through direct access to an item, usefunctions ‘enable()’ and ‘disable()’. These two functions have different functionalityon combo level.

See the preview of above example. Note, the first item has been disabled, whenbutton (at bottom) is clicked.

Disable and Enable UI Combo completely:

To disable, and re-enable a complete UI Combo use functions ‘enable’ and ‘disable’,so that user cannot perform any operation over it (through mouse). Example of it isin file UICO_23.swi. test through clicking the buttons at bottom o the movie.function ‘disable’ disables a UI Combo on the position wherever it was previously.See the preview of the example, after it has been expanded and then disabled:

Stop a UI Combo to accept more items:

This is another feature of UI Combo. It allows you to stop your UI Combo to not toaccept more items at a certain point. This functionality is performed by combo levelfunctions ‘lock’ and ‘unlock’. Such as:

UICombo.lock(); from now on, do not accept anymore entriesUICombo.unlock(); start accepting new entries from now on

UI Combo Style switching at runtime (using UI Combo as List Box)

Page 165: Swish Climax


Style switching is one of big features of UI Combo, where you can turn your UICombo 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, sothat, 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 ofthe UI Combo, as shown below:

You will notice that, your UI Combo is turned into a full functional list box and thedropper button (which was on top-right corner of UI Combo) is automaticallydisappeared; as sown below:

You can switch the mode through script as well. See example file UICO_25.swi.

Extra code line in example and its explanation:


function ‘setClipable’ is used to switch between styles and accepts only oneargument 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 ispassed, it is restored original layout.

Note: the combo turned to a listbox style, and became dragable too; you may dragthe listbox by clipping it from title.

Now for example, you do not want to allow the user to switch between modes, andset a default mode for him/her to work with. Use function ‘allowUserClipping’ to turnstyle switching ON or OFF. Open example file UICO_26.swi. run the example andsee, that, you cannot find the button (on top-left corner of UI Combo) which allowsyou to switch between styles.

Code to set style switching OFF (false):UICombo.allowUserClipping(false);

Similarly the code to set style switching ON (true):UICombo.allowUserClipping(true);How to make a UI Combo non-dragable?

You may also want to disable the dragging of the control for user. If you wish to plansuch, use function ‘setDragable’, and pass it boolean value ‘false’ as argument to

Page 166: Swish Climax


disable the dragging, pass ‘true’ otherwise (default is true), see example code takenfrom file UICO_27.swi:


UI Toolbars

UI Toolbar Collection Object provides you ease to create a set of icons withina dragable/resizable interactive toolbar. You can add shortcut icons to a UI Toolbarat runtime. It has some events to work with, which allow you to capture the behaviorof a UI Toolbar at runtime, and some functions to manipulate a UI Toolbar. You canalso 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 iconsyourself (procedure will be demonstrated in upcoming discussions).

How to insert a UI Toolbar in your SWiSHMax project?

Copy the sprite ‘UIToolbar’ from any o the relevant examples and copy in yourSWiSHMax project.

Our first example of UI Toolbar is implemented in file UICO_28.swi (preview):

Run the example and test it.Now, come to the code in main timeline (explanation):

onLoad() { event handler ‘onLoad’ of main timelineUIToolbar.onReady = function() { implementation of handler for event

‘onReady’ of UI Toolbar object, which isautomatically generated/fired when a UIToolbar is ready to operate. Now, when itis ready to operate,

with(UIToolbar) { use ‘with’ statement to access innerfunctions and properties of the sprite‘UIToolbar’.

addTag(true); add a new Tag using function ‘addTag’,from where user can drag the wholetoolbar. Value ‘true’ is passed asargument, which means the new addedtag is dragable, pass ‘false’ otherwise.This is tag area:

Page 167: Swish Climax


addButton("b1","screen"); add new button to the UI Toolbar, usingfunction ‘addButton’. This functionrequires 2 (two) or 3 (three) arguments(all are string type). Where the firstargument is the unique id/name of thebutton through which we can access itindividually, 2nd argument is theembedded icon name.

Names of Embedded Icons:cd, folder, document, screen, setup, globe, help, tip, documentblue, and folderblue.

addButton("b2","folder"); -do- (add another button)addButton("b3","document"); -do- (add another button)} closing block of ‘with’ statement}; closing block of event handler ‘onReady’} closing block of event handler ‘onLoad’

Note: If third argument of function ‘addButton’ is ignored it does not set any ToolTipfor the added button. Your can also set custom ToolTip text to buttons in a UIToolbar, while adding the buttons.

Adding a button with ToolTip:

addButton( button_id, icon_name [, tooltip_text]);

See example UICO_29.swi of UI Toolbar where we have added ToolTip to eachbutton. Here is the preview of the file, a ToolTip (‘Go to Home’) is shown whenmouse cursor rolls over the first button:

Here is the code in main timeline:addButton("b1","screen","Go to Home"); 3rd argument passed, so, ToolTip

set for this button.addButton("b2","folder","Open Document"); -do-addButton("b3","document"); We did not pass 3rd argument, so

that, the ToolTip will not be set forthis button.

Page 168: Swish Climax


Separate Buttons by adding separator:

See example UICO_30.swi of UI Toolbar, where we have 4 (four) buttons; 2 (two)groups (each of 2 buttons) are separated with a separator in between them:


See the code (extra line) in main timeline and it explanation:

addSeparator(); Function ‘addSeparator’ of UI Toolbar that allowsto add new separator between button. It acceptsno argument at all. Simply call it the way it isshown.

Resizing the width of the UI Toolbar:

User can resize the UI Toolbar at runtime, by using the button in right most corner ofthe UI Toolbar, as shown below (highlighted in green border):

Try resizing the UI Toolbar from this button (at runtime) yourself by running any ofthe examples provided for UI Toolbar.

Resizing the width of the UI Toolbar through script:

You must be looking for a way to resize a UI Toolbar yourself, so that, an initialwidth 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 isimplemented in example file UICO_31.swi.

See the additional code line:

setWidth(280); set the width of UI Toolbar to 280 pixels

After running it, you will notice that the width of the UI Toolbar is large by default.As shown here:

Adding additional non-dragable tags within the UI Toolbar:

Page 169: Swish Climax


e.g. To make the UI Toolbar more cool, you wish to add more tags to it instead ofseparators. See the file UICO_32.swi that contains example of additional tags in atoolbar (preview):

See the code (addition line) ‘addTag(false);’, which adds a new tag, but due to theargument passed ‘false’, the UI Toolbar is not dragable from the send tag.

Disable and re-Enable a UI Toolbar for the user:

You can also disable a UI Toolbar by using function ‘disable’, so that, the user cannotperform any operation over it through mouse. Run the example file UICO_33.swiand click the button ‘Disable UI Toolbar’. You will notice that after clicking this buttonthe UI Toolbar is no more clickable and no more dragable, and has been fadedsomething like this:

The code for button to disable is:

on(release) { UIToolbar.disable();}

and to re-enable the UI Toolbar click the button ‘Enable’ which will enable the UIToolbar, 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 isclicked.

Tracking the clicked button in a UI Toolbar:

An event ‘onClick’ is generated/fired when a button of a UI Toolbar is clicked by theuser. Now we can implement this event as handler according to our needs. Our firstexample of UI Toolbar event capture is implemented in example file UICO_34.swiwhich gives is the id of the button clicked, so that, we can take specific action onspecific button click.

Implementation of ‘onClick’ event handler:

See last few lines:

Page 170: Swish Climax


UIToolbar.onClick=function() { implement a handler for event ‘onClick’,now, when event has been fired, let uswrite the code to be executed.

msg=UIToolbar.lastID; get the id of the last clicked button fromvariable ‘lastID’ of UI Toolbar (‘UIToolbar’sprite), and assign it to the variable ‘msg’which is attached to a dynamic textbox.


Now run example and notice the value of the textbox is changed according thebutton click from the UI Toolbar.

Move to a bit advanced example, run/test file UICO_35.swi that contains a simpleanimation which is controlled through the UI Toolbar buttons. 1st button is used toplay the animation and second button is being used to stop the animation. Here isthe preview of the movie:

Let us see the code in main timeline that is controlling the events of button click:With Explanation:

UIToolbar.onClick=function() { implement handler of event ‘onClick’ of UIToolbar

id=UIToolbar.lastID; get the id/name of the last clicked button andsave it in a new variable ‘id’, it may also be as:‘id=UIToolbar.getLastClicked();’

if(id eq "b1") now, if the last clicked button id is equal to ‘b1’then,

animation.play(); play the timeline of sprite ‘animation’else if(id eq "b2") otherwise if the last clicked button’s id then,animation.stop(); stop the playing sprite ‘animation’}; closing block of event handler ‘onClick’

Additional Function to manipulate a UI Toolbar:

setTooltipText(bID,bText) set Custom ToolTip text of a button at runtime,where you replace ‘bID’ with button id and‘bText’ with the new ToolTip text.

Page 171: Swish Climax


removeTooltipText(bID) remove the ToolTip text from a button (if set)getButtonById(bID) get access to button directly, where ‘bID’ is the

button iddisableButon(bID) disable a single button in UI Toolbar.getWidth() get current width of the UI Toolbar in pixels

(don’t use _width property which may respondwrong)

totalItems() get number of buttons in a UI Toolbar.

Additional Event for UI Toolbar:

onStartDrag event fired/generated when UI Toolbar is startedbeing dragged by the user

onDragged event fired when UI Toolbar has been placedsomewhere after dragging

onStartResize event fired when UI Toolbar is started beingresized

onResize event fired when UI Toolbar is being resizedonResized event fired when UI Toolbar has been resizedonButtonAdded event fired when a new button is added to UI


UI Spreadsheet

This sophisticated allows you to add full functional spread sheets to yourSWiSHMax 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 unlimitednumber 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 Spreadsheetfunctions are controlled through script, where the developer can allow or disallowsome or a set of functions to user. Colors, font, and other layout options can bealtered from within SWiSHMax environment except some of the functions which allowalteration 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 asMicrosoft Excel. Here is the preview of a normal UI Spreadsheet:

How to insert a UI Spreadsheet in my SWiSHMax project?

Open any of the examples of UI Spreadsheet, such as UICO_36.swi, copy the sprite‘UISpreadsheet’ and paste in your SWiSHMax project file.

Getting started with UI Spreadsheet:

Page 172: Swish Climax


To get started with this Collection Object, first, we must know somefunctioning structure of the UI Spreadsheet Collection Object. UI Spreadsheet workslike a normal spread sheet built up of columns and rows, where Each cell maycontain different value from others. As in other spread sheet software, you cannotinsert a new single cell, but new column and/or new row. You can also name thehead 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 tagavailable for each inserted row, through which you can select entire row. Eachcolumn is also selectable individually through user click. The developer can get thedata from selected or unselected cell, column, or row through script and process itaccording to your project requirements. This type of control can be used to develop asite for school results, employee sales/payroll program, or polling and user rankingsystems etc.

There is no limit for number of columns and/or rows, it is dependant upon thememory and power of user’s computer either it can handle a huge UI Spreadsheet ornot. Usually it does not take much memory, but its examples are tested on PentiumIV processor, and worked perfectly with huge number of columns and rows. Thecolumns are resizable at runtime, so that, the user can view the data the way s/hefeels comfortable.

Let UI Spreadsheet get started with examples and code. Our first example iscontained in file UICO_36.swi.

Code of main timeline and its explanation:

onLoad () { event handler ‘onLoad’ o main timelineUISpreadsheet.onReady = function() { implementation of the handler for event

‘onReady’ which is fired/generatedautomatically when a UI Spreadsheet isfully loaded into memory and is ready toaccept operations.

UISpreadsheet.addColumn("Name"); Add a new Column to the UI Spreadsheet,using function ‘addColumn’, where"Name" is the caption of the new columnto be added (caption is shown over thehead of column)

UISpreadsheet.addColumn("Email"); Add another column with head "Email"UISpreadsheet.addRow(); Add new Row to the UI Spreadsheet,

using function ‘addRow’ which does nottake any argument.

UISpreadsheet.addRow(); -do- add one more Row}; closing block of event handler ‘onReady’} closing block of event handler ‘onLoad’

Note: It does not matter, if you add Rows before adding Columns.

Changing the value of a cell:

Page 173: Swish Climax


Here we demonstrate you the function ‘getCell’, which returns the path of a cell wecan 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, thevalue 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";}


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 thespecific cell we obtained through ‘getCell’function of UI Spreadsheet.

mycell.value="Ali"; Assign a new value to the cell through itsproperty ‘value’


This operation may also be done through a shortcut method as:


Page 174: Swish Climax


Can user alter/change the values of cells:

Yes, the user can alter the values by clicking on the cell and alter the value througha popup input text. Run the previous example again and click on any of the cell; youwill notice that, an input box appears on the top-left corner of sheet, as shownbelow:

Above shown popup input textbox has 2 (two) buttons attached with it on the rightcorner. 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 willalso notice that, the value of selected cell is also being changed exactly as the typedtext. This feature is to provide an ease to the user to edit the UI Spreadsheet datahim/herself. But you have the full control over this Collection Object, where you canturn user editing ON or OFF. How?

Turning the user editing ON/OFF:

By turning user editing OFF, the user is no more able to modify the data/values ofthe cells, although s/he can select the cells as in normal mode. Open fileUICO_38.swi, run the example, and select any of the cells by clicking over it. Youwill notice that, there is no input box appearing anymore. How did we do that?

See the code we used to disable the user editing option (explanation):There is an additional line of code in the main timeline, as:

UISpreadsheet.setEditable(false); use the function ‘setEditable’ to turn the userediting OFF by passing the argument value‘false’.

Now if, at a certain point you wish to turn the user editing ON, simply use thefunction ‘setEditable’ but pass the boolean value ‘true’, which will enable the userediting, as here:


How to get the value of currently selected cell?

For this purpose we have an event ‘onSelect’, which is invoked when a single cell isselected. Open example file UICO_39.swi which contains the implementation ofhandler for event ‘onSelect’, run it, and select any of the cell (suppose you selectedcell at col:1 and row:1), note the textbox at bottom of movie contains the value ofthe selected cell:

Page 175: Swish Climax


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


UISpreadsheet.onSelect = function() { implementation of the handler for event‘onSelect’ which is invoked/fired when acell is selected by the user through mouseclick.

mycell=UISpreadsheet.selectedCell; Get the currently selected cell from the UISpreadsheet from its property‘selectedCell’, and assign it to a newvariable ‘mycell’, so that, we would accessthe selected cell directly through variable‘mycell’ (mycell is the pointing variable).

msg=mycell.value; get the value of selected cell through itsproperty ‘value’ and assign the to variable‘msg’ which is attached to a dynamictextbox _msg.

}; closing block of the event handler‘onSelect’

How to alter the value of priorly selected Cell?

Simply, get access to currently selected cell through property ‘selectedCell’ of UISpreadsheet and alter the cell property ‘value’ through it, as:

UISpreadsheet.selectedCell.value = 1500;

Page 176: Swish Climax


How to get access to/obtain value of each cell of a specific column?

Logically a column may contain 1 (one) or more cells in it, so that, the values of thecells may not be obtained as a single value. So we put all the values of cellssequentially into a data Array. The function ‘getColumnValues’ returns an arraycontaining the values of all cells within a column of UI Spreadsheet. I hope youremember the use of Arrays, we already studied in depth. Open file UICO_40.swiwhich contains the example of obtaining data from a selected cell. Run the exampleand click button captioned ‘Get values of Column 1’. You will see the values of firstcolumn (separated with comma ‘,’) are shown in the textbox at bottom of the movie,as shown here:

Note: if an array is displayed in a textbox, final value automatically becomes acomma ‘,’ delimited string of the values in the Array.

See the code and explanation:This code is for the button in the movie:

on(release) {myArray = UISpreadsheet.getColumnValues(1); Get values (as array) of column #1

(one), through function‘getColumnValues’ and assign to anew variable ‘myArray’,

msg = myArray; then assign the values in array to avariable ‘msg’ that is attached to adynamic textbox.


Obtain values of a specific row from UI Spreadsheet:

The Same way you can obtain values of a row in UI Spreadsheet through function‘getRowValues’, see screenshot of example file UICO_41.swi. after the button(captioned ‘Get Values of Row 2’) is clicked:

Page 177: Swish Climax


Where code for the button used to operate was:

on(release) { myArray = UISpreadsheet.getRowValues(2); msg = myArray;}

Obtaining access to a specific Column or Row:

Logically obtaining access to a specific column means to get access to all cellsattached to a specific column. Similarly obtaining access to a row means to getaccess to all the cells in a specific row. Following are the functions used for thispurpose:

Remember: these functions do not return the values of cells but accurate path to thecell sprites, so you can obtain each cell value by ‘mycol[n-1].value’ where n is theindex/serial of cell in sequence

mycol=UISpreadsheet.getColumn(1); get column #1 from UISpreadsheet and savereturning cells as array intovariable ‘mycol’

mycol=UISpreadsheet.getColumnById("Email"); get column with tag name‘Email’ and save in variable‘mycol’

myrow=UISpreadsheet.getRow(1); get row #1 from UISpreadsheet and saveresulting array in variable‘myrow’

How to get access to the currently selected Column or currently selected Row?

As we already mentioned that the UI Spreadsheet Collection Object allows user toselect all the cells in a specific column or a row. So the selected column or theselected row is saved in two different properties of he UI Spreadsheet‘selectedColumn’ and ‘selectedRow’, which provide the same resulting arraycontaining path to each cell.

Page 178: Swish Climax


Stop a UI Spreadsheet using default values:

You must have noticed that there are some initial values in the cells before assigningnew values or editing. You can turn the default values OFF using function‘setDefaultValues’, which accepts only one argument/parameter of Boolean type. Ifyou pass ‘false’ as argument the default values are set OFF (by default the defaultvalues are set ON). You may open example file UICO_42.swi and run it, you willnotice that all the cells are empty by default. Here is the preview of the examplewhen ran:

The syntax:UISpreadsheet.setDefaultValues(false);

Note: this function should be called before adding any columns and/or rows, afterthis function has been added to code (with false value as argument), the cells ofnext added rows and columns will be empty.

Creating a Borderless cells UI Spreadsheet:

You can also hide the border of the cells using function ‘setBorderless’, which doesnot take any parameter/argument. After this function is called, the cells of nextinserted columns and rows are border less, as shown here (preview of exampleUICO_43.swi):


Creating a UI Spreadsheet with no top heads and left tags:

Use function ‘showCellsOnly’ to have the UI Spreadsheet without head and left tags.So that, it looks like (preview of example UICO_44.swi):

There are 4 (four) more advanced functions for UI Spreadsheet Collection Objectused to plot data as Pie Chart, Bar Graph, and/or line Graph, which will be discussedat the end of this chapter

Additional event for UI Spreadsheet:

Page 179: Swish Climax


onColumnAdded event invoked/fired when a new Column is addedto the UI Spreadsheet

onRowAdded event invoked/fired when a new Row is added tothe UI Spreadsheet

UI Form Dialogue

UI Form Dialogue acts as a usual forms/dialogues used in almost all applications ofmodern operating systems. Form is the basic unit of almost every visual application.Forums in Microsoft Windows operating systems are usually with 3 (three) buttonsminimize, maximize/restore/close, a Titlebar with caption over it, and the form viewarea (where every component/input is shown). UI Form Dialogue is also dragable aswell as resizable at runtime as other forums of an operating system.

Preview of a usual form dialogues of Microsoft Windows 98:

Preview of a usual form dialogues of Microsoft Windows XP:

Page 180: Swish Climax


Preview of a usual form dialogues of RedHat Linux 8:

Preview of a usual form dialogues of Linspire (Lindows) OS 4.5:

Preview of our UI Form Dialogue:

Above preview is taken from example file UICO_45.swi. Test the example in player,try dragging the Form Dialogue, try resizing it from left, right, and bottom corners,and test maximize/restore option by clicking on the button in middle of the buttonson top-right corner of form. Automation of minimize and close options, will bedemonstrated in upcoming discussion.

What is a Form used for?

Page 181: Swish Climax


A Form itself does not perform any important operations, but used as a stagecombining several sub components to perform a specific task. So, a UI FormDialogue has a specific part where it may contain sub components or load anexternal movie from outside.

An Extra feature (auto percentage preloader):

When an out resource is loaded into UI Form Dialogue, it automatically adds anaccurate percentage preloader just under the Titlebar.

How to insert/add a UI Form Dialogue to my SWiSHMax project?

Open any of the example files, copy sprite ‘UIForm’, paste it in your SWiSHMaxproject file, and move it to desired position.

Setting Title/Caption of a UI Form Dialogue:

Use function ‘setCaption’ to set Title/Caption of a UI Form Dialogue, as:UIForm.setCaption("My new UI Form Dialogue Title");

Loading external SWF movie in the Form area:

Function ‘loadResource’ is used to load external SWF movie or JPEG image within theforum stage area. Open example file UICO_46.swi, export the SWF file to theexamples folder, then test in player, and press button ‘Load Resource’. This is thepreview of the movie when an external image has been loaded into it:

Script used in button’s event ‘on(release)’:

on(release) {UIForm.loadResource("UICO_46.jpeg"); function ‘loadResource’ of UI Form

Dialogue accepts only oneargument of string type asabsolute path to external resourcefile to be loaded, either an SWF orJPEG file. As we passed‘UICO_46.jpeg’ name of JPEG file.


Page 182: Swish Climax


Now, let us try loading an external SWF file ‘external1.swf’, open example fileUICO_47.swi, and test in player. We loaded an SWF file through same function‘loadResource’, see the script used for button:


Review of event ‘onReady’:

This event is invoked/fired automatically, when a UI Form Dialogue is fully loadedinto memory and is ready to perform further actions. So, you have you implement itas an handler within the timeline’s ‘onLoad’ event handler, as it is implementedwithin almost all the examples.

Setting width and height of the UI Form Dialogue at startup:

You may not want the default size height and width of the UI Form Dialogue whenmovie starts. In this case you will be using function ‘resize’, to resize the forum todesired height and width. open example file UICO_48.swi, and run it, you will seethe following preview (setting width and height both to 300 pixels):

Script in main timeline to set UI Form Dialogue custom size:

onLoad() { event handler ‘onLoad’ of main timelineUIForm.onReady = function() { event handler ‘onReady’ of UI Form

DialogueUIForm.resize(300,300); use function ‘resize’ to resize form to

custom width and height, where , firstargument is width in pixels, and second isheight in pixels of the UI Form Dialogue.


Page 183: Swish Climax


Setting a UI Form Dialogue non-resizable:

Function ‘setResizable’ used to set a UI Form Dialogue resizable and non-resizable.Function ‘setResizable’ accepts only one argument of boolean type, either true orfalse. To set it non-resizable (static) pass value ‘false’ to this function, and to re-enable the resizing pass ‘true’. Open file UICO_49.swi, test it in player; you willnotice that the UI Form Dialogue is no more resizable, and the middle button(maximize/resize) has also been disabled and user is not anymore able to resize it,see preview:

Syntax to use function ‘setResizable’:

UIForm.setResizable(false); set resizable functionality OFFUIForm.setResizable(true); set resizable functionality ON

Disable or Enable the UI Form Dialogue:

UIForm.disable() disable the UI Form Dialogue, so that, it is notoperatable by the user anymore, nor evenclickable

UIForm.enable() enable back the UI Form Dialogue

Additional Functions for UI Form Dialogue:

UIForm.setMaxSize(w,h) set the maximum size of resizing width andheight, where ‘w’ I width and ‘h’ is height.

UIForm.isDisabled() returns ‘true’ if form currently disabled and ‘false’otherwise

UIForm.maximize() maximize the form through scriptUIForm.restore() restore the form to original width & height

through scriptUIForm.getX() current X coordinatesUIForm.getY() current X coordinatesUIForm.getWidth() get width of the form (don’t use _width property)UIForm.getHeight() get height of the form (don’t use _height

property)UIForm.topOnFocus() after calling this function, the UI Form Dialogue

swaps and becomes on top when dragged.UIForm.moveTo(x,y) move to specific X and Y coordinates on screenUIForm.getCaption() returns current Title/Caption of the UI FormAdditional Events for UI Form Dialogue:

onMaximize event invoked when a UI Form Dialogue is maximizedonMinimize event invoked when a UI Form Dialogue is minimizedonRestore event invoked when a UI Form Dialogue is restored to

original width and height

Page 184: Swish Climax


onClose event invoked when close button of UI Form Dialogue isclicked by the user

onResize event invoked when a UI Form Dialogue is resizedonDrag event invoked when a UI Form Dialogue is DraggedonDrop event invoked when a UI Form Dialogue is DroppedonDisable event invoked when a UI Form Dialogue is disabledonEnable event invoked when a UI Form Dialogue is enabled

Customizing the event ‘onClose’ and ‘onMinimize’:

You can implement custom handler for ‘onClose’ and ‘onMinimize’ events accordingto your needs, as:

UIForm.onClose = function() {take_some_action

};UIForm.onMinimize = function() {


Forms within Sprites (Encapsulation/Nested forms):

You have already tested the UI Form Dialogue’s maximize and restore features. Youmust 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 maximizedaccording to the movie/stage width and height. If a UI Form Dialogue is embeddedinto a normal sprite, it will maximized according to the width and the height of thesprite ‘pan’ in parent path. Open file UICO_50.swi, that demonstrates UI FormDialogue within the sprite.

Explaining the file UICO_50.swo structure:

Open the file, it contains a sprite ‘mySprite’ which contains further two sub-spritesin. 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 beenmaximized exactly to the width and height of the sprite ‘pan’ in parent path. So, youmust have a sprite named ‘pan’ in the same path where sprite ‘UIForm’ is, if youwish to embed the form sprite within other sprite.

Here is the preview of the above example before and after maximizing:

Page 185: Swish Climax


Before Maximize After maximize

Forms within Forms (Encapsulation/Nested forms):

You can load several UI Forms within a UI Form Dialogue. To do that, you will needto make another SWiSH movie (e.g. ’xyz.swi -> xyz.swf’), embed forms in it andload ‘xyz.swf’ in form using function ‘loadResource’. Example files xyz.swi andUICO_51.swi have been created for instance.

Preview of nested form from above example:

Preview of same example of the loaded form maximized within form:

Graphs and Charts

Best solution to present statistics big organization/sites (that maintain a hugeamount of data), is through Graphical shapes called Graphs or Charts, instead of

Page 186: Swish Climax


showing data in figures & tables and loosing much more bandwidth. For this type ofusers and developers we have developed 3D type Pie Charts, 3D Bar Graphs, andLine Graph Collection Objects (within your favorite environment of SWiSHMax),which do not only save your time but provided you a big ease to draw dynamiccharts and graphs at runtime and integrate them with any server-side script.

See the preview of three type of Graphical Charts:

All of above three types of charts/graphs can easily be used within your SWiSHMaxenvironment, and can easily be integrated with your data (even generated throughuser/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 datafrom plain text file, where you do not need to call and wait for data arrival, theseCollection Objects have their own functions to load, calculate/manipulate data andplot the graphs/charts.

UI Pie Charts

Pie Chart is the most used type of Graphical presentation of data. Many of theorganizations/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 eyecatching type of a pie chart is 3D pie chart. Our UI Pie Charts Collection Object is

Page 187: Swish Climax


developed directly 3D, in a view to provide best output/printing results and lesseruse of resources (memory and space).

How to insert/add a UI Pie Charts in my SWiSHMax project file?

Simply copy the sprite ‘UIPiechart’ from any of the example files provided for thisCollection Object, and paste into your SWiSHMax project file. Then you can positionit by dragging with mouse or moving it using arrow-keys.

First example of UI Pie Charts:

Our first example demonstrate the simplest example of a UI Pie Charts. Openexample 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, Iintroduce you a new and simplest way to create an Array without using object ‘Array’in definition/declaration as ‘new Array()’.


You simply type the comma ‘,’ delimited values within the square brackets ‘[’ and ‘]’,and assign it to some variable. The variable assigned to such structure willautomatically become an array, such as:

values = [10, 100, 3, 515]; create new array of 4 (four) integerelements in, and name it’s variable‘values’

Function UIPiechart.plot()

Function ‘plot’ of UI Pie Charts is used to populate/plot a UI Pie Charts with customvalues, labels, and colors. It basically requires 3 (three) array typearguments/parameters, where first argument is array of values, 2nd is array oflabels/captions, and last 3rd array of colors (hex values with ‘0x’ in start). Thisfunction calculates the percentage and required area automatically according to thevalues.

Page 188: Swish Climax


Note: number of elements for a UI Pie Charts are determined from the number ofvalues in the first argument of array type passed to function ‘plot’.

Now, see the script in main timeline, used to plot the UI Pie Charts (explanation):

onLoad() { event handler ‘onLoad’ of main timelineUIPiechart.onReady = function() { implementation of handler for event

‘onReady’, which is invoked/fired when aUI Pie Charts is fully loaded into memoryand ready to operate the data andperform further operations.

values = [1000, 400, 200, 100]; array containing valueslabels = ['Flash MX', 'SWiSH',….. array containing labels/captionscolors = [0x336699, 0xFF660….. array containing colors for each element

sequentiallyUIPiechart.plot(values, labels, colors); sad populate and plot the UI Pie Charts}; closing block of event handler ‘onReady’} closing block of event handler ‘onLoad’

Which are the labels/captions actually? Used in above example:

Answer, encircled ones in the following screenshot:

Direct Method:

You can do the same example, by passing the arrays directly to the function ‘plot’,instead of defining array variables first, such as the following example (taken fromfile UICO_53.swi):

Page 189: Swish Climax


Can I use UI Pie Charts sprite multiple times with different values, labels, colors, anddifferent number of values each time?

Absolutely yes, you can use a single UI Pie Charts sprite to plot the Charts (withcompletely 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 2buttons. In this example, we have populated the chart with initial values immediatelyas the movie is loaded. Then the two buttons ‘plot 1’ and ‘plot2’ are used to plot thechart with different values, labels, and colors. Test the example in player, and clickthe buttons. You will see the same sprite producing different results each time. Hereis 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 loadtime for the client browser and save bandwidth of your server.

UI Pie Charts Loading Data from text file:

This is also not static, you can load and plot the pie chart from several text files onserver. For this purpose, we have a function ‘plotFromFile’, which accepts only one

Page 190: Swish Climax


argument/parameter of string type as name of the file to be loaded data from. Thefile may be in current path where the movie is loaded from, or on some other site. Ifthe 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 fileUICO_55.swi, export SWF to the examples folder where it will load the fileUICO_55.txt. And run the example SWF now. If the UI Pie Charts cannot read thefile in specified path, it displays an error such as ‘ERROR loading UIPiechart data file– UICO_55.txt’.

Script used to plot UI Pie Charts from text file:

UIPiechart.plotFromFile("UICO_55.txt"); call the function ‘plotFromFile’ of UIPie Charts and pass it the filenameto loaded data from, as parameter.

How to get a pie chart data from a server-side PHP script?

It is as easy as the loading of data from a text file. The same function ‘plotFromFile’is used to call the script and get data from it. Now your server-end PHP script mustbe 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 UIPie Charts. This example loads the file UICO_56.php the same way we loaded textfile in previous example, as:


Now let us have a view over the PHP script:

In following PHP script we have used some assumed data. We have assumed thisdata has been fetched from a database and then sent back to our movie.


$data = "&values=150,35,15,10& &labels=Flash MX,SWiSH,Swift 3D,K.Moves& &colors=0x3366FF,0x00ff00,0xFF0000,0x000000&";

echo $data;?>

Note: remember to run this script on server not local computer.

Additional functions for UI Pie Charts:

UIPiechart.setAlpha(new_alpha_value) function used to set custom alpha /opacity / visibility value of the UI PieCharts, accepts only one argument ofnumeric type, value from 0 (zero) to 100

Page 191: Swish Climax


(one hundred), see example fileUICO_57.swi.

UIPiechart.setWidth(newW) change width of the 3D pie slices area inpixels

UIPiechart.getWidth() get current width of the 3D pie slices areain pixels

UI Bar Graphs

Colors and design of the UI Bar Graphs can only be set/modified within SWiSHMaxenvironment and cannot be altered or set at runtime. UI Bar Graphs CollectionObject also works almost the similar way of the UI Pie Charts, where you pass thevalues and labels (not colors) to its function ‘plot’ and you UI Bar Graph is ready. Itis also capable of picking up entries from a plain text file as well as communicatewith a server-side script (PHP, asp, cfm, pearl etc).

First UI Bar Graphs example:

Our first example of UI Bar Graphs is implemented in file UICO_58.swi. Open thefile 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 PieCharts. The function with same name ‘plot’ is used to plot/populate a UI Bar Graphs.

UIBargraph.onReady = function() { implementation of handler for event‘onReady’, which is invoked/fired when a

Page 192: Swish Climax


UI Bar Graphs is fully loaded into memoryand us ready to operate.

values = [50, 30, 20, 60]; Create new array ‘values’ for UI BarGraphs entries

labels = ['Swift 3D', 'Flash…. Create new array ‘labels’ for UI BarGraphs labels

UIBargraph.plot(values, labels); plot the UI Bar Graphs using function ‘plot’}; closing block of event handler ‘onReady’

Reading values for a UI Bar Graphs from text file:

The same function ‘plotFromFile’ is to be used to read entries from text file. Openexample file UICO_59.swi, export it to examples folder so that, it can read the textfile UICO_59.txt from that folder, and then run it in the player.

Script in main timeline:

UIBargraph.plotFromFile("UICO_59.txt"); use function ‘plotFromFile’ to reada text file that contains comma ‘,’values and labels

Text in the text file UICO_59.txt:

&values=50,35,15,10& comma ‘,’ delimited values&labels=Flash MX,SWiSH,Swift 3D,K.Moves& comma ‘,’ delimited labels

Is it possible to use UI Bar Graphs sprite multiple times?

Yes, it is possible. Use the same functions ‘plot’ or ‘plotFromFile’ to populate the UIBar Graphs with different values and labels. The UI Bar Graphs is automaticallyupdated when you call any of these two functions.

Loading data for UI Bar Graphs from a PHP script:

Follow exactly the same method we used to load the data from text file, pass thePHP script file name which will process data either from text and/or MySQL databaseand response back and variables. Example file UICO_60.swi is implemented for thispurpose, see and manipulate yourself (because we already demonstrated theprocedure in previous topic of UI Pie Charts). Do not forget to upload the PHPmodule as well.

Note: remember to run this script on server not local computer.What to do, if I do not want to show the labels?

Simply turn the labels OFF through function ‘setLabels’, by passing it a boolean value‘false’, but remember to call this function before calling the function ‘plot’. Open fileUICO_61.swi and test it in player. You will see the following preview:

Page 193: Swish Climax


Here is the additional script we used before plotting UI Bar Graphs:


Now, if you need to turn the labels ON, pass boolean value ‘true’ to this function andre-plot the UI Bar Graphs.

How to insert/add a UI Pie Charts in my SWiSHMax project file?

Simply copy the sprite ‘UIPiechart’ from any of the example files provided for thisCollection Object, and paste into your SWiSHMax project file. Then you can positionit by dragging with mouse or moving it using arrow-keys.

How to modify the design and layout of the UI Bar Graphs?

Open sprite ‘UIBargraph’, then sprite ‘item’ and change the design of followingencircled sprites:

He is the example of UI Bar Graphs in cylinder style:Preview taken from example UICO_62.swi:

Page 194: Swish Climax


UI Line Graphs

UI Line Graph work exactly the same way as the UI Bar Graphs. UI Line Graph hasexactly same data gathering and plotting functions.

How to insert/add a UI Pie Charts in my SWiSHMax project file?

Simply copy the sprite ‘UIPiechart’ from any of the example files provided for thisCollection Object, and paste into your SWiSHMax project file. Then you can positionit by dragging with mouse or moving it using arrow-keys.

First example of UI Line Graph:Preview of example file UICO_63.swi (has same code used for UI Bar Graphs):

How to set custom line color and thickness?

Use function ‘setLineStyle’, which accepts two arguments/parameters, 1st thicknessof line in pixels, and 2nd parameter color of the line (a hex value). Open example fileUICO_63.swi where we set the line thickness 5 pixels, and color (red = 0xFF0000),see the preview:

Page 195: Swish Climax


Script used to set the line style (function ‘setLineStyle’):

UILinegraph.setLineStyle(5, 0xFF0000);

Connecting UI Spreadsheet with UI Pie Charts, UI Line Graphs, and UI BarGraphs:

The most wanted/requested functionality of the charts and graphs is to have themconnected with the spread sheet (UI Spreadsheet) type data. Here, we introduce yousome additional functions of the UI Spreadsheet that enable the developer toconnect their UI Spreadsheet with any of the graphs or charts Collection Object.

There is are some specifications to connect UI Spreadsheet to graph or chart:

1. Only a single row of UI Spreadsheet can be connected to any of the graphs orcharts.

2. Row must contain numerical data in start of the string in each cell.3. Any of the values of cells in the row must be greater than zero.4. You must have the sprite of specific type of graph/chart within the movie to

connect to UI Spreadsheet (e.g. you are to plot UI Pie Charts, the, you must haveUI Pie Charts sprite within the movie alongwith the UI Spreadsheet sprite).

Following discussed four functions are used to plot a graph/chart based on the valuesobtained from a row of UI Spreadsheet.

Note again: these functions are specific to UI Spreadsheet.

Plot a UI Pie Charts using UI Spreadsheet:

Use function ‘plotUIPiechart’ to plot a UI Pie Charts based on the values obtainedfrom a specific row of UI Spreadsheet. It automatically fetched the fetches the labelsfrom 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 numericvalue.Open example file UICO_64.swi, test in player or browser, and click button ‘Plotfrom row 1’. You may also change the values of the cells of UI Spreadsheet byclicking over the cells and modifying them and then re-click the button. For exampleI change the value o the first cell to ‘1003’ and click the button, the chart seems tobe like this:

Page 196: Swish Climax


Let is view the code that we used to populate the UI Spreadsheet (in main timeline):Only the part where initial data has been set:

for(i=1; i<=4; i++) { mycell = UISpreadsheet.getCell(i,1); mycell.value=i*100; }};means:get each cell (1-4) one by one of row #1 and set its initial value.

The script in button’s event ‘on(release)’ (used to plot UI Pie Charts from UISpreadsheet):



Call the function ‘plotUIPiechart’ of UI Spreadsheet, and pass the twoarguments/parameters, first the path of UI Pie Charts sprite ‘UIPiechart’ (which is incurrent path so need to add prefix path to it such as ‘_root.UIPiechart’), and 2nd

argument is the row number (1) in the UI Spreadsheet.

How come the colors are set automatically?

There are some default color values used by this function, but it has a limitation.Note: you can use this function only with maximum 10 cells/values.

If the row contains more than 10 (ten) columns/cells, this function will show a smallwarning and will not plot the UI Pie Charts. In this case you will have to use otherfunction ‘plotUIPiechartCC’, which allows you to set custom colors. Function‘plotUIPiechartCC’ accepts 3 (three) arguments/parameters. 1st and 2nd argumentsare same as used in previously discussed function, and the last argument is thearray containing color values (in hexadecimal), where number of values must beequal or more than the number of columns/cells of the row.

Example Syntax:

mycolors = [0xFFFFFF,0xFF0000,0x000000, 0xEEEEEE,…………………];UISpreadsheet.plotUIPiechart(UIPiechart, 1, mycolors);

Plot a UI Bar Graphs using UI Spreadsheet:

Page 197: Swish Climax


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 changethe values in the UI Spreadsheet and plot the UI Bar Graphs with different values byclicking the button.

Script used in button’s event handler ‘on(release)’:



Use function ‘plotUIBargraph’ of UI Spreadsheet and pass two arguments to it.Where first argument is the path of the UI Bar Graphs sprite and second argument isthe row id/number to get data from.Plot a UI Line Graph using UI Spreadsheet:

Open example file UICO_66.swi, test in player and click the button ‘Plot from row1’. You will see the following preview after you click the button:

Page 198: Swish Climax



Use function ‘plotUILinegraph’ to plot a UI Line Graph based on values obtainedfrom a row of UI Spreadsheet. This function takes only two arguments same to thefunction in previous example. Where first argument is the path to the UI Line Graphsprite and second argument/parameter is the row id/number to fetch data from.



Page 199: Swish Climax


Chapter 7

Preloaders, Scrollers, Dynamic Drawing,and External MP3

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

Page 200: Swish Climax


We have already discussed many of Sprite and Text Object properties and functionsin previous chapters. But some of the functions and properties are brought to thischapter to understand them separately. This chapter demonstrates you how to addfully functional Preloaders to your existing SWiSHMax project files, Text Scrollingmethods and pre-built simple control, creating container (empty) Sprites at runtime,some script methods that allow the developer to draw lines & shapes with customcolor and gradient, and creating light and fully functional preloader with loaderBarand accurate percentage, built up of only and only script.

Additional utility functions for creating Preloaders

There are 3 (functions) which give us the exact size of the SWF movie being loaded,the remaining part of the SWF movie to be loaded (in bytes), and percentage of theloaded SWF movie size.

The preloader I am to demonstrate here, can be added to your main movies as wellas to the externally loaded movies. Many of the users create preloaders, but theyface unpredictable results when they embed those preloaders within the externallyloaded SWF movies. Then why not to create a prefect preloader that fits all theneeds either used to preload main movie and/or sub movies that are loaded asexternal movies.

Get, Set, Go

Function ‘getBytesTotal’:

‘getBytesTotal’ is one of the built-in functions in SWiSHScript that returns the totalmovie 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 thefunction ‘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 whichis logically wrong. Because, the preloaders are always in main timeline of eachmovie, and when a movie is loaded externally ‘_root’ does not refer to the currenttimeline but the main movie loader priorly. What to do? Use ‘this’ as prefix path ineach and everywhere you create the preloader. So that

moviesize = _root.getBytesTotal(); is LOGICALLY WRONG, and we won’t useit anymore

moviesize = this.getBytesTotal(); is PERFECT (or simply ignore ‘this’)‘this.getBytesTotal()’ or ‘getBytesTotal()’will always refer to main timeline of themovie currently being loaded and return the total size of it in bytes, not the actualmain movie loaded priorly.

Page 201: Swish Climax


Function ‘getBytesLoaded’:

‘getBytesLoaded’ is also a built-in functions of SWiSHScript that returns the numberof bytes loaded currently. E.g.

loadedsize = this.getBytesLoaded();

where ‘loadedsize’ is the variable assigned the number of bytes loaded from thecurrent SWF movie being loaded.

Now, we can obtain the percentage of the loaded movie, by dividing the loaded bytesover total bytes and then multiplying it with 100 (one hundred), as:

moviesize = this.getBytesTotal(); // or getBytesTotal();loadedsize = this.getBytesLoaded(); // or getBytesLoaded();percentage = (loadedsize/moviesize)*100;

BUT, why to use initializations and calculations in 3 (three) lines, when SWiSHScriptprovides us a built-in function to obtain percentage.

Obtain percentage of a loaded SWF movie:

Use function ‘percentLoaded’ to obtain the percentage of the loaded movie size. E.g.percentage = this.percentLoaded();

I already contributed many more tutorials and quick tips to create preloaders inonline community forums, which make so easy for a developer to add a perfectpreloader to the SWiSHMax project file. Here, I do quote the same steps to create agood 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 allscenes.

Steps to create perfect preloader:

1. Create a borderless rectangle of 100 pixels wide, and put it in the middle ofscreen (color desired)

2. Copy the rectangle, paste it, and move it to the same position where previousrectangle is, set its border line (thickness 0 of desired color), and there should beno 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();

Page 202: Swish Climax


msg = pl +"% Loaded"; if(pl == 1000) { play(); delete this.onEnterFrame; }}

8. Finally, Remember to put a stop action in your next scene’s timeline, so that, themovie does not come back to preloader scene once played.

Explanation of script used in step 7:

onLoad() { ‘onLoad’ event handler of main timeline ofpreloader scene.

stop(); stop the movie immediately as it startsloading

} closing block of ‘onLoad’ event handler

onEnterFrame() { ‘onEnterFrame’ event handler of maintimeline of preloader scene.

bar._width = pl = this.percentLoaded(); get percent loaded of current movie(referring through prefix path ‘this’)through function ‘percentLoaded’, assign itto new variable ‘pl’, and then assign it tothe width of sprite ‘bar’ as well, so that,the width sprite ‘bar’ is changed topercent loaded.

msg = pl +"% Loaded"; add a string ‘% Loaded’ with value ofvariable ‘pl’ that contains the percentageof loaded movie, and assign it to variable‘msg’ which is attached with a dynamictextbox (so that, it is displayed).

if(pl == 1000) { Now, check if percent loaded is 100 (full),then,

play(); play the current timeline, so that it goesto the next scene directly

delete this.onEnterFrame; job has been done, now delete the eventhandler ‘onEnterFrame’

} closing block of ‘if’ statement} closing block of ‘onEnterFrame’ event


Page 203: Swish Climax


Scroller for Dynamic and Input text objects

Almost 20 to 25% of the topics in almost every SWiSH community, are asked abouttext scrollers. We have developed a scroller to meet all of your needs. This scrollercan be attached to any type of textbox either dynamic or input. It appears anddisappears automatically when text is enough to show the scroller or empty. It isalso invisible until it is not attached to any textbox. We have named it ATBS (AllTimes Best Scroller). ATBS is also capable of drawing custom color border around thetextbox.

Adding ATBS in my SWiSHMax project file:

Open example file 034.swi or any example file of this resource, copy sprite ‘atbs’,and paste I anywhere (on any position) in your SWiSHMax project file. Why pasteanywhere? Because when ATBS is attached to a textbox it automatically resizes andmoves itself to the absolute position.

How to attach ATBS to a textbox?

Open example file 034.swi, which contains an input textbox ‘_msg’ and ATBS sprite‘atbs’. Test it in player. Remember: the ATBS does not show until there is notenough text in textbox to add scroller. Type some text lines more than the text area,so that, the ATBS is automatically visible. Here is the preview:

Script in main time line of example:

onLoad() { ‘onLoad’ event handler of main timelineatbs.onReady = function() { implementation the handler for event ‘onReady’

which is invoked/fired when the ATBS is ready tobe attached and operate.

atbs.attachTo(_msg); use function ‘attachTo’ of ATBS to attach theATBS to any textbox, and pass it the absolutepath of the textbox instance

}; closing block of ‘onReady’ event handler} closing block of ‘onLoad’ event handler

Attaching ATBS to the left side of the textbox:

Use the function ‘attachLeftTo’ and pass it the path + name of the of textbox object.Open example file 035.swi, and see the different line in script in main timeline:atbs.attachLeftTo(_msg); use function ‘attachLeftTo’ to attach the ATBS on

the left side of the textbox.

Page 204: Swish Climax


Preview of the example:

Set custom color border of the attached textbox:

Use function ‘makeObjBorder’ and pass it the color value (as hexadecimal), you willsee a border with custom color is shown over the textbox. See the script in maintimeline of example file 036.swi.

Note: the border will only be visible when ATBS is visible.Here is the preview of the example:

Script we used to draw border:

atbs.makeObjBorder(0xFF0000); 0xFF0000 is the value of red color in hex

Creating new Sprites at runtime

A function ‘createEmptyMovieClip’ of SWiSHScript, which is exactly same in Flash MXActionScript, is used to create a new sprites at runtime. This function is capable ofcreating new sprites within any defined path.

What is the use of empty sprites?

Mostly, the sprites created at runtime, are used to load external SWF movies and/orcustom drawing through SWiSHScript.Open example file 037.swi, and see the code in main timeline:

Page 205: Swish Climax


createEmptyMovieClip("newSprite",1); create new sprite using function‘createEmptyMovieClip’, which accepts twoarguments/parameters; 1st argument isname of the new sprite being created, and2nd parameter is the new depth of themovie. Remember when assigning depth,if there are some other objects already incurrent path then assign the new depth(n+1) where ‘n’ is number of existingobjects.

newSprite.loadMovie("external1.swf"); load movie external1.swf using function‘loadMovie’ within the newly created sprite‘newSprite’

You can treat the newly created sprites exactly as the physical sprites we usuallycreate within SWiSHMax environment.

Now, if you wish to create a new sprite within another ‘xyz’ sprite, then, use thesprite name ‘xyz’ as prefix path to this function, as

xyz.createEmptyMovieClip("newSprite",1);then access the sprite through ‘xyz.newSprite’.

Direct Drawing Methods in SWiSHScript

SWiSHScript also provides almost all functions for drawing at runtime that areavailable in Flash MX ActionScript. We will be discussing some of the functions (notall) that allow the develop to draw normal shapes through SWiSHScript.


Function ‘lineTo’ accepts two arguments of numeric type. It draws line from currentposition (usually x:0, y:0) to the passed positions as arguments. This function is alsoavailable in Borland Graphics Interface Library (BGI).



Function ‘moveTo’ accepts two arguments of numeric type. It moves the currentpointer to specific position specified as arguments, to start next drawing from. Thisfunction is also available in Borland Graphics Interface Library (BGI).



Page 206: Swish Climax


Function ‘lineStyle’ is used to set line thickness and color. This function accepts twoarguments. The first argument is the line thickness in pixels and 2nd as color (hexvalue).


beginFill, endFill

Function ‘beginFill’ is used to fill and bordered area. This function must be calledbefore 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 to100. Function ‘endFill’ is used when you have finished drawing border and wish to fill.



Scripted Preloaders

We have written a cut-n-paste preloader script for you, by combining all the scriptsfrom this chapter (dynamic drawing methods and preloader methods). What youhave to do is, simply copy the following script and paste in the main timeline ofpreloader scene (no need to insert any object or draw anything in the preloaderscene).

Here is the script (also available in CODE VAULT of www.scriptsector.com) takenfrom file 038.swi:


Page 207: Swish Climax


stop(); /* +-------------------------------------------------+ | change following hex value to desired colors | +-------------------------------------------------+ */ _global.bar_color = 0xDDDDDD; _global.text_color = 0x000000; _global.border_color = 0x666666; _global.bar_height = 10;

//Calculate screen's center if(this == _root) { _global.CX = int((Stage.width/2)-50); _global.CY = int((Stage.height/2)-(_global.bar_height/2)); } else { _global.CX = int((_parent._width/2)-50); _global.CY = int((_parent._height/2)-(_global.bar_height/2)); }

//Create loaderBar sprite 'bar' this.createEmptyMovieClip ("bar", 1); with (this.bar){ _x = CX; _y = CY; beginFill(bar_color,100); lineStyle (0, bar_color, 100);

moveTo (0, 0); lineTo (100, 0);

lineTo (100, bar_height); lineTo (0, bar_height); lineTo (0, 0);

endFill(); } bar._width=0; //Create loaderBar border sprite 'border' this.createEmptyMovieClip ("border", 2); with (this.border){ _x = CX; _y = CY; lineStyle (0, border_color, 100);

moveTo (0, 0); lineTo (100, 0);

lineTo (100, bar_height); lineTo (0, bar_height); lineTo (0, 0);


//Create percentage text display this.createTextField("mytext",3,CX,CY+bar_height,100,20); mytext.border = false; myformat = new TextFormat(); myformat.align = "center";

Page 208: Swish Climax


myformat.color = text_color; myformat.font = "Verdana"; myformat.size = 10; tData = "0% Loaded"; mytext.variable = "tData"; mytext.setTextFormat(myformat);

/* +------------------------------------------+ | Copyrights ® www.swishclimax.com | | Don't remove without permission | +------------------------------------------+ */ this.createTextField("copyright",4,CX-50,CY+bar_height+20,200,20); copyright.border = false; copyright.text = "Powered by www.scriptsector.com"; copyright.setTextFormat(myformat);

//Implement onEnterFrame to check //percentage until it is 100%... this.onEnterFrame = function() { pl = int(percentLoaded()); tData = pl+"% Loaded"; mytext.setTextFormat(myformat); bar._width=pl; if(pl == 100) { bar.removeSprite(); border.removeSprite(); mytext.removeTextField(); copyright.removeTextField(); play(); delete this.onEnterFrame; } }}//CODE ENDS HERE

Page 209: Swish Climax


Loading external mp3 sounds

SWiSHScript provides a scripting object ‘Sound’ to control the embedded as well asexternal sounds perfectly.

Create new Sound object to loaded external MP3 file:

s = new Sound(); allocate new Sound object ‘s’s.loadSound(“somefile.mp3”); use function ‘loadSound’ of ‘Sound’ object

to load an mp3 file from outside, pass itthe name of mp3 file alongwith absoluteURL.

Start playing the loaded MP3 file:

Use function ‘start’ to play an mp3 loaded through ‘Sound’ object, as:


Stop a playing sound:

Use function ‘stop’ to stop a playing sound under ‘Sound’ object, as:


Obtain the Total bytes, loaded Bytes, total Duration, and current Position of sound:

s.getBytesTotal() function returns the total file size in bytess.getBytesLoaded() function returns the total bytes loaded so fars.duration property returns the duration of a sound in

milliseconds.s.position property returns the number of milliseconds a

sound has been playing

Set the volume percentage:

Use function ‘setVolume’ to set percent (0-100) volume, as



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 its.start();


Simple Method for streaming:

Page 210: Swish Climax


Here is a simple example of audio streaming:

onLoad() {playonmaximum = 50; // when 50% sound loaded start playings =new Sound();s.loadSound(“somefile.mp3”);this.onEnterFrame = function() {

percent = (s.getBytesLoaded() / s.getBytestotal())*100;if(percent >= playonmaximum) {

s.start();delete this.onEnterFrame;



Page 211: Swish Climax


Chapter 8

Core Practice / Source Code / Details Study of MySQL with PHP Creating Interactive Polling System using UI Collection Objects Online Resources / Help

Page 212: Swish Climax


Study of MySQL with PHP

MySQL is a powerful database engine that works with PHP by default. This enginecan handle a huge amount of connections at a time/flood as well has a big amountdata. It uses SQL Standards with some additions in data types.

The structure of the MySQL Engine:

Structure of MySQL engine can easily be understood from following picture.

Hierarchical structure of the MySQL engine is like the folders and files in theMicrosoft Windows Explorer. That, there should not be two or more folders of samename (regardless capital letters), and there should not be two or more files of thesame name (including extension) in same path. MySQL acts same, two are moredatabases cannot be of same name under one MySQL engine, similarly two or moretables of same name cannot be created under one database.

Mostly the database for a specific use is created by the hosting companiesthemselves and a lot the user a username and a password, through which userconnects to MySQL engine and runs the queries.

If a hosting company provides you MySQL database as well as the web space withinsame server, the engine is considered local host (although it is not running on localPC). But, when you have web space (PHP scripts) and MySQL database on twoseparate hosts, the connection to the engine will be established through the IP orURL granted by the hosting company.

There are dozens of built-in functions in PHP that enable the developer to manipulatedata in a database of MySQL engine. Here we go to discuss some of the most usedfunctions. Remember: The name of each and every function that is to be used forMySQL starts with prefix ‘mysql_’.

Page 213: Swish Climax


How to connect to MySQL engine?

Use function ‘mysql_connect’ to connect to the MySQL engine.


mysql_connect( host_name, username, password);

Where ‘host_name’ is the host (if script and MySQL both are on same server use‘localhost’ otherwise the granted IP or URL), username and password the same onewe discussed above.

How to know, either I am connected to MySQL engine or not?

Call the function ‘mysql_connect’ same way (mentioned above) and assign it to somevariable. Function ‘mysql_connect’ returns a boolean values after executed. If itreturns true, it means you are successfully connected to MySQL, and if it returnsfalse that means some error has occurred and connection could not be established.See following example code:

$myVar = mysql_connect(“localhost”, “Ali”, “Imran”);if($myVar == false) echo “ERROR: cannot connect to MySQL”;else echo “Successfully connected”;

Showing the errors generated by the server:

Usually the errors come up automatically, but some of the hosts set the errors OFFbecause of some reasons. In this case, if you wish to see the actual error generatedby the system, use function ‘mysql_error’ (which returns error string), as:

$myVar = mysql_connect(“localhost”, “Ali”, “Imran”);if($myVar == false) echo mysql_error();

Setting MySQL generated errors OFF:

May be (in some scenario) you wish the system not to display errors automatically.So that you can display custom error to the user. To do this, you simply put a ‘@’(sign : at the rate of) before the function name, see the following code:

$myVar = @mysql_connect(“localhost”, “Ali”, “Imran”);if($myVar == false) echo mysql_error();

Now, you must have been granted a database name that you are allowed to use. Towork on tables in a MySQL database, you must select the database first.

Selecting a database:

Page 214: Swish Climax


Use function ‘mysql_select_db’ to select an allowed database from MySQL engine,and pass it the database name as string (name of database) or a variable containingstring valued as name of database; as:

mysql_select_db( “alis_database”);

This function also returns true on success.

So from now on, remember to call both of the above discussed functions to establisha connection with MySQL database:

First connect to MySQL engine mysql_connect(“localhost”, “Ali”, “Imran”);Then select the database mysql_select_db( “alis_database”);

DML Operations:

What is DML? DML stands for Data Manipulation Language. It has 3 (three) majorfunctions:Data Insertion Inserting data into tablesData Deletion Deleting specific data from a tableData Modification Modifying existing data in a table

To perform above three DML operations, we run queries; First, we need to knowwhat is a query.


Query is a statement (set of several MySQL keywords and user data) that isexecuted by the MySQL engine and data is altered. Query is written following theMySQL syntax. Here are the examples of queries to be used to perform DMLoperations. If you have to execute multiple queries use semicolon ‘;’ on the end ofeach MySQL statement.


INSERT INTO ‘my_table’ VALUES (‘Ali Imran’, ‘[email protected]’)

Whenever you need to insert data in to table, start query with ‘INSERT INTO’, next isthe table name ‘my_table’ to insert data in. the last part of the insertion query is thenew values (encapsulated in brackets) to insert as new row, where ‘VALUES’ is akeyword of MySQL.Deletion:

DELETE FROM ‘my_table’ WHERE email=‘[email protected]

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 ‘[email protected]’ thendelete the row, this query will delete all the rows containing email ‘[email protected]’. If ‘WHERE’ clause is not implemented, all the rows will be deleted and tablewill be emptied.

Page 215: Swish Climax


Review on MySQL operators:

Note : The comparison operator ‘=’ and assignment operator ‘=’ both are same inSQL, as compare to SWiSHScript the comparison operator is ‘==’ and assignmentoperator is ‘=’.

Similarly another comparison operator ‘!=’ (not equal to) is used in SWiSHScriptwhereas in MySQL it is used as ‘<>’ as well as ‘!=’.

Logical ‘and’ or ‘&&’ in SWiSHScript is same as used ‘AND’ or ‘&&’ in MySQL.Logical ‘or’ or ‘||’ in SWiSHScript is same as used ‘OR’ or ‘||’ in MySQL.Logical ‘!’ (NOT) in SWiSHScript is same as used ‘!’ or ‘NOT’ in MySQL.

So combining more than one condition in MySQL query is done as:WHERE email=‘[email protected]’ OR username=‘Ali’


UPDATE ‘my_table’ SET email=‘[email protected]’, age=27 WHERE username=‘Ali’

Query for alteration/modification in row(s) of a MySQL table starts with keyword‘UPDATE’, next is table name ‘my_table’ to alter data of, then keyword ‘SET’ andfollowing alterations/assignments (as we are making two changes in specific rowsemail=‘[email protected]’ changing email, age=27 changing age [separated withcomma]), then the keyword ‘WHERE’ (implementation of ‘where’ clause) and lastpart is the conditions of ‘WHERE’ clause. After running this query the MySQL enginewill check all the rows where username is ‘Ali’ and change the email and age tospecified values. If ‘WHERE’ clause is not implemented, all the rows effected, and thecorresponding fields will be modified to specified data.

Table of MySQL:

A table of MySQL database is similar to the one created in Microsoft Access or theMicrosoft Excel Sheet, based on columns and rows. Where columns are called fieldsof a MySQL table. Each field of the MySQL table is specific for the data type it iscreated to hold. Where our requirements are 3 (three) data types, so, we will discussonly 3 (three).

Running the query from PHP?

Function ‘mysql_query’ (of PHP) is used to execute a query on MySQL engine. Itrequires only one argument of string type where you will pass the MySQL query. Thisfunction returns different types of values on each situation. If the query could not beexecuted either due to MySQL syntax error or any other error occurrence, thefunction will return false. If the query was executed successfully it returns true or theresource pointer (which will be discussed in upcoming topic of Fetching/RetrievingData from MySQL tables)


Page 216: Swish Climax


$result = mysql_query(“DELETE FROM ‘my_table’ WHERE age=27”);if(!$result) //same to if($result == false)

echo “Error occurred while executing query”;

Data types of the fields of a MySQL table:

As we already mentioned that, we have concern with only 3 (three) of the types, sowe go with those only.


This type is set for a field to contain text only data. Text may include any of thecharacters. A field defined to be of type ‘VARCHAR’ can contain maximum 255characters. You have to specify the maximum length of the filed you require.


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’ is the type defined for the MySQL tables’ fields to contain unspecified lengthof text data. This filed allow you to store text data of any length. The MySQL engineshrinks and grows the row size itself.

Creating new table in MySQL Database:

CREATE TABLE ‘my_table’ (username VARCHAR(20),age INT(3),bio BLOB


Bring above SQL code to minimum lines query string:

CREATE TABLE ‘my_table’ (username VARCHAR(20), age INT(3), bio BLOB)

To run a query that creates a table in currently selected MySQL Database, start itwith ‘CREATE TABLE’ then table name ‘my_table’, then starting bracket ‘(’ where youwill 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 ofnumeric type and can hold maximum 3 digits (which is maximum value 999). Lastfield is of type ‘BLOB’ which tells the type of field is capable of holding unlimitednumber of characters in (length not specified). At end close the bracket ‘)’. So that,to run this query we use:

mysql_query(“CREATE TABLE ‘my_table’ (username VARCHAR(20), age INT(3), bio BLOB)”);

Page 217: Swish Climax


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 lettersand numbers, etc.

Fetching/Retrieving Data from MySQL tables:

‘SELECT’ keyword is used to implement a query that fetches/reads data from aMySQL table.


SELECT username FROM ‘my_table’ WHERE age=27

A query to be used to fetch data from MySQL table starts with keyword ‘SELECT’,then the fields ‘username’ to fetch data from (to get data of multiple fields put morefield 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 rowswhere value of field ‘age’ is equal to 27 (twenty seven) .

If you wish all fields if the row as return use ‘*’ instead of specifying the field names,as:

SELECT * FROM ‘my_table’ WHERE age=27

If ‘WHERE’ clause is not implemented, the query will result in returning all rows withdata of only one field ‘username’.

To execute this query from PHP we use:$result = mysql_query(“SELECT * FROM ‘my_table’ WHERE age=27”);

If query was not successful and some error occurred the function will return false.Otherwise it will return a pointer to resource from which we can fetch rows one byone (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 itas parameter/argument and it returns an integer value (number of rows in theresource).


$result = mysql_query(“SELECT * FROM ‘my_table’ WHERE age=27”);$num = mysql_num_rows($result);if($num == 0)

echo “No data returned by the query”;

Where ‘$result’ is the variable used as resource pointer obtained from functionmysql_query after running the query

Now, if number of rows in the resource pointer was more than 0, we implement theelse block in our above code, and fetch the rows one by one using function

Page 218: Swish Climax


‘mysql_fetch_array’ which returns each fetched row as an array of PHP. This functionrequires only one argument as the resource pointer. as:

Note: structure of the ‘for’ loop in PHP is exactly same to the one used inSWiSHScript.

$result = mysql_query(“SELECT * FROM ‘my_table’ WHERE age=27”);$num = mysql_num_rows($result);if($num == 0)

echo “No data returned by the query”;else {

for($i=0; $i<$num; $i++) {$single_row = mysql_fetch_array($result);echo “$single_row[username] <br>”;



$result = mysql_query(“S… run the query using function‘mysql_query’, and save theresulting resource pointer in PHPvariable ‘$result’

$num = mysql_num_row… get number if rows from resourcepointer ‘$result’ and assign it tonew variable ‘$num’

if($num == 0) if returning number of rows areequal to ZERO, then,

echo “No data returned b… display the message ‘No datareturned by the query’

else { otherwise if the number of rowswas greater than ZERO, then,

for($i=0; $i<$num; $i++) { start ‘for’ loop to run ‘$num’ times$single_row = mysql_fetch_array($result); fetch a row out of the resource and

assign the resulting array tovariable ‘$single_row’

echo “$single_row[username] <br>”; display the data in index‘username’ of currently fetchedarray, where indexes of the arrayare same to the names of the fieldsin the table as well as the datatype is also same.

} closing block of the ‘for’ loop} closing block of the ‘else’

Which will result something like this on the browser screen:

Ali ImranCharly PixelsAli RomanEddie_k


Page 219: Swish Climax


‘DROP’ in MySQL means to erase a database of a table permanently.

Query Drop a database:

DROP DATABASE ‘my_database_name’

There is also a function ‘mysql_drop_db’ of PHP which may be used to dropDatabases, which returns true on success and false otherwise.


Query Drop a table:

DROP TABLE ‘my_table’

Creating Interactive Polling System using UI Collection Object

We will be creating a polling system using UI Collection Objects (UI Radio and UI PieCharts) where we will show the statistics using UI Pie Charts. This poll works withMySQL database accessed through PHP. There is an installer file 039_install.phpincluded with examples. What you have to do is, change some values in the file, as:

Making amendments (Installation):

mysql_connect("localhost","u","p") replace the “u” with your databaseusername, and “p” with the databasepassword

mysql_select_db("test") replace the “test” with your databasename you are allowed to work with

Now, upload the file and run it on the server, which will drop the table ‘sc_polls’ ifalready created, then recreates the table ‘sc_polls’. After you have run the page, itwill show you a message ‘SWiSH Climax MySQL Polling System successfullyinstalled.’, which indicates that it has been installed successfully. Now, open file039_poll.php and make same changed you made in installer file. Upload it in thedesired folder where you wish to run the polling system. Export the 039_poll.swi tohtml so that an html file as well as an SWF is created, upload both files to samefolder. And try running the polling system by typing the URL in your browser.

Explanation of the swi resource file created for poll:

Objets in the main timeline:

There are two static text, three dynamic text objects, three sprites, and one buttonobject. where

Page 220: Swish Climax


Dynamic Text Object ‘_msg’ (attached variable ‘msg’) is used to display differentmessages at each point.

Dynamic Text Object ‘_total’ (attached variable ‘total’) is used to display totalnumber of votes submitted so far.

Dynamic Text Object ‘_last’ (attached variable ‘last’) is used to display the dateof the last submitted vote.

Rest of the two static text objects are used as simple labels Sprite ‘bar’ contains the progress bar (simple animation sprite) Sprite ‘UIPiechart’ is the UI Pie Charts sprite used to show statistics as pie chart. Sprite ‘options’ contains further five sub-sprites (v1, v2, v3, v4, and v5) of UI

Radio, and a static text object as label. And a button object ‘submit’ used to submit data to the PHP script.

Now move onto script in the main timeline:

function setOption(opt) { create new function ‘setOption’ that will beaccepting one argument/parameter whichwill be then assigned to global variable‘option’

option=opt; assign the variable ‘option’ the value ofpassed argument as ‘opt’

} closing block of function ‘setOption’

onLoad() { ‘onLoad’ event handler of main timelineoptions._visible=false; set the ‘_visible’ property of the sprite

‘options’ to false, so that it becomeshidden at startup

submit._visible=false; set the ‘_visible’ property of the buttonobject ‘submit’ to false as well

option = 3; create new variable ‘option’ and assign itnew integer value 3 (three)

pid="swish_climax"; create a new variable ‘pid’ and assign itstring value ‘swish_climax’ which is to bepassed as poll id to the PHP script for thepoll identification, because there may bemore than one polls in the MySQL table.When we ran the installer file we inserteda new poll with ‘pid’ as ‘swish_climax’.

options.v1.onClicked = function() { implement handler of the event‘onClicked’ invoked by the UI Radio sprite‘v1’ which is sub-sprite if ‘options’, when itis invoked, then,

setOption(1); pass 1 (one) to function ‘setOption’ whichwill set the value of variable ‘option’ to 1(one)

}; closing block of the event handler‘onClicked’ of UI Radio ‘v1’

options.v2.onClicked = function() { implement the handlers for event‘onClicked’ the same way for other UIRadio sprites within sprite ‘options’

setOption(2); and set the value of the variable ‘options’};

Page 221: Swish Climax


options.v3.onClicked = function() {setOption(3); - do -};options.v4.onClicked = function() {setOption(4); - do -};options.v5.onClicked = function() {setOption(5); - do -};

response=0; create new variable ‘response’ and assignit integer value ZERO (0)

this.loadVariables("039_poll.php","POST"); load PHP script file 039_poll.php fromserver, and send it data through httpmethod ‘POST’ (to send datatransparently), so all the variables priorlydefined in current path are dispatched tothe script.

this.onEnterFrame = function() { implement event handler ‘onEnterFrame’within ‘onLoad’ event handler (blockstarts)

if(response==1) { if value of variable ‘response’ is equal to 1(which is returned back by the PHPscript), then,

if(cookie==1) { if value of variable ‘cookie’ (returned fromPHP script) is equal to 1 (one), then,prepare to initialize pie chart data to plot

labels = ['Not Bad', 'Good', create new variable ‘labels’ of type Array,'Excellent', 'Bad', and assign it 5 (five) elements of string'Worst']; type

colors = [0x00ff00,0xFF0000,0x000000, define a new variable ‘colors’ of type Array0x3366FF,0x993399]; and assign it five elements of type


//_values coming from server commentsvalues = _values.split(","); split the value variable ‘_values’ (returned

from PHP script) with delimiter ‘,’(comma) among a new array and assignthe resulting Array to new variable‘values’

UIPiechart.plot(values, labels, colors); plot the UI Pie Charts by passing itargument variables ‘values’, ‘labels’, and‘colors’

msg="Results"; change the value of variable ‘msg’ tostring ‘Results’, so that , it is displayed intext object ‘_msg’

} else { if value of cookie was not 1 (one), then,options._visible=true; set the sprite ‘options’ to visiblesubmit._visible=true; set the button ‘submit’ to visible, so that

user can select from UI Radio buttons andsubmit vote

Page 222: Swish Climax


} closing block of ‘if’ statement used tocheck value of variable ‘cookie’

bar._visible=false; set the sprite ‘bar’ invisibleresponse=0; set the value of variable response to ZEROdelete this.onEnterFrame; delete the event handler ‘onEnterFrame’

because the job has been done for now.} closing block of ‘if’ statement used to

check value of variable ‘response’}; closing block of event handler

‘onEnterFrame’} closing block of event handler ‘onLoad’

Understanding the functionality and Scenario:

On startup, we set the property ‘_visible’ of sprite ‘options’ and button ‘submit’ to‘false’ (to set them invisible). Why? Because our script will start working just after it,so that, we do not allow user to submit vote until our movie does not receive thevariable ‘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 itsvalue continuously, so it remains ZERO until it is not received from the script withvalue ‘1’. Why did we set the value of variable ‘option’ to 3 (three)? Because we setthe default selected the third UI Radio option. Then we loaded the PHP script usingfunction ‘loadVariables’ and sent it the variable ‘pid’ (where variable ‘option’ is alsosent, but it does not effect because we did not pass variable ‘a’ as querystring to theURL). Now if the variable ‘a’ I passes alongwith the loadVariables, the script assumesit is vote submission not just data retrieval.Now, in event handler ‘onEnterFrame’ we check the value of variable ‘response’, ifthe value of variable ‘response’ is 1 (one), it means the PHP script has respondedfully. Now check the value of variable ‘cookie’, if it is 1 (one) which means the cookiehas already been written in client computer, that indicates that the user has alreadysubmitted the vote, so directly display the statistics through UI Pie Charts,otherwise, if value of variable ‘cookie’ (received from PHP script) is ZERO it indicatesthe user has not submitted the vote yet, so, display him/her the sprite ‘options’ (UIRadio buttons) and button ‘submit’ by setting their ‘_visible’ property to ‘true’. Afterit process has been done set back the value of variable ‘response’ to ZERO anddelete 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:


that is ‘?a=x’

Note: Anything passed after the URL+ ? is called query string passed through httpmethod 'GET'


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

Page 223: Swish Climax


‘POST’. The PHP script checks for availability of the variable ‘a’, if it is available to thePHP script (as we have passed, so it will be available) the PHP script assumes thevote is submitted.

Short review on PHP script in file 039_poll.php:

$r=mysql_query("SELECT * FROM sc_polls WHERE pid='$pid'")or die("s:".mysql_error());

Run MySQL query that fetches the row containing our poll with poll id ‘pid’ comingfrom 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’ whichhalts the execution wherever called. It accepts on argument of string type as themessage to display and break execution.

$cookie_name = "swish_climax";$cookie_path = "/"; //do not change value of it$cookie_domain = ""; //use ".yourdomain.com" if not localhost$cookie_time = (3600*24)*7; //on week cookie, 3600 = 1 hour

set cookie information in 4 (four) variables.

if(!isset($a)) {

if variable ‘$a’ is not received from SWiSHScript.

if(!isset($_COOKIE[$cookie_name]) or $sum==0) {

check if cookie is not set in client browser or the number of total votes is ZERO, then

report ("total",$sum);

send variable ‘total’ to SWiSHScript

report ("last",$row['timer']==0?"":date("m-d-Y",$row['timer']));

send variable ‘last’ to SWiSHScript and its value the date of last vote if votes morethan ZERO or send empty string if no field timer is ZERO (which is by default ZEROwhen installed)

report ("cookie", 0);

send variable ‘cookie’ to SWiSHScript and its value ZERO

Page 224: Swish Climax


report ("response",1);

send variable ‘response’ to SWiSHScript with value ‘1’ (one), which indicates theSWiSHScript that process is complete and data ahs been received.

} else {otherwise, if cookie is set

$temp = Array();for($i=0; $i<count($values); $i++) {

$cval = intval($values[$i]);$temp []= $cval==0?1:$cval*10;

}report("_values",implode(",",$temp));report ("total",$sum);report ("last",date("m-d-Y",$row['timer']));report ("cookie", 1);report ("response",1);

process and calculate data and send to SWiSHScript through function ‘report’

if(isset($a)) {

now, if variable ‘$a’ is received from SWiSHScript, then

mysql_query("UPDATE sc_polls SET _values='$vals', lastip='$ip', timer=$tmWHERE pid='$pid'")

or die("e:".mysql_error());

update the existing poll and

setcookie($cookie_name,_ip(),$cookie_time,$cookie_path, $cookie_domain);

set the cookie in client computer

report ("cookie", 1);report("_values",implode(",",$temp));report ("last",date("m-d-Y",$row['timer']));report ("total",$sum);report ("response",1);

then response back to SWiSHScript.

function report($var,$val) { echo "&$var=$val&"; }

create new PHP function ‘report’ that is used to send variables back to SWiSHScript.It accepts two arguments two arguments 1st variable of SWiSHScript and 2nd value ofthe variable being sent to SWiSHScript.

function _ip() { return $_SERVER['REMOTE_ADDR']; }

Page 225: Swish Climax


create new PHP function ‘_ip’ which returns IP address of the client computerobtained from array $_SERVER and index REMOTE_ADDR which is automaticallyavailable in the PHP environment.

Online Resources / Help

There are many community forums for SWiSH 2 an SWiSHMax help. The forum weare currently running (is open for everyone) can be found on www.swish-db.com,and for customers (of this book) support visit www.swishclimax.com.

On swish-db.com we have a huge download center full of SWiSH 2, SWiSHMax, PHP,Flash MX, and other scripting and design resources.

Our newly established community can be found on www.scriptsector.com

Official site of SWiSHMax is www.swishzone.com, and their community forum forhelp and updates is, www.swishzone.com/forums.

Page 226: Swish Climax


Chapter 9 SWiSHMax integration withASP and MS-AccessNote: This chapter does not teach you the core ASP, But the integration of ASP with SWiSHMax, and

some useful methods which can give you goodstart for writing ASP + SWiSHMax Databasedriven applications.

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

Page 227: Swish Climax


What is Microsoft Access?

Access is a database creation/manipulation tool that comes alongwith the set of toolsin Microsoft Office, product of Microsoft Corporation. There are many versions of theMicrosoft Office available in the market. The one we have to choose is, the one whichwill be compatible with all the Office Software, so that the users do no need to worryabout the backward compatibility of the files you deliver to them. Similarly, the userof Operating system Linspire can also alter the files through Sun Microsystems’ StarOffice easily. So, we will use Access 97 (comes alongwith Microsoft Office 97) tomake our database alterable from within all version of Microsoft Office. If you do nothave 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, becauseit is written only for Access 97. You may find some tutorials or Demonstrations aboutcreating database and tables in specific version of your Microsoft Access, throughsearch engines (such as www.google.com)

Creating Database and Tables with Microsoft Access

Here are steps to create a database in Microsoft Access.Note: All the steps and screenshots are taken from Microsoft Access 97.

When you start Microsoft Access, a form Dialogue appears as shown below:

Page 228: Swish Climax


Select the Radio Button ‘Blank Database’ and click the button ‘OK’. After you haveclicked the button, another common dialogue appears, to save the database file, asshow here:

After entering desired name of the database file to save, click button ‘Create’ visiblein 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 iconunder the menus, as shown here:

It will display a dialogue of a bit different type, Select ‘Blank Database’ icon and clickbutton ‘OK’, as shown here:

Page 229: Swish Climax


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 tocreate new table. You simply select ‘design View’ from the list on right side and clickbutton ‘OK’, as shown here:

The last step is to create structure of the table, as shown below. A dialogue appearswith title ‘Table1 :Table’, that allows you to insert desired names of the fields in firstcolumn (on left) and type of the field in 2nd column (on right) where it allows you toselect the type of field through a sophisticated combo. See the screenshot:

Page 230: Swish Climax


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 areavailable under the editing table area as tabs ‘General’ and ‘Lookup’, as shownabove; you are recommended to use ‘General’ tab options not the options availablein tab ‘Lookup’.

Now it is time to save the created table in the database file we created. To do thissimply click the save icon available in the toolbar under the top menu, as shownhere:

Page 231: Swish Climax


Access will prompt you asking the new table name to write to database, you simplytype the desired table and click button ‘OK’, as shown here:

Furthermore, if another dialogue appears, simply click button ‘NO’, if you areunaware of Primary Key, as shown here:

This was the complete step by step procedure of creating new database and a newtable in Microsoft Access.

If you need to add more tables to the created database simply close currently opentable, 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’ andfollow the same procedure to create new table as we priorly defined. Screenshot ishere:

Now, when we are successful in creating a new database and table with MicrosoftAccess, let us see the integration of this database with ASP.

Page 232: Swish Climax


What is ASP?

Word ‘ASP’ stands for Active Server Pages. This technology was introduced byMicrosoft Corporation a couple of years ago, to provided an ease to user to createhis/her dynamic web pages using Visual Basic Language like syntax ‘VBScript’ orJava Language like syntax ‘JavaScript’. For writing ASP applications you may use anyof VBScript and JavaScript languages. I myself use VBScript to write Active ServerPages which is much easy and flexible for the developer as well as for the Beginnersor Moderate Level developers of Microsoft Visual Basic, to directly jump onto ASPwithout problems.

A Database created with Microsoft Access is accessible directly through ASP (ActiveServer Pages, the server-end script). Where all the standard SQL commands areapplicable over the Access database through ASP.

Code of an ASP application is enclosed in <% and %>, means script of active serverpage starts with <% and ends with %>. And ASP script files as usually saved withextension ‘.asp’. Since we will be using normal ASP not ASP .Net (the latest versionof ASP), we will save files with extension ‘.asp’, not ‘.aspx’ etc.

Adding comments in ASP code

Since we will be using VBScript in our ASP script, comments are styled the sameused in VBScript, QBasic and/or Visual Basic, as shown here:

<%‘I am comment text line‘I am comment text line 2

myVar = 10%>

Tracking variables obtained through GET and POST method in ASP

ASP has built-in objects interact with client application.

Object ‘Request’ (discussing POST Method)

This is the object available on server which provides the data alongwith variablenames sent from client application through http method POST. We can access eachindividual variable (coming from client application e.g. SWF), sent through httpmethods 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 secondline I used double quotes (“ and ”), this is just to make you sure that both of thequotes can be used.

Page 233: Swish Climax



userName = Request(‘Name’) get the value of variable ‘Name’ comingfrom client application (e.g. SWF) via httpmethod POST, and assign it to a newvariable ‘userName’. It is equivalent toPHP statement:$userName = $_POST[‘Name’];

userEmail = Request(“Email”) get the value of variable ‘Email’ comingfrom client application (e.g. SWF) via httpmethod POST, and assign it to a newvariable ‘userEmail’. It is equivalent toPHP statement:$userEmail = $_POST[“Email”];

Note: there is no semicolon at the end of VBScript statements.

You may also obtain the values of variables coming through http method POST, as:

userEmail = Request.Form(“Email”)

because, logically, the variables coming from POST method are always sent througha form.

Object ‘Request.QueryString’ (discussing GET Method)

What is Query String?

Simple definition: Query String is a string following to the URL + ? with variables andvalues.E.g. http://www.swishclimax.com/myscript.asp?Name=Ali&[email protected]

‘Name=Ali&[email protected]’ is the query string, where ‘Name’ and ‘Email’are the variables (sent through http method GET) assigned value using ‘=’ andassignments separated with ‘&’.

Example and explanation:

userName = Request.QueryString(‘Name’)equivalent to PHP statement: $userName = $_GET[‘Name’];

userEmail = Request.QueryString(“Email”)equivalent to PHP statement: $userEmail = $_GET[“Email”];

You already know that the server side scripts are called/loaded through SWiSHMaxfunction ‘loadVariables’ or the ‘loadVars’ object’s function ‘load’. Assume we have avariables ‘age’ already in SWiSHMax. Now if we pass the above mentioned URL tothis function as:

this.loadVariables(“http://www.abc.com/myscript.asp?Name=Ali&[email protected]”, “POST”);

Page 234: Swish Climax


we will receive the variable ‘age’ through POST, where ‘Name’ and ‘Email’ throughhttp method GET, as:


userAge = Request(“age”) $_POST[“age”];‘or //oruserAge = Request.Form(“age”) $_POST[“age”];‘and //anduserName = Request.QueryString(“Name”) $_GET[“Name”];userEmail = Request.QueryString(“Email”) $_GET[“Email”];

So far we have learnt to receive the variables (coming through http methods GETand POST) in our ASP script, question is:

How to send information back to client application (e.g. SWF)?

Answer is contained in next topic.

Sending back Response to SWiSHMax movie (Object ‘Response’)

Object ‘Response’ is used to send response back to client application, that might bean SWF (SWiSH or Flash generated), standard browser page. Where response maybe in plain text, standard html, XML, and/or any kind of data that is build up ofcharacters. Function ‘Write’ if object ‘Response’ is used for this purpose, which actsalmost same to ‘echo’ or ‘print’ the functions of PHP.


Response.Write(“&msg=Response from ASP”)orResponse.Write “&msg=Response from ASP” Note: brackets are not

necessary, in VBScript.

Is equivalent to PHP script as shown here:

echo “&msg=Response from PHP”;orprint “&msg=Response from PHP”;

where ‘msg’ is the variable of SWiSHScript.

Sample SWiSHMax application with ASP

Open 040.swi that is dummy of example 014.swi, and uses to load script file040.asp, then the 040.asp response back the data for SWiSHScript variable‘myVar2’ which is attached with a textbox in our SWiSHMax movie.

Page 235: Swish Climax


See the code of 040.asp:

Note:‘&’ is used in VBScript as concatenation operator similar to the one in PHP as ‘.’

<%'we have recieved variable myVar as ASP variable Request("myVar")'now we will send back the myVar2 containing data of my myVar we recieved.

myVar2 = "Hello " & Request("myVar") & " from ASP&"Response.Write myVar2‘or‘Response.Write(myVar2)


equivalent PHP script:

<?//we have recieved variable myVar as PHP variable $myVar//now send back the myVar2 containing data of my myVar we recieved.

$myVar2 = "Hello " . $myVar . " from PHP&";// or// $myVar2 = "Hello $myVar from PHP&";echo $myVar2;


Connecting ASP with MS-Access

Connecting MS-Access from within ASP is done through objects, but the procedure iseasier than in PHP. What you have to do is, create an object to establish connectionwith Microsoft Access file. Then run the standard SQL query and perform desiredDML operations. The interestion operation is the data retrieval, which is performedby a resource object that is created after connection has been established withengine.

Establishing connection to load MS-Access Database file:

Create connection object (use as it is):

Set connection = Server.CreateObject("ADODB.Connection")connection.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=abc.mdb"


Creating Record-Set pointer to fetch data from:

Now, when connection has been established with the specific Driver, let us movetowards create recordset object and run the desired query, as:

Set record = Server.CreateObject("ADODB.Recordset")record.Open ("SELECT * FROM myTable", connection)

Page 236: Swish Climax


or use variable created connection object ‘connection’, call its function ‘Execute’ andsave the resulting resource in new variable for ‘record’, as

Set record = Server.CreateObject("ADODB.Recordset")Set record = connection.Execute ("SELECT * FROM myTable")

Fetching the resulting rows from Record-Set pointer ‘record’:

After the query is ran and we are expecting some results in the variable ‘record’ usedas 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 arow. So that to fetch ‘age’ from current row we use record("age"), see detailedexample here:

Do While Not record.EOF Response.Write ( record("userName") & "-" & record("Email") ) record.MoveNextLoop


Do While start VBScript loop with keywords ‘Do While’

Not record.EOF while record not reaches to End Of File (EOF)

Response.Write ( send back response to client application, asrecord("userName") data of field ‘userName’ from current row& "-" concatenate ‘-’ with output& record("Email") ) concatenate data of field ‘Email’ from current row

record.MoveNext move the internal pointer of record-set to nextrow using function ‘MoveNext’ of record-setobject we created priorly

Loop closing block of loop ‘Do While’

Note: loop ‘Do While’ of VBScript acts as the loop ‘while’ in PHP.

Closing the connection:

After the job is done, and we have utilized/processed the data, we free up thevariable ‘record’ holding record-set information, and then close the establishedconnection, as:


Encoding special characters with VBScript:

I you remember, we already encoded special characters before sending back to ourSWiSHMax generated SWF. VBScript provides us a easy way to do that, throughfunction ‘URLEncode’ of object ‘Server’. See example:

Page 237: Swish Climax



myURL = “&swfurl=<b>http://www.swishlimax.com/script.asp?name=Ali Imran&[email protected]</b>&”enURL = Server.URLEncode(myURL)

Response.Write( enURL )

Where ‘swfurl’ is the variable in the client SWF movie.

So the final code becomes:


Set connection = Server.CreateObject("ADODB.Connection")connection.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=abc.mdb"


Set record = Server.CreateObject("ADODB.Recordset")record.Open ("SELECT * FROM myTable", connection)

Set record = Server.CreateObject("ADODB.Recordset")Set record = connection.Execute ("SELECT * FROM myTable")

Do While Not record.EOF Response.Write ( record("userName") & "-" & record("Email") ) record.MoveNextLoop