Welcome to Action(t)ad
 

This is the place for pure ActionScript 3.0 examples.

This page is the old plain version of the site, it has no flash content.

This page also serves as a catcher of 404 errors.
Also, the main version of the site will not allow itself to be put in an html frame,
the site will redirect you to this page if that happens.
Some search engines will show sites in a frame, so if that's how you got here
simply press the "close" or "exit frame" or similar button and the site will automatically go to the full flash enabled version.

However, if you would like to just use a plain version of the site, you can use this page.

Note: This page is no longer updated. The up to date plain version of the site is now located at:
www.actiontad.com/plain/


Main version of the site
XML Map


About the Author
A Brief History of ActionScript
 


ActionScript started as a set of commands for the flash player called 'actions'.
With the release of flash player version 5 (in 2000)
the term ActionScript was used to describe the programming language
that resulted from the addition of more 'actions' and a
object-oriented approach akin to JavaScript.

In 2003 -2004 ActionScript 2.0 was released alongside flash player version 7.
The code before 2.0 became known as ActionScript 1.0.
ActionScript 2.0 added support for classes and variable type declaration.

Before 2005 ActionScript and the flash player were updated by Macromedia.
In 2005 Adobe acquired Macromedia. With 2006 came ActionScript 3.0.
Version 3.0 is a more complete language.
It is based on the new ECMAScript edition 4 (JavaScript 4),
has an event model based on the Document Object Model level 3 specifications, and has support for regular expressions.

An Overview of ActionScript 3.0 Syntax
 


ActionScript 3.0 is similar to JavaScript, and should be easy to learn for those who know JavaScript.
For the most part, the synatx of AS3 is just like JavaScript.

ActionScript is case sensitive:
myvar
is not the same as:
Myvar
Arrays are declared the same way as in JavaScript:
var myarray:Array = new Array("one", "two", "three");
var myotherarray:Array = ["one", "two", "three"];

In fact, alot of the same general functions in JavaScript simply carry over:
JavaScript:
var backslash = new Array(String.fromCharCode(92)).join(""); // "\"
var myregx = new RegExp("[0-9]{2, }[a-z]{3, }", "i");

ActionScript 3.0: var backslash:String = new Array(String.fromCharCode(92)).join(""); // "\" var myregx:RegExp = new RegExp("[0-9]{2, }[a-z]{3, }", "i");

However in .as files, (as you can see above) all variable types must be declared
and, unlike JavaScript, the use of namespaces, classes and packages is also a focus.

In AS3 objects are the focus.
Objects can contain variables, shapes, sprites, functions, methods, classes or other objects.
Variables, functions, and classes are all objects.
All of the functions and methods above come from the Top Level package of AS3;
use of classes (Array, String, Math, Object..) in the Top Level does not require an import.
In order to utilize more functions and methods in the language,
other imported classes from packages are used.

Got all that? To get the general feel for AS3 syntax let's go over a basic "Hello World!" example.

A basic ActionScript 3.0 package
 


To use AS3 by itself, without a program like Adobe Flash CS3,
we must use what is known as a package.
Packages hold class defenitions. A basic AS3 package looks like this:

package
{
   public class ABlankSwf
   {
      public function ABlankSwf()
      {
           //when saved as a file called ablankswf.as
           //this will compile to a blank .swf called ablankswf.swf
           //the name of the class must match the name the .as file
           //the public function gives 'action' to the class of the same name  
           //public classes and functions will be accesable by the whole file 
           //the word public can be thought of as a namespace
 
           //just as in JavaScript, lines like this one are comments
      }
   }
}

To make the above example display "Hello World!" some code must be added.

  1. We must use the import command to include the Sprite and TextField classes.
    The import command can be thought of as importing different parts of the AS3 language.
    Only the parts that are used in your particular file need to be imported,
    this reduces compilation time and helps minimize errors.
    Imports go directly below the opening of the package.
    package
    {
      import flash.display.Sprite;
      import flash.text.TextField;
    ...
    
  2. The flash.display package is what allows us to work with display objects.
    A sprite is a display object. To initiate an instance of a sprite,
    we say that our public class ablankswf extends Sprite.
    public class ABlankSwf extends Sprite
    {
    ...
    
    This means that the code (variables, functions, objects...) within the class named ablankswf
    will now be able to reference code in the Sprite class.
    In other words, our swf file is now a sprite that can display objects.

  3. The ablankswf function will now house the code that will add objects to the display.
    The flash.text package allows us to work with text formats and text fields.
    Text fields are objects, text formats give style to text fields,
    therefore the TextFormat object can also be called a method.
    To create a new text field with the "Hello World!" text,
    in the public function ablankswf we replace the comments with the following code:
    var textSpot:TextField = new TextField();
    textSpot.text = "Hello World!";
    addChild(textSpot);
    
    We did not define a text format so the default text format of the flash player is used.

The complete code now looks like:
package
{
  import flash.display.Sprite;
  import flash.text.TextField;

   public class ABlankSwf extends Sprite
   {
      public function ABlankSwf()
      {
            var textSpot:TextField = new TextField();
            textSpot.text = "Hello World!";
            addChild(textSpot);
      }
   }
}


Let's go over the above code in more detail now:
  1. We define the package wich is the whole file in this case.
  2. We import the classes of code that we need.
    In this case we needed the Sprite class of the flash.display package,
    and the TextField class of the flash.text package.
    The Sprite class tells the flash player what a sprite is.
    The TextField class tells the flash player what a text field is.
    If we wanted to import the whole display package
    (which includes the MovieClip class amongst other objects)
    we type this:
    import flash.display.*;
    The asterisk signifies that we are importing all objects from the package.
    We can do the same for the text package.
    import flash.text.*;
    Note:
    A Sprite ( http://livedocs.adobe.com/flex/3/langref/flash/display/Sprite.html)
    in AS3 does not have a timeline.
    Sprites have just one frame, however the on enter frame event can still be invoked.

    A MovieClip ( http://livedocs.adobe.com/flex/3/langref/flash/display/MovieClip.html)
    has a timeline, however,
    I prefer to use the flash.utils.timer class to accomplish a multiple frame effect.
    (please see the animated "Hello World!" example: HelloWorldAnimationExample)

  3. Our main class is defined, in this case it extends the sprite class,
    which basically means our file will consist of one main sprite.
    We can add other sprites to the main sprite and we can even add timers which can serve as separate timelines,
    but in this case we just need the one main sprite.
  4. The public function holds the 'action' of the sprite.
    The 'action' that this sprite will do is display a text field.
    The variable TextSpot will be a text field,
    we have declared its type by using a colon and the word TextField.
    var TextSpot:TextField
    In .as files all new variables must be declared in this way.
    We could have used an asterisk instead so that TextSpot could be any type of object.
    var TextSpot:*
    We then say that TextSpot equals a new TextField(),
    this is what creates a text field named TextSpot.
    To give TextSpot some text we say that its text property equals the string "Hello World!"
    Finaly, we add TextSpot to the display by calling the addChild method of the Sprite class.

When the code is compiled this is the result:
HelloWorld! result swf image

Variables, Functions, and Event Listeners:
 


Just like most other languages, in AS3 there are variables that are global,
(accessable by every function in a package)
and variables that are not global (can only be accessed within their own function).

To define a global variable for the main class we declare it after the opening of the class,
and call the varaible private, meaning it will be accessable only in the class:
The word private basically signifies a namespace.
In AS3 you can create your own namespaces, but that is a more advanced topic.
private var myvariable:String = "Hello World!";
or just:
private var myvariable:*;

Variables declared within private functions can only be used within those functions.
To create a private function we declare it after the public funtion
and before the end of the class:
package
{
   import flash.display.Sprite;
   import flash.events.Event;

   public class MySwf extends Sprite
   {

        private var globalVariable:String = 
        "Im global and accessable by all functions in this class.";

        public function MySwf()
        {
           //this is how to add the onenterframe event to the main Sprite
           //now the function named thisfunction will continually happen

           stage.addEventListener(Event.ENTER_FRAME, thisFunction)
        }

        private function thisFunction(event:Event):void
        {

             
             //when making a private function
             //what the function is going to return must be declared
             //in this case this function will return nothing
             //so a colon and the word void is added 
             //after the closing parenthesis of the function
             //if the function was to return a string then we would put String instead 

             //functions can return just about any object

             //because this function will happen on the enterframe event
             //its arg must be the event
             //notice that the type of event must also be declared
             //in this case its just a standard Event
             //in the case of timers it would be a TimerEvent
             //we could have called the lower case "event" anything

             //a function called by this function would not require an arg

             //this function is only to be used by the myswf class
             //thats why we call it private
             
             //variables declared inside of functions are not global
             //the private declaration is not needed for these kind of variables
              
             var insideFunction:String = "Im inside the function and not global.";

        }

   }

}


As seen in the above code, we can add events to the main sprite.
We can also add events to sprites within the main sprite.
To add any events we must import from the event package:
import flash.events.*;
There are many different event classes
including the TimerEvent, MouseEvent, and just plain Event class.
We add events by calling the addEventListener() method.
In the below example, our main class will get the ENTER_FRAME event which is part of the Event class,
a child Sprite will get the CLICK event which is part of the MouseEvent class,
and a Timer will get the TIMER_COMPLETE event which is part of the TimerEvent class:
package
{

  import flash.display.Sprite;
  import flash.display.Graphics;
  import flash.text.TextField;
  import flash.text.TextFieldAutoSize;
  import flash.utils.Timer;
  import flash.events.Event;
  import flash.events.MouseEvent;
  import flash.events.TimerEvent;
   

   public class ThreeEvents extends Sprite
   {

    private var tellEvent:TextField = new TextField();

      public function ThreeEvents()
      {

	//the autoSize property of text fields lets the text field automatically
	//adjust to the length of the text it contains

	tellEvent.autoSize = TextFieldAutoSize.LEFT;
	addChild(tellEvent);

	//theenterframefunc is the name of the function that will happen on enter frame  
	//this swf will have only one frame, nonetheless,
	//theenterframefunc will happen continually

	stage.addEventListener(Event.ENTER_FRAME, theEnterFrameFunction);

	var babySprite:Sprite = new Sprite();
	//the visualization section has information on graphics
	babySprite.graphics.beginFill(0xFF0000, 1.0);
	babySprite.graphics.drawCircle(100, 100, 25);
	babySprite.graphics.endFill();

	//mouseclickedfunc will happen when babysprite is clicked
	babySprite.addEventListener(MouseEvent.CLICK, mouseClickedFunction);

	addChild(babySprite);
	//the visualization section has more about timers
	var aTimer:Timer = new Timer(5000, 1);

	//timercompletefunc will happen when the timer is complete
	aTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteFunction);

	//starting the timer
	aTimer.start();

      }

      private function theEnterFrameFunction(eventone:Event):void
      {

	//this function is happening on enter frame

	//to ensure that it only appends text to tellevent once
	//we check tellevents text for an index of what is to be added

	//to have the text forever appended remove the if statement

	//this function should happen first

	if (tellEvent.text.indexOf("enter frame event")==-1)
	{tellEvent.appendText("enter frame event");}

      }

      private function mouseClickedFunction(eventtwo:MouseEvent):void
      {

	//when the red circle named babysprite is clicked, "mouse click event"
	//will be added to the text field named tellevent

	tellEvent.appendText("mouse click event");

      }

      private function timerCompleteFunction(eventthree:TimerEvent):void
      {

	//when the timer is complete the string "timer complete event"
	//will get added to tellevents text

	tellEvent.appendText("timer complete event");

      }

   }

}


When compiled, if you click on the circle before five seconds, then wait a few seconds,
this is what it would look like:
ActionScript Events result image

The ActionScriptVisualizationConcepts section has more on sprites, the display class and animation.
The ActionScriptFiles section is all about how to compile .as files into .swf files and the software resources needed.

This book is perfect for the ActionScript 3.0 beginner:
Learning ActionScript 3.0: A Beginner's Guide

To get deep into the ActionScript 3.0 language there is no better online resource than:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3

Simple Ping Pong with AS3
 


The Code:      object types/classes  events  properties, methods, declarative words  functions/operational methods


Overview:
This ping pong game is simple and straigthfoward.
There are other commands in Actionscript 3.0 that help us do some of the math
that is done in the code below, however,
to give a more clear feel for the logic, this example spells out the math.

We begin by declaring our package and importing the needed classes. The [SWF...] part tells the compiler the frameRate, width, and height of the swf it will make.
In this casg the background color is determined by the wrapper the swf file is in. Now the main class is defined.
Before we define the swf files main function we declare all but one of our variables.
In this example only the draglock variable is not global. The pongstart function gives shape to our sprites,
adds events to the paddle sprites, starts the compfocus timer that will
act as the computers brain, and adds all sprites to the stage. The changeOfErrorRatio function changes the error ratio of the computer paddle.
The higher the error ratio, the more stupid the computer will be.
The error ratio gets greater as the velocity of the ball gets greater, in other words,
the computer has a harder time keeping up with the ball as the ball gets faster.
This function is happening on its own timer (compFocus) every 100 milliseconds. The movementGovern function is the main opperational function of this file.
It is happening on enter frame of the main timeline.
Because movementGovern is always happening,
the if thens and statements within are more like declarations:
a. The balls x and y position are equal to the direction values
multiplied by velocity then divided by 50.
b. If the balls x or y positions become greater than the set x and y ranges,
which include both paddles and the square bounderies,
then the balls direction should change to its opposite and velocity should increase.
c. If' the balls x and y are greator than any range or hit any boundary, play the ding sound.
d. If the balls y position is past the computer paddle and not touching the computer paddle,
then give the player a point, and the same for the player paddle, give the computer a point.
e. When velocity is greater than zero subtract velocity by one.
f. If velocity becomes 501 bring velocity to 480.
g. When the ball is in range, the x position of the computer paddle is the x position of the ball plus the error ratio diveded by two,
minus half the width of the computer paddle minus the error ratio diveded by eight.
The updatescore function is used within the movegov function to update the score. The paddle grab function is the event that happens on mouse down of the player paddle.
In this function if the velocity is zero it is changed to 300, initializing ball movement. The paddlerelease function happens when the mouse is released over the player paddle.

To compile this file you will need to create your own ding sound mp3 file and
change the embed folder (../exampimages) to the folder where your mp3 is.
Or you can take out the embed code, including the private var theding,
and take out the phrase theding.play(); from the code.

package { import flash.display.Sprite; import flash.display.Graphics; import flash.events.MouseEvent; import flash.events.Event; import flash.events.TimerEvent; import flash.geom.Rectangle; import flash.text.TextField; import flash.utils.Timer; import flash.media.Sound; /* a (t)a.d as3 tutorial copyright 2008 (t)a.d */ [SWF(frameRate = '20', width = '580', height = '400')] public class PongGame extends Sprite { private var dirX:Number = 2; private var dirY:Number = 2; private var velocity:Number = 0; private var theBall:Sprite; private var basicBounds:Rectangle = new Rectangle(25, 25, 530, 350); private var showBounds:Sprite; private var compScore:Number = 0; private var userScore:Number = 0; private var playerPaddle:Sprite; private var compPaddle:Sprite; private var showScore:TextField; private var errorRatio:Number = Math.random()*5; private var compFocus:Timer; [Embed(source="../exampimages/poing2.mp3")] private var Dinger:Class; private var theDing:Sound = new Dinger(); public function PongGame() { compFocus = new Timer(100, 0); compFocus.addEventListener(TimerEvent.TIMER, changeOfErrorRatio); showBounds = new Sprite(); showBounds.graphics.lineStyle(3, 0xFF0000); showBounds.graphics.drawRect(25, 25, 530, 350); addChild(showBounds); showScore = new TextField(); showScore.text = "Computer: "+ compScore + "\n" + "You: " + userScore; showScore.x = 35; showScore.y = 35; addChild(showScore); theBall = new Sprite(); theBall.graphics.lineStyle(1, 0x000000); theBall.graphics.beginFill(0xFF0000); theBall.graphics.drawCircle(0, 0, 15); theBall.graphics.endFill(); theBall.x = 580/2 - theBall.width/2; theBall.y = 400/2 - theBall.height/2; addChild(theBall); playerPaddle = new Sprite(); playerPaddle.graphics.lineStyle(1, 0x000000); playerPaddle.graphics.beginFill(0xC0C0C0); playerPaddle.graphics.drawRect(0, 0, 100, 17); playerPaddle.x = 30; playerPaddle.y = 360; playerPaddle.buttonMode = true; playerPaddle.addEventListener(MouseEvent.MOUSE_DOWN, paddleGrabHandler); playerPaddle.addEventListener(MouseEvent.MOUSE_UP, paddleReleaseHandler); addChild(playerPaddle); compPaddle = new Sprite(); compPaddle.graphics.lineStyle(1, 0x000000); compPaddle.graphics.beginFill(0xFE0000); compPaddle.graphics.drawRect(0, 0, 100, 17); compPaddle.x = 30; compPaddle.y = 22; addChild(compPaddle); stage.addEventListener(Event.ENTER_FRAME, movementGovern); } private function changeOfErrorRatio(event:TimerEvent):void { errorRatio = Math.random()*127 + velocity/5; } private function movementGovern(event:Event):void { theBall.x += dirX*velocity/50; theBall.y += dirY*velocity/50; if (theBall.x > 530) {dirX = -2;velocity += 5;theDing.play();} if (theBall.x < 50) {dirX = 2;velocity += 5;theDing.play();} if (theBall.y > 350 && !theBall.hitTestObject(playerPaddle)) {dirY = -2;velocity += 5;compScore += 1;updateScore(compScore,userScore);theDing.play();} if (theBall.y < 45 && !theBall.hitTestObject(compPaddle)) {dirY = 2;velocity += 5;userScore += 1;updateScore(compScore, userScore);theDing.play();} if (theBall.hitTestObject(playerPaddle)) {dirY = -2; velocity += 40;theDing.play();} if (velocity>0) {velocity -= 1;} else {velocity = 0;} if (velocity>500) {velocity = 450;} if (theBall.x <= 460 && theBall.x >=25) {compPaddle.x = theBall.x + errorRatio/2 - compPaddle.width/2-errorRatio/8;} if (theBall.hitTestObject(compPaddle)) {dirY = 2; velocity += 45;theDing.play();} } private function updateScore(computer:Number, user:Number):void { showScore.text = "Computer: "+ computer + "\n" + "You: " + user; } private function paddleGrabHandler(event:MouseEvent):void { if (velocity == 0) {velocity = 300;} else {velocity = velocity;} if (compFocus.running == false) {compFocus.start();} var dragLock:Rectangle = new Rectangle(20, 360, 435, 0); event.target.startDrag(false, dragLock); } private function paddleReleaseHandler(event:MouseEvent):void { if (velocity !=0) {velocity = 0;} event.target.stopDrag(); } } }
Basic Form with AS3
 


The Code:      types  events  properties, methods, declarative words  functions/operational methods

package
{

  import flash.display.Sprite;
  import flash.display.Graphics;
  import flash.net.URLRequest;
  import flash.net.navigateToURL;
  import flash.text.TextField;
  import flash.text.TextFormat;
  import flash.text.TextFormatAlign;
  import flash.text.TextFieldType;
  import flash.events.MouseEvent;


  public class basicForm extends Sprite 
  {

    private var firstWordField:TextField = new TextField();
    private var lastWordField:TextField = new TextField();
    private var theTXTFormat:TextFormat = new TextFormat();



      public function basicForm()
      {

     	theTXTFormat.font = "Arial";
     	theTXTFormat.color = 0x000000;
     	theTXTFormat.size = 12;
     	theTXTFormat.align = TextFormatAlign.LEFT;

     	var fwLabelTXT:TextField = new TextField();
     	fwLabelTXT.selectable = false;
     	fwLabelTXT.text = "First Word:";
     	fwLabelTXT.x = 10;
     	fwLabelTXT.y = 20;
     	addChild(fwLabelTXT);

     	firstWordField.type = TextFieldType.INPUT; 
     	firstWordField.defaultTextFormat = theTXTFormat;
     	firstWordField.maxChars = 20;
     	firstWordField.border = true;
     	firstWordField.restrict = "a-z";
     	firstWordField.height = 20;
     	firstWordField.width = 120;
     	firstWordField.background = true;
     	firstWordField.backgroundColor = 0xFFFFFF;
     	firstWordField.wordWrap = true;
     	firstWordField.multiline = false;
     	firstWordField.text = " ";
     	firstWordField.x = fwLabelTXT.x;
     	firstWordField.y = fwLabelTXT.y + 15;
     	addChild(firstWordField);

     	var swLabelTXT:TextField = new TextField();
     	swLabelTXT.selectable = false;
     	swLabelTXT.text = "Second Word:";
     	swLabelTXT.x = firstWordField.x;
     	swLabelTXT.y = firstWordField.y + 25;
     	addChild(swLabelTXT);

     	lastWordField.type = TextFieldType.INPUT; 
     	lastWordField.defaultTextFormat = theTXTFormat;
     	lastWordField.maxChars = 20;
     	lastWordField.border = true;
     	lastWordField.height = 20;
     	lastWordField.width = 120;
     	lastWordField.restrict = "a-z";
     	lastWordField.wordWrap = true;
     	lastWordField.multiline = false;
     	lastWordField.background = true;
     	lastWordField.backgroundColor = 0xFFFFFF;
     	lastWordField.text = " ";
     	lastWordField.x = swLabelTXT.x;
     	lastWordField.y = swLabelTXT.y + 15;
     	addChild(lastWordField);


     	var submitButton:Sprite = new Sprite();
     	submitButton.graphics.beginFill(0x000000, .2);
     	submitButton.graphics.drawRect(0, 0, 40, 20);
     	submitButton.buttonMode = true;
     	var subTXT:TextField = new TextField();
     	subTXT.text = "Submit";
     	submitButton.x = lastWordField.x;
     	submitButton.y = lastWordField.y + 25;
     	subTXT.x = submitButton.x;subTXT.y=submitButton.y;
     	submitButton.addEventListener(MouseEvent.CLICK, submitFormHandler);
     	addChild(subTXT);
     	addChild(submitButton);

      }

      private function submitFormHandler(event:MouseEvent):void 
      {

         var theRequest:URLRequest = 
         new URLRequest("basicresult.html?fw="+firstWordField.text+"&lw="+lastWordField.text);
         navigateToURL(theRequest, "_blank");

      }





  }

}


Hello World! on a Timer
 


The Code:      object types/classes  events  properties, methods, declarative words  functions/operational methods
package
{
    
    
    /* a tad tutorial
    copyright 2008 (t)a.d



    start package
    import all of display text and events
    and import flash utils timer */ 
    
    import flash.display.Sprite;
    import flash.display.Graphics;       
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFormat;
    import flash.text.TextFormatAlign;
    import flash.text.TextFieldType;
    
    import flash.events.TimerEvent;
    import flash.events.MouseEvent;
    import flash.utils.Timer;
    
    /* start the actual swf file
    this extention is the sprite that takes up the stage */

    
    public class TimerTimeline extends Sprite 
    {
        
        /* assign variable types */
        
        private var theTimeline:Timer;
        private var theShowTyping:TextField;
        private var theShowTypeFormat:TextFormat;
        
        
        public function TimerTimeline()
        {
            
            /* create a text field format */ 
            theShowTypeFormat = new TextFormat();
            theShowTypeFormat.font = "Arial";
            theShowTypeFormat.color = 0x000000;
            theShowTypeFormat.size = 16;
            theShowTypeFormat.align = TextFormatAlign.CENTER;
            
            /* create a text field with the above format */

            theShowTyping = new TextField();
            theShowTyping.type = TextFieldType.DYNAMIC; 
            theShowTyping.defaultTextFormat = theShowTypeFormat;
            theShowTyping.autoSize = TextFieldAutoSize.LEFT;
            theShowTyping.text = "H";
            
            /* add the text field to the stage
            will be in top left corner
            can reposition with theShowTyping.x and theShowTyping.y */       
            this.addChild(theShowTyping);
            
            /* theTimeline can be thought of as 11 frames at 1 frame per 500 milliseconds (half a second)
            it does not repeat
            
            really its a timer that goes once every 500 milliseconds 11 times then stops
            if you want it to go forever put 0 instead of 11
            it can be controlled with .start() .stop() 
            however, when it reaches 11 (or whatever num your using other than 0) it will not start again
            until you use the .reset() command
            
            it only has the currentCount property (used below) 
            if the repeatCount (the 11 spot) is not 0
            the spot with the milliseconds is called the delay */

            
            
            theTimeline = new Timer(500, 11);
            
            
            /* now an event listener is added to this timer
            which itself is an event
            it gets some special events called TimerEvents
            namely TIMER and TIMER_COMPLETE
            timer fires on every repeatCount interval
            and timer complete fires when and only when the repeatCount is finished 
            (therefore not initialy 0)
            note that the last timer event will happen and then the timer complete event */
            
            theTimeline.addEventListener(TimerEvent.TIMER, doTheAnimation);
            theTimeline.start();
            
            /* the replay button */

            var resetButton:Sprite = new Sprite();
            resetButton.graphics.lineStyle(1, 0x000000);
            resetButton.graphics.beginFill(0x000000, .2);
            resetButton.graphics.drawRect(0, 0, 65, 20);
            /* replay text */

            var resetButtonTXT:TextField = new TextField();
            resetButtonTXT.type = TextFieldType.DYNAMIC;
            resetButtonTXT.selectable = false; 
            resetButtonTXT.defaultTextFormat = theShowTypeFormat;
            resetButtonTXT.autoSize = TextFieldAutoSize.LEFT;
            resetButtonTXT.text = "replay";
            /* position of the button and text */  
            resetButton.y = 25;
            resetButtonTXT.y = resetButton.height/2 + resetButtonTXT.height/2;
            resetButtonTXT.x = resetButton.width/2 - resetButtonTXT.width/2;
            /* give the sprite a pointer cursor */ 
            resetButton.buttonMode = true;
            /* add the replaytimer func as the onclick */

            resetButton.addEventListener(MouseEvent.CLICK, replayTimerHandler);
            
            /* add text then button to the display */
            addChild(resetButtonTXT);
            addChild(resetButton);
            
        }
        
        
        /* this is the func called on each repeatCount interval
        so its called eleven times
        once every 500 milliseconds */

        
        private function doTheAnimation(event:TimerEvent):void 
        {
            
            /* event.target is theTimeline timer
            currentCount is how we get the current interval
            we have placed it in a var named currentFrameOn
            we use appendText to add each letter per interval */       
            
            var currentFrameOn:int = event.target.currentCount;
            switch (currentFrameOn)
            {
                
            case 1:
            theShowTyping.appendText("e");
            break;
            
            case 2:
            theShowTyping.appendText("l");
            break;
            
            case 3:
            theShowTyping.appendText("l");
            break;
            
            case 4:
            theShowTyping.appendText("o");
            break;
            
            case 5:
            theShowTyping.appendText(" ");
            break;
            
            case 6:
            theShowTyping.appendText("W");
            break;
            
            case 7:
            theShowTyping.appendText("o");
            break;
            
            case 8:
            theShowTyping.appendText("r");
            break;
            
            case 9:
            theShowTyping.appendText("l");
            break;
            
            case 10:
            theShowTyping.appendText("d");
            break;
            
            case 11:
            theShowTyping.appendText("!");
            break;
            
            }
            
        }
        
        /* the function below resets the timer
        after clearing theShowTyping */

         
        private function replayTimerHandler(event:MouseEvent):void 
        {
            
            theTimeline.stop();theShowTyping.text = "H";
            theTimeline.reset();
            theTimeline.start();
        }
        
        
        
    }
    
}

ActionScript 3.0 Visualization Concepts
 


ActionScript 3.0 programming begins by having a good mental picture of what your code will do once compiled.
In this section we'll go over how to control the visual aspects of the swf file and Sprites, and how to add animation.

Width Height and Background Color of a .swf file
 


With AS3 there are a few different ways to change the size and background color of a swf.
  1. Use the [SWF...] declaration after the opening of a package.
    Within such a declaration the frame rate, width, height and background color
    of the swf file to be complied can be declared as follows:
     [SWF(frameRate = '20', backgroundColor = '0xc8c8c8', width = '433')]
    
  2. Embed a background image and add it as the first (bottom) child in the display:
    package
    {
       import flash.display.Sprite;
       import flash.display.DisplayObject;
      
       public class EmbededBackground extends Sprite
       {
       
           [Embed(source="../imagefolder/mybackground.jpg")]
           private var TheBackground:Class;
        
           public function EmbededBackground()
           {
                  var swfBackground:DisplayObject = new TheBackground();
                  addChild(swfBackground);
    
                  //any child added afterwards will be on top of the background
                  //swfbackground is on level 0 which is the bottom
                  //this is different than in AS2
           }
    
       }
    
    }
    
  3. Use the wrapper to determin background color, width and height:
     
     <object type="application/x-shockwave-flash"
     data="myswf.swf" width="480px" height="400px" >
     <param name="bgcolor" value="#6495ED" />
    ...
    
    The background color that the wrapper defines will replace
    whatever background color defined inside the swf file.
    If the width and height in the wrapper are not the same as the swf file, the swf file will be scaled.
    The SWFWrappers section has more on this topic.


The Graphics Class
 

The Graphics class is part of the flash.display package.
It allows us to add graphics such as colors and shapes, to display objects such as sprites.
Drawing a circle:
package
{
  import flash.display.Sprite;
  import flash.display.Graphics;

  public class ACircle extends Sprite
  {
     public function ACircle()
     {
        //define a new sprite
        var aSprite:Sprite = new Sprite();

        //the beginFill method initiates a color and alpha value for the sprite
        aSprite.graphics.beginFill(0xFFFFFF, 1.0);

        //the drawCircle method draws a circle with the specified x, y, and radius values
        aSprite.graphics.drawCircle(0, 0, 25);

        //the endFill method is used to apply fills
        aSprite.graphics.endFill();

        //finaly we add the sprite to the display
        addChild(aSprite);
     }
  }
}
You can find out more about the graphics class here:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/Graphics.html

Animation with the Timer Class
 


To make full use of the Timer class we also need the TimerEvent class.
We can import both as follows:
import flash.utils.Timer;
import flash.events.TimerEvent;

With the Timer class we can add timers to our swf file.
When events are added, timers act much like timelines to allow for animation.
A basic timer that waits 3 seconds, displays "Hello "
then waits another 3 seconds then displays "World!":
package
{
  import flash.display.Sprite;
  import flash.utils.Timer;
  import flash.events.TimerEvent;
  import flash.text.TextField;

  public class ATimer extends Sprite
  {

      //this text field has been defined globaly so that all functions may reference it
      private var showText:TextField = new TextField();

      public function ATimer()
      {
        showText.text="";
        addChild(showText);

        //initalize a new timer that will run twice at three second intervals
        //if we want the timer to run forever we would replace the two with a zero
        var myTimer:Timer = new Timer(3000, 2);

        //this event (showhello) will be triggered at every interval of the timer
        myTimer.addEventListener(TimerEvent.TIMER, showHello);

        //this event (showworld) will be triggered on the last interval of the timer
        myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, showWorld);
  
        //starting the timer
        myTimer.start();        
      }
   
      private function showHello(event:TimerEvent):void
      {
         //we use an if statement because this event will fire on every interval
         //without the if,  two "Hello " strings would be added, one on each interval
         //the currentCount property gets the current interval of the timer

         if (event.target.currentCount < 2)
         {showText.appendText("Hello ");}
      }

      private function showWorld(event:TimerEvent):void
      {
         //this will happen when the last interval is complete
         showText.appendText("World!");
      }

  }

}

There is a "Hello World!" animation example that uses a timer to 'type' each letter.
HelloWorldAnimationExample
ActionScriptFiles is about how to compile .as files into .swf files.

Using ActionScriptFiles
 


ActionScript files have the extension .as.
To make a .as file simply open note pad or your favorite plain text editor and write your packaged ActionScript code
then save the file with the ending .as instead of .txt. (eg. "myfile.as")

the mxmlc compiler
Mxmlc.exe is a command line tool that can be used to compile .as files into .swf files. (shown above)
This file comes with Adobe Flex Builder and is also part of the Adobe Flex SDK.
The Flex SDK is offered freely, Flex Builder is an Adobe program for creating rich Flex applications.
(you can search from this trial page for a link to the SDK) http://www.adobe.com/go/flex_trial/

Technically the mxmlc.exe compiler is for making Flex applications
that utilize the mxml language or import from the mx package,
using either is considerd the basis of a Flex application.
(Swfs can also be made from a combination of .mxml and .as files
or one .mxml file that is much like xml with AS3 in its "<mx:Script>" tags)
However, in general terms Flex applications are .swf files.

The reason I stray from the mxml language and the mx package is because swf files
compiled with mx controls are normally larger in size and are best suited as desktop or network applications.
Simply using the mx.controls.Button class costs 100kb or more.
literaly this:
package
{
  import mx.controls.Button;

  public class BareButton extends Button
  {

  }

}
would be about 113kb.
(note that the ship shooter example is only 104kb)

Flex applications are just that..applications.
For the most part they all have the same general look,
and best of all come with a pre-loader already.
But doing things with just pure ActionScript 3.0 is smaller
and therefore more suited for web pages.

Using the mxmlc Compiler
 

The mxmlc.exe file (above) does not work by itself, it is linked with different files in the SDK.
Furthuremore, to use the mxmlc compiler you will also need to have Java installed on your computer.
Most people already have Java installed on their computers, however if you do not you can download the latest version from java.sun.com

note: If you are a Windows Vista user and you've downloaded version 6 of Java you may need to copy the
msvcr71.dll file (located in java/jre6/bin/new_plugin) to your windows/system32 folder.

In general do not move the mxmlc.exe file, make shortcuts to it and then files compiled should get saved in the shortcuts' folder,
if not, they will be in the bin folder of where you unzipped the SDK.

If you've unzipped the SDK it will be located in c:\(your folder choice)\bin\
If you have Flex Builder look for the bin folder amongst the installation folder.

To compile swfs in Windows all you have to do is drop a .as on mxmlc.exe (or a shortcut to it).
If the .as is written correctly a .swf file will get created.
If there are errors it will show them to you and not compile,
however from a drag and drop you will not have enough time to see the errors.

In Windows you can use mxmlc.exe from the command prompt to see the errors.
A basic execution would be "start", "run..", (type) cmd.exe (hit enter) then:
(type) cd\   (hit eneter)
(type) cd (folder you unzipped to)\bin  (hit enter)
(type) mxmlc.exe "c:\(the .as file location)\myswf.as"  (hit enter)
On a Mac you will also need to execute mxmlc.exe.

For complete information about the compiler look here:
http://www.adobe.com/go/flex_documentation for the build_deploy_flex3.pdf download.

Using ActionScript files with Flash CS4
 


In Flash CS4 .as files can be used to hold Document Classes.
To define a Document Class you simply write the name of the .as file (minus .as) as the Document Class name of your project.
Your .fla file and .as file must both be in the same location when testing and exporting.
Your .as file must be written as packaged code.

Instead of using any [Embed...] declarations you would use symbols in the library.
You would also declare stage width, height, frame rate and background color in Flash instead of using [SWF...] in your package.

ActionScript Programming Efficency and Best Practices
 

A key to good programming is getting the most out of
the smallest/most efficient amount of code.

The ActionScript language contains many tools and techniques that help minimize
the amount of code needed in a project.

As you look through the examples on this site,
it is important to note that they where not built with efficency in mind, but rather "understandability"

The animated "Hello World!" example uses a long switch statement to break each interval
of the Timer into separate visible parts.

This helps to express the point of the example; the Timer class can be used much like a timeline with frames.
However, a more efficient way to think about that code would be to
also take into account a situation where the words "Hello World!" would need/or want to be changed:

...

private var myWord:String = "Hello World!"; 

...
theTimeline = new Timer(500, myWord.length);

...

private function doTheAnimation(event:TimerEvent):void
{

theShowTyping.appendText(myWord.substring(Number(event.target.currentCount), 
Number(Number(event.target.currentCount)+1)));

}
...
Using the above code is more efficient because the phrase "Hello World!" would be easier for anyone to change.
It also takes fewer lines of code than the "understandable" way.

As you get deeper into programming with ActionScript 3.0,
efficiency is one of the things you will need be mindful of.

To Upper Case or not
 

camelCase is the term for the industry standard technique of Capatalizing the start of new words in a variable:
(for example:  myText   mouseDownHandler)
Using camelCase helps in phrase recognition.
But it can also get confusing keeping up with what is supposed to be capatalized,
especially when the programming language is using camelCase as well.

For my own personal applications I tend to give things with more importance camelCase and the lesser variables of my own lowercase.

without camelCase:
package
{

 import flash.display.Sprite;

 public class myclass extends Sprite
 {

   public function myclass()
   {

     var myvar:Sprite = new Sprite();
     addChild(myvar);

   }

 }

}
with camelCase:
package
{

 import flash.display.Sprite;

 public class myClass extends Sprite
 {

   public function myClass()
   {

     var myVar:Sprite = new Sprite();
     addChild(myVar);

   }

 }

}


These kind of details are really just a matter of opinion.
However, most people prefer camelCase simply because it is the standard.

Placing your swf in an html wrapper
 


The wrapper is what a .swf file is embedded in.
A .swf file can even stand on its own as a .exe file.
The majority of the time .swf files are used in websites or web based networks and therefore in html.
This section gives a more modern approach to embedding swf files, one that validates as strict mark-up,
by using the object tag only, and JavaScript to output the swf.
We'll also go over a simple method to ensure communication with the swf object can happen.

Emebedding for Internet Explorer:
<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'
codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#
version=9,0,0,0' id='myswfid' width='500px' height='500px'>
<param name='movie' value='myswf.swf' />
<param name='bgcolor' value='#FFFFFF' />
<param name='SWLIVECONNECT' value='true' />
<param name='quality' value='high' />

<param name='menu' value='true' />
<param name='allowscriptaccess' value='SameDomain' />
</object>

Embedding in all other browsers:
<object type='application/x-shockwave-flash' 
data='myswf.swf'
width='500px' height='500px' id='myswfid'>
<param name='bgcolor' value='#FFFFFF' />
<param name='SWLIVECONNECT' value='true' />

<param name='quality' value='high' />
<param name='menu' value='true' />
<param name='stanby' value='Launching Flash..' />
<param name='allowscriptaccess' value='SameDomain' />
</object>

You can place the above code directly in your html, but I recommend using JavaScript
to dynamically place the swf object in the page like so:
function putflash()
{
var browsers=navigator.appName;
if (browsers.indexOf('Internet Explorer')!=-1 || browsers.indexOf('MSIE')!=-1)
{
document.getElementById('divforflash').innerHTML=
"<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'"+
" codebase='http://download.macromedia.com/"+
"pub/shockwave/cabs/flash/swflash.cab#"+
"version=9,0,0,0' id='tadner' width='500px' height='500px'>\n"+
"<param name='movie' value='myswf.swf' />\n"+
"<param name='bgcolor' value='#FFFFFF' />\n"+
"<param name='SWLIVECONNECT' value='true' />\n"+
"<param name='quality' value='high' />\n"+
"<param name='menu' value='false' />\n"+
"<param name='allowscriptaccess' value='SameDomain' />\n"+
"</object>\n";
}
else
{
document.getElementById('divforflash').innerHTML=
"<object type='application/x-shockwave-flash'\n"+
"data='myswf.swf'\n"+
"width='500px' height='500px' id='myswfid'>\n"+
"<param name='bgcolor' value='#FFFFFF' />\n"+
"<param name='SWLIVECONNECT' value='true' />\n"+
"<param name='quality' value='high' />\n"+
"<param name='menu' value='false' />\n"+
"<param name='stanby' value='Launching Flash..' />\n"+
"<param name='allowscriptaccess' value='SameDomain' />\n"+
"</object>\n";
}

}


Communication with the swf via JavaScript:
 

In .as files you can set up what is known as a callback in the wrapper.
You do this by first importing the flash.external package and then calling
ExternalInterface.addCallback("jsfunction", as3function)
( http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/package-detail.html)
"jsfunction" is the actual name of the function that JavaScript can call to invoke the AS3 function.
Below is a nifty little function I've made to ensure that JavaScript will be able to call the callback function.
The trouble was in the fact that using embed inside of an object tag meant that only the object
would have an id because embed can only take the name attribute.
Also some browsers will not be able to reference the flash simply by its id.
This function aims at accounting for all those possibilities:
function callascallback(flashid)
{

  try
  {
  var flashcontent=window.document.getElementById(flashid);
  }
  catch(e)
  {
    try
    {
     var flashcontent=window.document.flashid;
    }
    catch(e)
    {
       var movie=flashid;
       
       if (navigator.appName.indexOf("Microsoft")!=-1 || navigator.appName.indexOf("MSIE")!=-1)
       { 
          if (window.document[movie])
          {var flashcontent=window.document[movie];}
          else
          {var flashcontent=window[movie];};
       }else{
         if (document.embeds[movie])
         {var flashcontent=document.embeds[movie];}
         else
         {var flashcontent=document[movie];};
       }
    }
  }
  try
  {
  //the actual call to the callback function
  flashcontent.jsfunction();
  }
  catch(e)
  {
   //this catch is for if all failed
    var cantcommunicate="yes";
  }
}

Sponsored Links
 

Flashden.net


           Graphicriver.net        Themeforest.net

Goodies from Actiontad
 


All actiontad components are controlled via XML and come with source ActionScript files, source vector files, XML files with instructions, and compilation instructions.

All actiontad components can be compiled with either Adobe CS3(4), Flex Builder, or by using the Adobe Flex 3 SDK.

All actiontad goodies have only three restrictions:
1. Please do not sell the codes.
2. Any copyright information must remain intact.
3. Please do not distribute them (in code form or otherwise)
    as templates or tutorials.

Other than that you may use them as you wish.
 


 


ActionScript colorer

The fist version of my ActionScript text colorer for the browser.
(a work in progress)

Colors your ActionScript 3.0 code as you type.
A simple JavaScript script, CSS script, and HTML page do the work.

It's made to run in FireFox.

The FireFox version

 


Image Gallery in a Picture Frame

A simple image gallery whose thumbnails scroll horizontaly inside a picture frame.
There are 3 frame styles to choose from,
plain, shadeblots, and threeshade.
The frame width and height can vary in size.
It's very easy to modify, everything is controlled via XML.



The XML used to control the gallery :

<?xml version="1.0" encoding="UTF-8"?>
<galleryoptions>


   
   <numofpictures>7</numofpictures>


   <imagelocation>same</imagelocation>

   <picextensions>.jpg</picextensions>

   <thumbnaillast>thum</thumbnaillast>

   <thepictures>
   imageone,imagetwo,imagethree,imagefour,imagefive,
   imagesix,imageseven,end
   </thepictures>

   <picdescriptions>
   image one,image two,image four,image five,
   image six,image seven,end
   </picdescriptions>

   <saystyle>ffffff</saystyle>

   <thumbanidirec>left</thumbanidirec>

   <thescrollspeed>18</thescrollspeed>

   <backgroundcolor>black</backgroundcolor>

   <framewh>900,500</framewh>

   <framestyle>plain</framestyle>

   <framecolorrgb>178,126,0</framecolorrgb>

   <fullscreenbutton>no</fullscreenbutton>

   <ermessage>There was an error while loading.</ermessage>




</galleryoptions>




Download this component :

pframeimggallery.zip

 
Simple BlackJack with AS3
 


The Code:     object types/classes  events  properties, methods, and declaritive words  functions/operational methods

Overview:
This black jack game is just a standard deal hit and split game with no betting.
(A bet system can be easily added into the calculateWinner function.)
The main functions are the hit and calculateWinner functions.
The basic logic is to always calculate for player hands that are as close to 21 as possible.
The dealers hand should always aim for 17.
An array of aces is created so that aces used
(changed from one to eleven or vise versa) can be kept track of.

To compile this game you will need to create your own images and sound, and
change the name of the embed folder (../exampimages) to the folder where your images are.
package { import flash.display.Sprite; import flash.display.Graphics; import flash.display.DisplayObject; import flash.events.TimerEvent; import flash.events.Event; import flash.events.MouseEvent; import flash.text.TextField; import flash.text.TextFormat; import flash.text.TextFieldAutoSize; import flash.text.TextFormatAlign; import flash.utils.Timer; import flash.geom.Rectangle; import flash.media.Sound; /* a (t)a.d tutorial copyright 2009 (t)a.d */ [SWF(frameRate = '20', backgroundColor = '0xc8c8c8', width = '433', height = '400')] public class tadsBlackJack extends Sprite { private var playerTXTField:TextField; private var dealerTXTField:TextField; private var TXTFormat:TextFormat; private var playerCardOne:String = "0"; private var playerCardTwo:String = "0"; private var dealerCardOne:String = "0"; private var dealerCardTwo:String = "0"; private var playerHand:Number = 0; private var dealerHand:Number = 0; private var acesUsed:Number = 0; private var splitCardOne:String = "0"; private var splitCardTwo:String = "0"; private var splitCardThree:String = "0"; private var splitCardFour:String = "0"; private var splitCardFive:String = "0"; private var splitCardSix:String = "0"; private var splitHandOne:Number = 0; private var splitHandTwo:Number = 0; private var splitHandThree:Number = 0; private var hitButton:Sprite; private var firstSplitButton:Sprite; private var secondSplitButton:Sprite; private var hitSplitOneButton:Sprite; private var hitSplitTwoButton:Sprite; private var hitSplitThreeButton:Sprite; private var dealTXT:TextField; private var hitTXT:TextField; private var cardSpotOne:Sprite; private var cardSpotTwo:Sprite; private var cardSpotThree:Sprite; private var dealerSpot:Sprite; private var dealerGo:Sprite; private var dealerGoTXT:TextField; private var winField:TextField; [Embed(source="../exampimages/aimg.jpg")] private var AceImage:Class; [Embed(source="../exampimages/img2.jpg")] private var TwoImage:Class; [Embed(source="../exampimages/img3.jpg")] private var ThreeImage:Class; [Embed(source="../exampimages/img4.jpg")] private var FourImage:Class; [Embed(source="../exampimages/img5.jpg")] private var FiveImage:Class; [Embed(source="../exampimages/img6.jpg")] private var SixImage:Class; [Embed(source="../exampimages/img7.jpg")] private var SevenImage:Class; [Embed(source="../exampimages/img8.jpg")] private var EightImage:Class; [Embed(source="../exampimages/img9.jpg")] private var NineImage:Class; [Embed(source="../exampimages/img10.jpg")] private var TenImage:Class; [Embed(source="../exampimages/cardback.png")] private var CardBackImage:Class; [Embed(source="../exampimages/bjback.jpg")] private var GameBack:Class; private var theBackground:DisplayObject = new GameBack(); [Embed(source="../exampimages/playerwins.mp3")] private var WinVoice:Class; private var winSound:Sound = new WinVoice(); public function tadsBlackJack() { addChild(theBackground); TXTFormat = new TextFormat(); TXTFormat.font = "Arial"; TXTFormat.color = 0x000000; TXTFormat.size = 10; TXTFormat.align = TextFormatAlign.LEFT; winField = makeTXTField(winField, " "); /* The playerTXTField and dealerTXTField text fields are used as the brain of the game. The data of each hand is placed as text in these text fields and based on the numbers and phrases held in each one, winning, losing, split needs and draws can be calculated and remebered. Notice that they are never added to the display and yet still exist and can be manipulated. */ playerTXTField = new TextField(); playerTXTField.defaultTextFormat = TXTFormat; playerTXTField.autoSize = TextFieldAutoSize.LEFT; playerTXTField.height = 20; playerTXTField.selectable = false; playerTXTField.text = "Player cards: "+ playerCardOne + " " + playerCardTwo + " your hand totals: " + playerHand; playerTXTField.x = 50; playerTXTField.y = 50; dealerTXTField = new TextField(); dealerTXTField.defaultTextFormat = TXTFormat; dealerTXTField.autoSize = TextFieldAutoSize.LEFT; dealerTXTField.height = 20; dealerTXTField.selectable = false; dealerTXTField.text = "Dealer cards: "+ dealerCardOne + " " + dealerCardTwo + " dealer hand totals: " + dealerHand; dealerTXTField.x = 50; dealerTXTField.y = playerTXTField.y - 27; /* card spots */ cardSpotOne = new Sprite(); cardSpotOne.x = 20; cardSpotOne.y = 400/2 - 40; addChild(cardSpotOne); cardSpotTwo = new Sprite(); cardSpotTwo.x = cardSpotOne.x + 125 + 5 + 5; cardSpotTwo.y = 400/2 - 40; addChild(cardSpotTwo); cardSpotThree = new Sprite(); cardSpotThree.x = cardSpotTwo.x + 125 + 5 + 5; cardSpotThree.y = 400/2 - 40; addChild(cardSpotThree); dealerSpot = new Sprite(); dealerSpot.x = 5; dealerSpot.y = 5; addChild(dealerSpot); /* buttons */ var dealButton:Sprite = new Sprite(); dealButton.graphics.lineStyle(1, 0x000000); dealButton.graphics.beginFill(0x7FFF00); dealTXT = makeTXTField(dealTXT, "Deal"); dealButton.graphics.drawRect(0, 0, dealTXT.width, dealTXT.height); dealButton.addChild(dealTXT); dealButton.addEventListener(MouseEvent.CLICK, deal); dealButton.x = 20;dealButton.y = 330; addChild(dealButton); /* hit button */ hitButton = new Sprite(); var hitButtonGraphics:Sprite = new Sprite(); hitButtonGraphics.graphics.lineStyle(1, 0x000000); hitButtonGraphics.graphics.beginFill(0x0000FF); hitTXT = makeTXTField(hitTXT, "Hit"); hitButtonGraphics.graphics.drawRect(0, 0, hitTXT.width, hitTXT.height); hitButton.addEventListener(MouseEvent.CLICK, hit); hitButtonGraphics.addChild(hitTXT); hitButton.addChild(hitButtonGraphics); hitButton.x = dealButton.x + 55; hitButton.y = dealButton.y; addChild(hitButton); /* split button */ firstSplitButton = new Sprite(); firstSplitButton.graphics.lineStyle(1, 0x000000); firstSplitButton.graphics.beginFill(0xC0C0C0); var splitTXT:TextField = makeTXTField(splitTXT, "Split"); firstSplitButton.graphics.drawRect(0, 0, splitTXT.width, splitTXT.height); firstSplitButton.addEventListener(MouseEvent.CLICK, hit); firstSplitButton.x = hitButton.x + 65; firstSplitButton.y = hitButton.y;firstSplitButton.alpha = 0.5; splitTXT.x = firstSplitButton.x;splitTXT.y = firstSplitButton.y; addChild(splitTXT); addChild(firstSplitButton); /* split again button */ secondSplitButton = new Sprite(); secondSplitButton.graphics.lineStyle(1, 0x000000); secondSplitButton.graphics.beginFill(0xFFD700); var splitAgainTXT:TextField = makeTXTField(splitAgainTXT, "Split again"); secondSplitButton.graphics.drawRect(0, 0, splitAgainTXT.width, splitAgainTXT.height); secondSplitButton.addEventListener(MouseEvent.CLICK, hit); secondSplitButton.x = firstSplitButton.x + 120; secondSplitButton.y = firstSplitButton.y;splitAgainTXT.x = secondSplitButton.x;splitAgainTXT.y=secondSplitButton.y; secondSplitButton.alpha = 0.5; addChild(splitAgainTXT); addChild(secondSplitButton); /* hit first hand after split button */ hitSplitOneButton = new Sprite(); hitSplitOneButton.graphics.lineStyle(1, 0x000000); hitSplitOneButton.graphics.beginFill(0x1E90FF); var hitFirstHandTXT:TextField = makeTXTField(hitFirstHandTXT, "Hit first hand"); hitSplitOneButton.graphics.drawRect(0, 0, hitFirstHandTXT.width, hitFirstHandTXT.height); hitSplitOneButton.addEventListener(MouseEvent.CLICK, hit); hitSplitOneButton.x = firstSplitButton.x;hitSplitOneButton.alpha = 0.5; hitSplitOneButton.y = firstSplitButton.y + hitSplitOneButton.height + 3; hitFirstHandTXT.x = hitSplitOneButton.x;hitFirstHandTXT.y = hitSplitOneButton.y; addChild(hitFirstHandTXT); addChild(hitSplitOneButton); /* hit second hand after split button */ hitSplitTwoButton = new Sprite(); hitSplitTwoButton.graphics.lineStyle(1, 0x000000); hitSplitTwoButton.graphics.beginFill(0x1E90FF); var hitSecondHandTXT:TextField = makeTXTField(hitSecondHandTXT, "Hit second hand"); hitSplitTwoButton.graphics.drawRect(0, 0, hitSecondHandTXT.width, hitSecondHandTXT.height); hitSplitTwoButton.addEventListener(MouseEvent.CLICK, hit); hitSplitTwoButton.x = hitSplitOneButton.x; hitSplitTwoButton.y = hitSplitOneButton.y + hitSplitTwoButton.height + 3; hitSecondHandTXT.x = hitSplitTwoButton.x;hitSecondHandTXT.y = hitSplitTwoButton.y; hitSplitTwoButton.alpha = 0.5; addChild(hitSecondHandTXT); addChild(hitSplitTwoButton); /* hit third hand after second split button */ hitSplitThreeButton = new Sprite(); hitSplitThreeButton.graphics.lineStyle(1, 0x000000); hitSplitThreeButton.graphics.beginFill(0x1E90FF); var hitThirdHandTXT:TextField = makeTXTField(hitThirdHandTXT, "Hit third hand"); hitSplitThreeButton.graphics.drawRect(0, 0, hitThirdHandTXT.width, hitThirdHandTXT.height); hitSplitThreeButton.addEventListener(MouseEvent.CLICK, hit); hitSplitThreeButton.x = secondSplitButton.x; hitSplitThreeButton.y = secondSplitButton.y + hitSplitThreeButton.height + 3; hitThirdHandTXT.x = hitSplitThreeButton.x;hitThirdHandTXT.y = hitSplitThreeButton.y; hitSplitThreeButton.alpha = 0.5; addChild(hitThirdHandTXT); addChild(hitSplitThreeButton); /* done button end hand calculate dealers hand and who wins button */ dealerGo = new Sprite(); dealerGo.graphics.lineStyle(1, 0x000000); dealerGo.graphics.beginFill(0xFC0000); dealerGoTXT = makeTXTField(dealerGoTXT, "Done"); dealerGo.graphics.drawRect(0, 0, dealerGoTXT.width, dealerGoTXT.height); dealerGo.addEventListener(MouseEvent.CLICK, dealerBeginHandler); dealerGo.x = dealButton.x; dealerGo.y = dealButton.y + 45;dealerGoTXT.x = dealerGo.x;dealerGoTXT.y = dealerGo.y; dealerGo.alpha = 0.5; addChild(dealerGoTXT); addChild(dealerGo); } private function calculateWinner():void { if (!stage.contains(winField)) { winField.x = secondSplitButton.x + 30;winField.y = secondSplitButton.y+42; if (dealerHand > playerHand && dealerHand <= 21 && playerHand < 21 && splitHandOne == 0 && splitHandTwo == 0 && splitHandThree == 0) {winField.appendText("dealer wins the hand");} if (playerHand > dealerHand && playerHand <=21 && dealerHand < 21 && splitHandOne == 0 && splitHandTwo == 0 && splitHandThree == 0) {winField.appendText("player wins the hand");winSound.play();} if (playerHand == dealerHand && dealerHand <=21 && playerHand <=21 && splitHandOne == 0 && splitHandTwo == 0 && splitHandThree == 0) {winField.appendText("the hand pushes");} if (playerHand > 21 && splitHandOne == 0 && splitHandTwo == 0 && splitHandThree == 0) {winField.appendText("player busts");} if (playerHand <= 21 && splitHandOne == 0 && splitHandTwo == 0 && splitHandThree == 0 && dealerHand > 21) {winField.appendText("dealer busts");winSound.play();} if (splitHandOne != 0 && splitHandOne <= 21 && splitHandOne > dealerHand && dealerHand < 21) {winField.appendText("first hand wins");} if (splitHandOne != 0 && splitHandOne < 21 && splitHandOne < dealerHand && dealerHand <= 21) {winField.appendText("first hand looses");} if (splitHandOne != 0 && splitHandOne > 21) {winField.appendText("first hand busts");} if (splitHandOne != 0 && splitHandOne <= 21 && dealerHand > 21) {winField.appendText("dealer busts first hand wins");} if (splitHandOne != 0 && splitHandOne <= 21 && splitHandOne == dealerHand && dealerHand <= 21) {winField.appendText("first hand pushes");} if (splitHandTwo != 0 && splitHandTwo <= 21 && splitHandTwo > dealerHand && dealerHand < 21) {winField.appendText("\nsecond hand wins");} if (splitHandTwo != 0 && splitHandTwo < 21 && splitHandTwo < dealerHand && dealerHand <= 21) {winField.appendText("\nsecond hand looses");} if (splitHandTwo != 0 && splitHandTwo > 21) {winField.appendText("\nsecond hand busts");} if (splitHandTwo != 0 && splitHandTwo <= 21 && dealerHand > 21) {winField.appendText("\ndealer busts second hand wins");} if (splitHandTwo != 0 && splitHandTwo <= 21 && splitHandTwo == dealerHand && dealerHand <= 21) {winField.appendText("\nsecond hand pushes");} if (splitHandThree != 0 && splitHandThree <= 21 && splitHandThree > dealerHand && dealerHand < 21) {winField.appendText("\nthird hand wins");} if (splitHandThree != 0 && splitHandThree < 21 && splitHandThree < dealerHand && dealerHand <= 21) {winField.appendText("\nthird hand looses");} if (splitHandThree != 0 && splitHandThree > 21) {winField.appendText("\nthird hand busts");} if (splitHandThree != 0 && splitHandThree <= 21 && dealerHand > 21) {winField.appendText("\ndealer busts third hand wins");} if (splitHandThree != 0 && splitHandThree <= 21 && splitHandThree == dealerHand && dealerHand <= 21) {winField.appendText("\nthird hand pushes");} stage.addChild(winField); } } private function hitThisHand(handtohit:Number, apossibs:Array, hitwith:String):Number { var newcard:String = hitwith; var asofar:String = apossibs.join(""); if (asofar.indexOf("A")==-1) { if (newcard == "A") { if (handtohit + 11 > 21) {handtohit += 1;acesUsed += 1;} else {handtohit += 11;} } else {handtohit += int(newcard);} } else { var howmanyar:Array = asofar.match("A"); var numofas:Number = howmanyar.length; if (newcard != "A") { if (handtohit + int(newcard) > 21 && acesUsed < numofas) {handtohit = handtohit - 10 + int(newcard);acesUsed += 1;} else { if (handtohit + 10 + int(newcard) <=21 && acesUsed < numofas) {handtohit = handtohit + 10 + int(newcard);acesUsed += 1;} else {handtohit = handtohit + int(newcard);} } } if (newcard == "A") { if (handtohit + 1 > 21 && acesUsed < numofas) {handtohit = handtohit - 10 + 1;acesUsed += 1;return(handtohit);} if (handtohit + 1 > 21 && acesUsed > numofas) {handtohit = handtohit + 1;} if (handtohit + 11 >21 && handtohit + 1 <= 21) {handtohit = handtohit +1;} if (handtohit + 11 <= 21) {handtohit = handtohit + 11;} } } return(handtohit); } private function splitHands(firstcard:String, secondcard:String):void { if (firstcard == "A" && secondcard == "A") {acesUsed -= 1;} splitCardOne = firstcard; splitCardTwo = giveCard(); splitHandOne = calculateTwoCardHand(splitCardOne, splitCardTwo); splitCardThree = secondcard; splitCardFour = giveCard(); splitHandTwo = calculateTwoCardHand(splitCardThree, splitCardFour); showSplit(firstcard, splitCardTwo, secondcard, splitCardFour); playerTXTField.appendText("\nsplit and got cards: "+splitCardTwo+" "+splitCardFour+""); playerTXTField.appendText("\nthe new&nbsp;hands are: "+splitHandOne+" "+splitHandTwo+""); } private function splitHandsAgain(firstcard:String, secondcard:String, whichspot:String):void { if (firstcard == "A" && secondcard == "A") {acesUsed -= 1;} var theonesplitre:Number = 0; splitCardFive = giveCard(); splitCardSix = giveCard(); if (whichspot == "one") {splitHandOne = calculateTwoCardHand(splitCardOne, splitCardFive);theonesplitre = splitHandOne; splitHandThree = calculateTwoCardHand(splitCardTwo, splitCardSix); showSplitThree(splitCardOne, splitCardFive, splitCardTwo, splitCardSix);} if (whichspot == "two") {splitHandTwo = calculateTwoCardHand(splitCardThree, splitCardFive);theonesplitre = splitHandTwo; splitHandThree = calculateTwoCardHand(splitCardFour, splitCardSix); showSplitTwo(splitCardThree, splitCardFive, splitCardFour, splitCardSix);} playerTXTField.appendText("\nsplit again and got cards: "+splitCardFive+" "+splitCardSix+""); playerTXTField.appendText("\nthe resplit hand is now: "+theonesplitre+""); playerTXTField.appendText("\nthe new&nbsp;hand is now: "+splitHandThree+""); } private function hit(event:MouseEvent):void { /* whichhit can be more than one type of object */ var whichhit:* = event.target; if (whichhit == firstSplitButton && playerCardOne == playerCardTwo &&
playerTXTField.text.indexOf('new&nbsp; hands')==-1 && playerTXTField.text.indexOf('hit for')==-1) {splitHands(playerCardOne, playerCardTwo);return(void);} if (whichhit == secondSplitButton && splitCardTwo == splitCardOne &&
playerTXTField.text.indexOf('resplit hand')==-1 && splitCardThree!= "0" && splitCardFour!= "0" &&
playerTXTField.text.indexOf('after hit')==-1 && splitCardOne != "0" || whichhit == secondSplitButton && splitCardThree == splitCardFour &&
playerTXTField.text.indexOf('resplit hand')==-1 && splitCardThree!= "0" && splitCardFour!= "0" &&
playerTXTField.text.indexOf('after hit')==-1 && splitCardOne != "0") { if (splitCardTwo == splitCardOne) {splitHandsAgain(splitCardOne, splitCardTwo, "one");}else{splitHandsAgain(splitCardThree, splitCardFour, "two");} return(void); } if (whichhit == hitSplitOneButton && splitHandOne!=0 && playerTXTField.text.indexOf('first hand after')==-1 && playerTXTField.text.indexOf('split')!=-1 && splitHandOne < 21) { var afhcard:String = giveCard();var possibas:Array = new Array(); if (playerTXTField.text.indexOf('resplit')!=-1) {possibas = [splitCardTwo, splitCardFive];} else {possibas = [playerCardOne, splitCardTwo];} splitHandOne=hitThisHand(splitHandOne, possibas, afhcard); addHit(afhcard); playerTXTField.appendText("\nhit and got card: "+afhcard+""); playerTXTField.appendText("\nfirst hand after hit: "+ splitHandOne+""); return(void); } if (whichhit == hitSplitTwoButton && splitHandTwo!=0 && playerTXTField.text.indexOf('second hand after')==-1 && playerTXTField.text.indexOf('split')!=-1 && splitHandTwo < 21) { var ashcard:String = giveCard(); splitHandTwo=hitThisHand(splitHandTwo, [playerCardTwo, splitCardFour], ashcard); addHitTwo(ashcard); playerTXTField.appendText("\nhit and got card: "+" "+" "+" "+ashcard+""); playerTXTField.appendText("\nsecond hand after hit: "+ splitHandTwo+""); return(void); } if (whichhit == hitSplitThreeButton && splitHandThree!=0 && playerTXTField.text.indexOf('last hand')==-1 && playerTXTField.text.indexOf('resplit')!=-1 && splitHandThree < 21) { var athhcard:String = giveCard(); splitHandThree=hitThisHand(splitHandThree, [splitCardOne, splitCardSix], athhcard); addHitThree(athhcard); playerTXTField.appendText("\nhit and got card: "+" "+" "+" "+athhcard+""); playerTXTField.appendText("\nlast hand is now: "+ splitHandThree+""); return(void); } if (whichhit == hitButton && playerTXTField.text.indexOf('first hand')==-1 || whichhit == hitTXT &&
playerTXTField.text.indexOf('first hand')==-1 && playerHand < 21 && !stage.contains(winField)) { var newcard:String = giveCard(); addHit(newcard); if (playerTXTField.text.indexOf("A")==-1) { if (newcard == "A") { if (playerHand + 11 > 21) {playerHand += 1;acesUsed += 1;} else {playerHand += 11;} } else { playerHand += int(newcard); } } else { var howmanyar:Array = playerTXTField.text.match("A"); var numofas:Number = howmanyar.length; if (newcard != "A") { if (playerHand + int(newcard) > 21 && acesUsed < numofas) {playerHand = playerHand - 10 + int(newcard);acesUsed += 1;} else { if (playerHand + 10 + int(newcard) <=21 && acesUsed < numofas) {playerHand = playerHand + 10 + int(newcard);acesUsed += 1;} else {playerHand = playerHand + int(newcard);} } } if (newcard == "A") { if (playerHand + 1 > 21 && acesUsed < numofas) {playerHand = playerHand - 10 + 1;acesUsed += 1; playerTXTField.appendText("\nhit for: "+newcard+" your hand is now: "+playerHand+""); return(void);} if (playerHand + 1 > 21 && acesUsed > numofas) {playerHand = playerHand + 1;} if (playerHand + 11 >21 && playerHand + 1 <= 21) {playerHand = playerHand +1;} if (playerHand + 11 <= 21) {playerHand = playerHand + 11;} } } playerTXTField.appendText("\nhit for: "+newcard+" your hand is now: "+playerHand+""); } } private function dealerBeginHandler(event:MouseEvent):void { /* now the aces used value is for the dealer so we reset it accordingly */ if (dealerCardOne == "A" && dealerCardTwo == "A") {acesUsed = 1;}else {acesUsed = 0;} dealerSpot.removeChildAt(0); if (dealerCardOne == "A") {dealerSpot.addChildAt(new AceImage(), 0);} if (dealerCardOne == "2") {dealerSpot.addChildAt(new TwoImage(), 0);} if (dealerCardOne == "3") {dealerSpot.addChildAt(new ThreeImage(), 0);} if (dealerCardOne == "4") {dealerSpot.addChildAt(new FourImage(), 0);} if (dealerCardOne == "5") {dealerSpot.addChildAt(new FiveImage(), 0);} if (dealerCardOne == "6") {dealerSpot.addChildAt(new SixImage(), 0);} if (dealerCardOne == "7") {dealerSpot.addChildAt(new SevenImage(), 0);} if (dealerCardOne == "8") {dealerSpot.addChildAt(new EightImage(), 0);} if (dealerCardOne == "9") {dealerSpot.addChildAt(new NineImage(), 0);} if (dealerCardOne == "10") {dealerSpot.addChildAt(new TenImage(), 0);} dealerSpot.getChildAt(0).x = 0; dealerSpot.getChildAt(0).y = 0; dealerSpot.getChildAt(1).x = dealerSpot.getChildAt(0).x + 105; dealerSpot.getChildAt(1).y = dealerSpot.getChildAt(0).y; if (dealerSpot.scaleX == 1.0) {dealerSpot.scaleX /= 1.80;dealerSpot.scaleY /= 1.80;} var givedealer:String; var dealercards:Array = [dealerCardOne, dealerCardTwo]; if (dealerHand < 17) { while (dealerHand < 17) { givedealer = giveCard(); dealerHand=hitThisHand(dealerHand, dealercards, givedealer); dealercards = dealercards.concat(givedealer); addDealerHit(givedealer); if (dealerHand >= 17) {calculateWinner();break;} } } else {calculateWinner();} } private function initializeDealerHand(carderone:String, cardertwo:String):void { dealerSpot.addChild(new CardBackImage()); if (cardertwo == "A") {dealerSpot.addChild(new AceImage());} if (cardertwo == "2") {dealerSpot.addChild(new TwoImage());} if (cardertwo == "3") {dealerSpot.addChild(new ThreeImage());} if (cardertwo == "4") {dealerSpot.addChild(new FourImage());} if (cardertwo == "5") {dealerSpot.addChild(new FiveImage());} if (cardertwo == "6") {dealerSpot.addChild(new SixImage());} if (cardertwo == "7") {dealerSpot.addChild(new SevenImage());} if (cardertwo == "8") {dealerSpot.addChild(new EightImage());} if (cardertwo == "9") {dealerSpot.addChild(new NineImage());} if (cardertwo == "10") {dealerSpot.addChild(new TenImage());} dealerSpot.getChildAt(0).x = 0; dealerSpot.getChildAt(0).y = 0; dealerSpot.getChildAt(1).x = dealerSpot.getChildAt(0).x + 105; dealerSpot.getChildAt(1).y = dealerSpot.getChildAt(0).y; if (dealerSpot.scaleX == 1.0) {dealerSpot.scaleX /= 1.80;dealerSpot.scaleY /= 1.80;} } private function initializePlayerHand(carderone:String, cardertwo:String):void { if (carderone == "A") {cardSpotOne.addChild(new AceImage());} if (carderone == "2") {cardSpotOne.addChild(new TwoImage());} if (carderone == "3") {cardSpotOne.addChild(new ThreeImage());} if (carderone == "4") {cardSpotOne.addChild(new FourImage());} if (carderone == "5") {cardSpotOne.addChild(new FiveImage());} if (carderone == "6") {cardSpotOne.addChild(new SixImage());} if (carderone == "7") {cardSpotOne.addChild(new SevenImage());} if (carderone == "8") {cardSpotOne.addChild(new EightImage());} if (carderone == "9") {cardSpotOne.addChild(new NineImage());} if (carderone == "10") {cardSpotOne.addChild(new TenImage());} if (cardertwo == "A") {cardSpotOne.addChild(new AceImage());} if (cardertwo == "2") {cardSpotOne.addChild(new TwoImage());} if (cardertwo == "3") {cardSpotOne.addChild(new ThreeImage());} if (cardertwo == "4") {cardSpotOne.addChild(new FourImage());} if (cardertwo == "5") {cardSpotOne.addChild(new FiveImage());} if (cardertwo == "6") {cardSpotOne.addChild(new SixImage());} if (cardertwo == "7") {cardSpotOne.addChild(new SevenImage());} if (cardertwo == "8") {cardSpotOne.addChild(new EightImage());} if (cardertwo == "9") {cardSpotOne.addChild(new NineImage());} if (cardertwo == "10") {cardSpotOne.addChild(new TenImage());} cardSpotOne.getChildAt(0).x = 0; cardSpotOne.getChildAt(0).y = 0; cardSpotOne.getChildAt(1).x = cardSpotOne.getChildAt(0).x + 25; cardSpotOne.getChildAt(1).y = cardSpotOne.getChildAt(0).y - 25; if (cardSpotOne.scaleX == 1.0) {cardSpotOne.scaleX /= 1.1;cardSpotOne.scaleY /= 1.1;} } private function addHit(wcard:String):void { if (wcard == "A") {cardSpotOne.addChild(new AceImage());} if (wcard == "2") {cardSpotOne.addChild(new TwoImage());} if (wcard == "3") {cardSpotOne.addChild(new ThreeImage());} if (wcard == "4") {cardSpotOne.addChild(new FourImage());} if (wcard == "5") {cardSpotOne.addChild(new FiveImage());} if (wcard == "6") {cardSpotOne.addChild(new SixImage());} if (wcard == "7") {cardSpotOne.addChild(new SevenImage());} if (wcard == "8") {cardSpotOne.addChild(new EightImage());} if (wcard == "9") {cardSpotOne.addChild(new NineImage());} if (wcard == "10") {cardSpotOne.addChild(new TenImage());} cardSpotOne.getChildAt(cardSpotOne.numChildren-1).x =cardSpotOne.getChildAt(cardSpotOne.numChildren-2).x + 25; cardSpotOne.getChildAt(cardSpotOne.numChildren-1).y =cardSpotOne.getChildAt(cardSpotOne.numChildren-2).y - 25; if (cardSpotOne.scaleX == 1.0) {cardSpotOne.scaleX /= 1.1;cardSpotOne.scaleY /= 1.1;} } private function addHitTwo(wcard:String):void { if (wcard == "A") {cardSpotTwo.addChild(new AceImage());} if (wcard == "2") {cardSpotTwo.addChild(new TwoImage());} if (wcard == "3") {cardSpotTwo.addChild(new ThreeImage());} if (wcard == "4") {cardSpotTwo.addChild(new FourImage());} if (wcard == "5") {cardSpotTwo.addChild(new FiveImage());} if (wcard == "6") {cardSpotTwo.addChild(new SixImage());} if (wcard == "7") {cardSpotTwo.addChild(new SevenImage());} if (wcard == "8") {cardSpotTwo.addChild(new EightImage());} if (wcard == "9") {cardSpotTwo.addChild(new NineImage());} if (wcard == "10") {cardSpotTwo.addChild(new TenImage());} cardSpotTwo.getChildAt(cardSpotTwo.numChildren-1).x =cardSpotTwo.getChildAt(cardSpotTwo.numChildren-2).x + 25; cardSpotTwo.getChildAt(cardSpotTwo.numChildren-1).y =cardSpotTwo.getChildAt(cardSpotTwo.numChildren-2).y - 25; if (cardSpotTwo.scaleX == 1.0) {cardSpotTwo.scaleX /= 1.1;cardSpotTwo.scaleY /= 1.1;} } private function addHitThree(wcard:String):void { if (wcard == "A") {cardSpotThree.addChild(new AceImage());} if (wcard == "2") {cardSpotThree.addChild(new TwoImage());} if (wcard == "3") {cardSpotThree.addChild(new ThreeImage());} if (wcard == "4") {cardSpotThree.addChild(new FourImage());} if (wcard == "5") {cardSpotThree.addChild(new FiveImage());} if (wcard == "6") {cardSpotThree.addChild(new SixImage());} if (wcard == "7") {cardSpotThree.addChild(new SevenImage());} if (wcard == "8") {cardSpotThree.addChild(new EightImage());} if (wcard == "9") {cardSpotThree.addChild(new NineImage());} if (wcard == "10") {cardSpotThree.addChild(new TenImage());} cardSpotThree.getChildAt(cardSpotThree.numChildren-1).x =cardSpotThree.getChildAt(cardSpotThree.numChildren-2).x + 25; cardSpotThree.getChildAt(cardSpotThree.numChildren-1).y =cardSpotThree.getChildAt(cardSpotThree.numChildren-2).y - 25; if (cardSpotThree.scaleX == 1.0) {cardSpotThree.scaleX /= 1.1;cardSpotThree.scaleY /= 1.1;} } private function showSplit(bottc:String, topc:String, bottc2:String, topc2:String):void { cardSpotOne.removeChildAt(cardSpotOne.numChildren - 1); if (topc == "A") {cardSpotOne.addChild(new AceImage());} if (topc == "2") {cardSpotOne.addChild(new TwoImage());} if (topc == "3") {cardSpotOne.addChild(new ThreeImage());} if (topc == "4") {cardSpotOne.addChild(new FourImage());} if (topc == "5") {cardSpotOne.addChild(new FiveImage());} if (topc == "6") {cardSpotOne.addChild(new SixImage());} if (topc == "7") {cardSpotOne.addChild(new SevenImage());} if (topc == "8") {cardSpotOne.addChild(new EightImage());} if (topc == "9") {cardSpotOne.addChild(new NineImage());} if (topc == "10") {cardSpotOne.addChild(new TenImage());} cardSpotOne.getChildAt(cardSpotOne.numChildren-1).x =cardSpotOne.getChildAt(cardSpotOne.numChildren-2).x + 25; cardSpotOne.getChildAt(cardSpotOne.numChildren-1).y =cardSpotOne.getChildAt(cardSpotOne.numChildren-2).y - 25; if (bottc2 == "A") {cardSpotTwo.addChild(new AceImage());} if (bottc2 == "2") {cardSpotTwo.addChild(new TwoImage());} if (bottc2 == "3") {cardSpotTwo.addChild(new ThreeImage());} if (bottc2 == "4") {cardSpotTwo.addChild(new FourImage());} if (bottc2 == "5") {cardSpotTwo.addChild(new FiveImage());} if (bottc2 == "6") {cardSpotTwo.addChild(new SixImage());} if (bottc2 == "7") {cardSpotTwo.addChild(new SevenImage());} if (bottc2 == "8") {cardSpotTwo.addChild(new EightImage());} if (bottc2 == "9") {cardSpotTwo.addChild(new NineImage());} if (bottc2 == "10") {cardSpotTwo.addChild(new TenImage());} if (topc2 == "A") {cardSpotTwo.addChild(new AceImage());} if (topc2 == "2") {cardSpotTwo.addChild(new TwoImage());} if (topc2 == "3") {cardSpotTwo.addChild(new ThreeImage());} if (topc2 == "4") {cardSpotTwo.addChild(new FourImage());} if (topc2 == "5") {cardSpotTwo.addChild(new FiveImage());} if (topc2 == "6") {cardSpotTwo.addChild(new SixImage());} if (topc2 == "7") {cardSpotTwo.addChild(new SevenImage());} if (topc2 == "8") {cardSpotTwo.addChild(new EightImage());} if (topc2 == "9") {cardSpotTwo.addChild(new NineImage());} if (topc2 == "10") {cardSpotTwo.addChild(new TenImage());} cardSpotTwo.getChildAt(0).x = 0; cardSpotTwo.getChildAt(0).y = 0; cardSpotTwo.getChildAt(cardSpotTwo.numChildren-1).x =cardSpotTwo.getChildAt(cardSpotTwo.numChildren-2).x + 25; cardSpotTwo.getChildAt(cardSpotTwo.numChildren-1).y =cardSpotTwo.getChildAt(cardSpotTwo.numChildren-2).y - 25; if (cardSpotTwo.scaleX == 1.0) {cardSpotTwo.scaleX /= 1.1;cardSpotTwo.scaleY /= 1.1;} if (cardSpotThree.scaleX == 1.0) {cardSpotThree.scaleX /= 1.1;cardSpotThree.scaleY /= 1.1;} } private function showSplitTwo(bottc:String, topc:String, bottc2:String, topc2:String):void { cardSpotTwo.removeChildAt(cardSpotTwo.numChildren - 1); if (topc == "A") {cardSpotTwo.addChild(new AceImage());} if (topc == "2") {cardSpotTwo.addChild(new TwoImage());} if (topc == "3") {cardSpotTwo.addChild(new ThreeImage());} if (topc == "4") {cardSpotTwo.addChild(new FourImage());} if (topc == "5") {cardSpotTwo.addChild(new FiveImage());} if (topc == "6") {cardSpotTwo.addChild(new SixImage());} if (topc == "7") {cardSpotTwo.addChild(new SevenImage());} if (topc == "8") {cardSpotTwo.addChild(new EightImage());} if (topc == "9") {cardSpotTwo.addChild(new NineImage());} if (topc == "10") {cardSpotTwo.addChild(new TenImage());} cardSpotTwo.getChildAt(cardSpotTwo.numChildren-1).x =
cardSpotTwo.getChildAt(cardSpotTwo.numChildren-2).x + 25; cardSpotTwo.getChildAt(cardSpotTwo.numChildren-1).y =
cardSpotTwo.getChildAt(cardSpotTwo.numChildren-2).y - 25; if (bottc2 == "A") {cardSpotThree.addChild(new AceImage());} if (bottc2 == "2") {cardSpotThree.addChild(new TwoImage());} if (bottc2 == "3") {cardSpotThree.addChild(new ThreeImage());} if (bottc2 == "4") {cardSpotThree.addChild(new FourImage());} if (bottc2 == "5") {cardSpotThree.addChild(new FiveImage());} if (bottc2 == "6") {cardSpotThree.addChild(new SixImage());} if (bottc2 == "7") {cardSpotThree.addChild(new SevenImage());} if (bottc2 == "8") {cardSpotThree.addChild(new EightImage());} if (bottc2 == "9") {cardSpotThree.addChild(new NineImage());} if (bottc2 == "10") {cardSpotThree.addChild(new TenImage());} if (topc2 == "A") {cardSpotThree.addChild(new AceImage());} if (topc2 == "2") {cardSpotThree.addChild(new TwoImage());} if (topc2 == "3") {cardSpotThree.addChild(new ThreeImage());} if (topc2 == "4") {cardSpotThree.addChild(new FourImage());} if (topc2 == "5") {cardSpotThree.addChild(new FiveImage());} if (topc2 == "6") {cardSpotThree.addChild(new SixImage());} if (topc2 == "7") {cardSpotThree.addChild(new SevenImage());} if (topc2 == "8") {cardSpotThree.addChild(new EightImage());} if (topc2 == "9") {cardSpotThree.addChild(new NineImage());} if (topc2 == "10") {cardSpotThree.addChild(new TenImage());} cardSpotThree.getChildAt(0).x = 0; cardSpotThree.getChildAt(0).y = 0; cardSpotThree.getChildAt(cardSpotThree.numChildren-1).x =cardSpotThree.getChildAt(cardSpotThree.numChildren-2).x + 25; cardSpotThree.getChildAt(cardSpotThree.numChildren-1).y =cardSpotThree.getChildAt(cardSpotThree.numChildren-2).y - 25; if (cardSpotTwo.scaleX == 1.0) {cardSpotTwo.scaleX /= 1.1;cardSpotTwo.scaleY /= 1.1;} if (cardSpotThree.scaleX == 1.0) {cardSpotThree.scaleX /= 1.1;cardSpotThree.scaleY /= 1.1;} } private function showSplitThree(bottc:String, topc:String, bottc2:String, topc2:String):void { cardSpotOne.removeChildAt(cardSpotOne.numChildren - 1); if (topc == "A") {cardSpotOne.addChild(new AceImage());} if (topc == "2") {cardSpotOne.addChild(new TwoImage());} if (topc == "3") {cardSpotOne.addChild(new ThreeImage());} if (topc == "4") {cardSpotOne.addChild(new FourImage());} if (topc == "5") {cardSpotOne.addChild(new FiveImage());} if (topc == "6") {cardSpotOne.addChild(new SixImage());} if (topc == "7") {cardSpotOne.addChild(new SevenImage());} if (topc == "8") {cardSpotOne.addChild(new EightImage());} if (topc == "9") {cardSpotOne.addChild(new NineImage());} if (topc == "10") {cardSpotOne.addChild(new TenImage());} cardSpotOne.getChildAt(cardSpotOne.numChildren-1).x =cardSpotOne.getChildAt(cardSpotOne.numChildren-2).x + 25; cardSpotOne.getChildAt(cardSpotOne.numChildren-1).y =cardSpotOne.getChildAt(cardSpotOne.numChildren-2).y - 25; if (bottc2 == "A") {cardSpotThree.addChild(new AceImage());} if (bottc2 == "2") {cardSpotThree.addChild(new TwoImage());} if (bottc2 == "3") {cardSpotThree.addChild(new ThreeImage());} if (bottc2 == "4") {cardSpotThree.addChild(new FourImage());} if (bottc2 == "5") {cardSpotThree.addChild(new FiveImage());} if (bottc2 == "6") {cardSpotThree.addChild(new SixImage());} if (bottc2 == "7") {cardSpotThree.addChild(new SevenImage());} if (bottc2 == "8") {cardSpotThree.addChild(new EightImage());} if (bottc2 == "9") {cardSpotThree.addChild(new NineImage());} if (bottc2 == "10") {cardSpotThree.addChild(new TenImage());} if (topc2 == "A") {cardSpotThree.addChild(new AceImage());} if (topc2 == "2") {cardSpotThree.addChild(new TwoImage());} if (topc2 == "3") {cardSpotThree.addChild(new ThreeImage());} if (topc2 == "4") {cardSpotThree.addChild(new FourImage());} if (topc2 == "5") {cardSpotThree.addChild(new FiveImage());} if (topc2 == "6") {cardSpotThree.addChild(new SixImage());} if (topc2 == "7") {cardSpotThree.addChild(new SevenImage());} if (topc2 == "8") {cardSpotThree.addChild(new EightImage());} if (topc2 == "9") {cardSpotThree.addChild(new NineImage());} if (topc2 == "10") {cardSpotThree.addChild(new TenImage());} cardSpotThree.getChildAt(0).x = 0; cardSpotThree.getChildAt(0).y = 0; cardSpotThree.getChildAt(cardSpotThree.numChildren-1).x =cardSpotThree.getChildAt(cardSpotThree.numChildren-2).x + 25; cardSpotThree.getChildAt(cardSpotThree.numChildren-1).y =cardSpotThree.getChildAt(cardSpotThree.numChildren-2).y - 25; if (cardSpotTwo.scaleX == 1.0) {cardSpotTwo.scaleX /= 1.1;cardSpotTwo.scaleY /= 1.1;} if (cardSpotThree.scaleX == 1.0) {cardSpotThree.scaleX /= 1.1;cardSpotThree.scaleY /= 1.1;} } private function addDealerHit(card:String):void { if (card == "A") {dealerSpot.addChild(new AceImage());} if (card == "2") {dealerSpot.addChild(new TwoImage());} if (card == "3") {dealerSpot.addChild(new ThreeImage());} if (card == "4") {dealerSpot.addChild(new FourImage());} if (card == "5") {dealerSpot.addChild(new FiveImage());} if (card == "6") {dealerSpot.addChild(new SixImage());} if (card == "7") {dealerSpot.addChild(new SevenImage());} if (card == "8") {dealerSpot.addChild(new EightImage());} if (card == "9") {dealerSpot.addChild(new NineImage());} if (card == "10") {dealerSpot.addChild(new TenImage());} dealerSpot.getChildAt(dealerSpot.numChildren -1).x =
dealerSpot.getChildAt(dealerSpot.numChildren-2).x +105; dealerSpot.getChildAt(dealerSpot.numChildren -1).y =dealerSpot.getChildAt(dealerSpot.numChildren-2).y; } private function makeTXTField(fieldName:TextField, fieldTXT:String):TextField { fieldName = new TextField(); fieldName.defaultTextFormat = TXTFormat; fieldName.autoSize = TextFieldAutoSize.LEFT; fieldName.height = 20; fieldName.selectable = false; fieldName.text = fieldTXT; return(fieldName); } private function deal(event:MouseEvent):void { if (stage.contains(winField)) {winField.text = "";stage.removeChild(winField);} splitHandOne = 0; splitHandTwo = 0; splitHandThree = 0; while (cardSpotOne.numChildren > 0) { cardSpotOne.removeChildAt(cardSpotOne.numChildren-1); if (cardSpotOne == null) {break;} } while (cardSpotTwo.numChildren > 0) { cardSpotTwo.removeChildAt(cardSpotTwo.numChildren-1); if (cardSpotTwo == null) {break;} } while (cardSpotThree.numChildren > 0) { cardSpotThree.removeChildAt(cardSpotThree.numChildren-1); if (cardSpotThree == null) {break;} } while (dealerSpot.numChildren > 0) { dealerSpot.removeChildAt(dealerSpot.numChildren-1); if (dealerSpot == null) {break;} } acesUsed = 0; playerCardOne = giveCard(); playerCardTwo = giveCard(); playerHand=calculateTwoCardHand(playerCardOne, playerCardTwo); dealerCardOne = giveCard(); dealerCardTwo = giveCard(); dealerHand=calculateTwoCardHand(dealerCardOne, dealerCardTwo); update(); initializePlayerHand(playerCardOne, playerCardTwo); initializeDealerHand(dealerCardOne, dealerCardTwo); } private function update():void { dealerTXTField.text = "Dealer cards: "+ dealerCardOne + " " + dealerCardTwo + " dealer hand totals: " + dealerHand; playerTXTField.text = "Player cards: "+ playerCardOne + " " + playerCardTwo + " your hand totals: " + playerHand; } private function giveCard():String { var theCard:String = "A"; var randomNumber:Number = Math.floor(Math.random()*10); if (randomNumber == 1) {theCard ="A";} else { if (randomNumber == 0) {theCard = "10";} else {theCard = randomNumber.toString();} } return(theCard); } private function calculateTwoCardHand(cardOne:String, cardTwo:String):Number { var theHand:Number = 0; if (cardOne == "A" && cardTwo != "A") { /* only two aces could make this happen */ if (11 + int(cardTwo) > 21) {theHand = 1+ int(cardTwo);} else {theHand = 11+ int(cardTwo);} } if (cardOne != "A" && cardTwo == "A") { if (11 + int(cardOne) > 21) {theHand = 1 + int(cardOne) ;} else {theHand = 11 + int(cardOne) ;} } if (cardOne == "A" && cardTwo == "A") { theHand = 2; if (cardOne !=dealerCardOne || cardTwo !=dealerCardTwo) {acesUsed += 1;} } if (cardOne != "A" && cardTwo != "A") { theHand = int(cardOne) + int(cardTwo); } return(theHand); } } }
Spaceship Shooter game with AS3
 


The Code:     types  events  properties, methods, and declarative words  functions/operational methods


Overview:
This game is simple and is a good example of using the Timer class for a multiple timeline effect.
To compile this game you will need to create your own images and sound, and
change the name of the embed folder (../testimages) to the folder where your images are.
package { import flash.display.Sprite; import flash.display.Graphics; import flash.display.DisplayObject; import flash.display.GradientType; import flash.geom.Rectangle; import flash.geom.Matrix; import flash.events.MouseEvent; import flash.events.KeyboardEvent; import flash.events.Event; import flash.events.TimerEvent; import flash.utils.Timer; import flash.ui.Mouse; import flash.text.TextField; import flash.text.TextFormat; import flash.text.TextFormatAlign; import flash.text.TextFieldAutoSize; import flash.media.Sound; [SWF( backgroundColor = '0xA9A9A9', frameRate = '20', width = '500', height = '500')] /*a (t)a.d as3 tutorial copyright 2008 */ public class ShipShooterGame extends Sprite { private var shotDistance:Number = 20; private var shotGo:Timer; private var pellet:Sprite; private var pelletTwo:Sprite; private var pelletThree:Sprite; private var theShip:Sprite; private var pelletTwoGo:String = "no"; private var pelletThreeGo:String = "no"; private var enemyOne:Sprite; private var enemyOneLife:Number = 0; /* the smaller the tougher */ private var enemyOneToughness:Number = .03; private var enemyOneBaby:Sprite; private var enemyTwo:Sprite; private var enemyTwoLife:Number = 0; private var enemyTwoToughness:Number = .01; private var enemyThree:Sprite; private var enemyThreeLife:Number = 0; private var enemyThreeToughness:Number = .01; private var enemyDeploy:Timer; private var lifeMeter:Sprite; private var playerLife:Number = 115; private var lifeBox:Sprite; private var theScore:Number = 0; private var shipStatus:TextField; private var currentSituation:String = "All systems go - click then press enter"; private var statTXTFormat:TextFormat; private var gameStarted:String = "no"; private var powerUp:Sprite; private var pelletPower:Number = 0; private var backgroundAnimation:Timer; private var gameBack:Sprite; private var pelletShotMatrix:Matrix; private var shotColors:Array = [0xFFFF60, 0xFFFFFF]; private var circleRadius:Number = 5; private var mouseActive:String = "yes"; [Embed(source="../testimages/pup.png")] private var PowerUpImage:Class; [Embed(source="../testimages/backstars.gif")] private var StarBackOne:Class; [Embed(source="../testimages/backstarsb.gif")] private var StarBackTwo:Class; [Embed(source="../testimages/backstarsc.gif")] private var StarBackThree:Class; [Embed(source="../testimages/aship.png")] private var ShipImage:Class; [Embed(source="../testimages/enys.png")] private var enemyImage:Class; [Embed(source="../testimages/enysother.png")] private var YellowEnemyImage:Class; [Embed(source="../testimages/shot.mp3")] private var ShotSound:Class; private var shotNoise:Sound = new ShotSound(); public function ShipShooterGame() { backgroundAnimation = new Timer(300, 0); gameBack = new Sprite(); gameBack.addChild(new StarBackOne()); gameBack.addChild(new StarBackTwo()); gameBack.addChild(new StarBackThree()); addChild(gameBack); backgroundAnimation.addEventListener(TimerEvent.TIMER, backAnimation); backgroundAnimation.start(); powerUp = new Sprite(); var puper:DisplayObject = new PowerUpImage(); puper.x = 0 - puper.width/2; puper.y = 0 - puper.height/2; powerUp.addChild(puper); powerUp.x = 75; powerUp.y = -50; addChild(powerUp); statTXTFormat = new TextFormat(); statTXTFormat.font = "Arial"; statTXTFormat.color = 0xE0FFFF; statTXTFormat.size = 10; statTXTFormat.align = TextFormatAlign.LEFT; shipStatus = new TextField(); shipStatus.defaultTextFormat = statTXTFormat; shipStatus.autoSize = TextFieldAutoSize.LEFT; shipStatus.height = 20; shipStatus.selectable = false; shipStatus.text = "Score: " + theScore + "\n" + "Status: " + currentSituation; enemyDeploy = new Timer(300, 50); enemyOne = makeAnEnemy(enemyOne); enemyOne.y = -55; enemyOne.x = 500/2; enemyOneBaby=makeBaby(enemyOneBaby); enemyOneBaby.x = enemyOne.x; enemyOneBaby.y = enemyOne.y; enemyTwo = makeAnEnemy(enemyTwo); enemyTwo.y = -55;enemyTwo.x = 500/2 + enemyOne.width + 95; enemyThree = makeAnEnemy(enemyThree); enemyThree.y = -55;enemyThree.x = 500/2 - enemyOne.width - 95; addChild(enemyThree); addChild(enemyTwo); addChild(enemyOneBaby); addChild(enemyOne); lifeBox = new Sprite(); lifeBox.graphics.lineStyle(2, 0x6A5ACD); lifeBox.graphics.drawRect(0, 0, 120, 20); lifeMeter = lifeMeterCreate(lifeMeter, playerLife); lifeBox.addChild(lifeMeter); lifeBox.y = 500 - 40; lifeBox.x = 30; addChild(lifeBox); shipStatus.x = lifeBox.x; shipStatus.y = lifeBox.y - lifeBox.height - 7; addChild(shipStatus); shotGo = new Timer(50, 7); theShip = new Sprite(); var ship:DisplayObject = new ShipImage(); ship.x = 0 - ship.width/2; ship.y = 0 - ship.height/2; theShip.addChild(ship); pelletShotMatrix = new Matrix(); pelletShotMatrix.createGradientBox(2, 2, Math.PI/2, 0, 0); pellet = new Sprite(); pellet.graphics.lineStyle(0); pellet.graphics.beginGradientFill(GradientType.LINEAR, shotColors, [1.0, 0.4], [0, 127], pelletShotMatrix); pellet.graphics.drawCircle(0, 0, circleRadius); pelletTwo = new Sprite(); pelletTwo.graphics.lineStyle(0); pelletTwo.graphics.beginGradientFill(GradientType.LINEAR, shotColors, [1.0, 0.4], [0, 127],pelletShotMatrix); pelletTwo.graphics.drawCircle(0, 0, circleRadius); pelletThree = new Sprite(); pelletThree.graphics.lineStyle(0); pelletThree.graphics.beginGradientFill(GradientType.LINEAR, shotColors, [1.0, 0.4], [0, 127], pelletShotMatrix); pelletThree.graphics.drawCircle(0, 0, circleRadius); theShip.x = 500/2 - theShip.width/2; theShip.y = 500/2 - theShip.height/2; theShip.buttonMode = true; theShip.addEventListener(MouseEvent.CLICK, firePelletHandler); pellet.x = theShip.x; pellet.y = theShip.y; pelletTwo.x = theShip.x; pelletTwo.y = theShip.y; pelletThree.x = theShip.x; pelletThree.y = theShip.y; addChild(pelletThree); addChild(pelletTwo); addChild(pellet); addChild(theShip); stage.addEventListener(Event.ENTER_FRAME, theGame); stage.addEventListener(MouseEvent.CLICK, goBackToMouse); stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler); } /* start funcs */ private function goBackToMouse(event:MouseEvent):void { mouseActive = "yes"; } private function upThePellets():void { circleRadius += 1; pellet.graphics.clear(); pellet.graphics.lineStyle(0); pellet.graphics.beginGradientFill(GradientType.LINEAR, shotColors, [1.0, 0.4], [0, 127], pelletShotMatrix); pellet.graphics.drawCircle(0, 0, circleRadius); pelletTwo.graphics.clear(); pelletTwo.graphics.lineStyle(0); pelletTwo.graphics.beginGradientFill(GradientType.LINEAR, shotColors, [1.0, 0.4], [0, 127],pelletShotMatrix); pelletTwo.graphics.drawCircle(0, 0, circleRadius); pelletThree.graphics.clear(); pelletThree.graphics.lineStyle(0); pelletThree.graphics.beginGradientFill(GradientType.LINEAR, shotColors, [1.0, 0.4], [0, 127], pelletShotMatrix); pelletThree.graphics.drawCircle(0, 0, circleRadius); } private function backAnimation(event:TimerEvent):void { /* this is always happening swapping the three background pics */ gameBack.swapChildrenAt(2, 1); gameBack.swapChildrenAt(1, 0); } private function changeStats(statnow:String):void { currentSituation = statnow; shipStatus.text = "Score: " + theScore + "\n" + "Status: " + currentSituation; } private function makeAnEnemy(enemy:Sprite):Sprite { enemy = new Sprite(); var enylook:* = new enemyImage(); /* this gives the object the x and y in its middle like a circle */ enylook.x = 0 - enylook.width/2; enylook.y = 0 - enylook.height/2; enemy.addChild(enylook); return(enemy); } private function changeEnemy(enemy:Sprite, enyimg:*, uptough:Number):void { enemy.removeChildAt(0); var enylook:* = enyimg; enylook.x = 0 - enylook.width/2; enylook.y = 0 - enylook.height/2; enemy.addChild(enylook); if (enemy == enemyOne) {enemyOneToughness -= uptough;} } private function makeBaby(benemy:Sprite):Sprite { benemy = new Sprite(); benemy.graphics.lineStyle(1, 0xFF0000); benemy.graphics.beginFill(0xD19275); benemy.graphics.drawCircle(0, 0, 7); return(benemy); } /* keyboard control all keyboard events happen off this one function that waits for any key to be pressed its also the function that starts the game since enter must be pressed */ private function keyDownHandler(event:KeyboardEvent):void { if (event.keyCode == 13 && enemyDeploy.running == false && gameStarted == "no") {startGame();} if (event.keyCode == 32 && enemyDeploy.running == true && gameStarted == "yes") {mouseActive="no";keyboardFirePellet();} if (event.keyCode == 39) {mouseActive="no";theShip.x += 7;} if (event.keyCode == 37) {mouseActive="no";theShip.x -= 7;} if (event.keyCode == 38) {mouseActive="no";theShip.y -= 7;} if (event.keyCode == 40) {mouseActive="no";theShip.y += 7;} } private function resetEnemysAndTimer():void { /* this function happens if all the enemies get destroyed in ortherwords alpha of zero or less */ Timer(enemyDeploy).reset();Timer(enemyDeploy).stop(); var nextleveldelay:Number = 800; if (theScore <= 9) {enemyOneToughness -= .0002;enemyTwoToughness -= .0002;enemyThreeToughness -= .0002; enemyDeploy.delay -= .5;} if (theScore >= 10 && theScore <= 12) {enemyOneToughness -= .001;enemyTwoToughness -= .001;enemyThreeToughness -= .001;enemyDeploy.delay -= 1;} if (theScore >= 20 && theScore < 24) {enemyOneToughness -= .003;enemyTwoToughness -= .002;enemyThreeToughness -= .002;enemyDeploy.delay -= 3; changeStats("next enemys");changeEnemy(enemyOne, new YellowEnemyImage(), .02);} if (theScore >= 30 && theScore <= 35) {enemyOneToughness -= .002;enemyTwoToughness -= .003;enemyThreeToughness -= .003;enemyDeploy.delay -= 10; changeStats("enemy level +3");} if (theScore >= 50 && theScore <= 52) {enemyOneToughness -= .004;enemyTwoToughness -= .004;enemyThreeToughness -= .004;enemyDeploy.delay -= 25; changeStats("enemy level +4");} enemyOne.alpha = 1;enemyOne.y = -70;enemyOneLife = 0; enemyTwo.alpha = 1;enemyTwo.y = -50;enemyTwoLife = 0; enemyThree.alpha = 1;enemyThree.y = -50;enemyThreeLife = 0;powerUp.alpha = 1;powerUp.y = -50; enemyTwo.x = enemyOne.x + enemyOne.width + 65; enemyThree.x = enemyOne.x - enemyOne.width - 65;enemyDeploy.delay -= 2; var killedallreset:Timer = new Timer(nextleveldelay, 2); killedallreset.addEventListener(TimerEvent.TIMER_COMPLETE, redeploy); killedallreset.start(); } private function redeploy(event:TimerEvent):void { Timer(enemyDeploy).reset();Timer(enemyDeploy).start(); } private function resetEnemys(event:TimerEvent):void { /* this function happens at the end of enemy deploy, in otherwords when the enemys pass the bottom to give time for any next level animation or not. enemyDeploys delay is what makes the enemys fall down faster */ var levelupdelay:Number = 1000; Timer(enemyDeploy).reset();Timer(enemyDeploy).stop(); if (theScore >= 10 && theScore <= 12) {enemyOneToughness -= .001;enemyTwoToughness -= .001;enemyThreeToughness -= .001;enemyDeploy.delay -= 1;} if (theScore >= 20 && theScore <= 22) {enemyOneToughness -= .002;enemyTwoToughness -= .002;enemyThreeToughness -= .002;enemyDeploy.delay -= 3; changeStats("get more enemies");} if (theScore >= 30 && theScore <= 34) {enemyOneToughness -= .003;enemyTwoToughness -= .003;enemyThreeToughness -= .003;enemyDeploy.delay -= 9; changeStats("enemy level +3");changeEnemy(enemyThree, new YellowEnemyImage(), .014);} if (theScore >= 50 && theScore <= 52) {enemyOneToughness -= .003;enemyTwoToughness -= .004;enemyThreeToughness -= .004;enemyDeploy.delay -= 24; changeStats("enemy level +4");} enemyOne.y = - 70;enemyOne.alpha =1;enemyOneLife = 0; enemyTwo.y = - 50;enemyTwo.alpha =1;enemyTwoLife = 0; enemyThree.y = - 50;enemyThree.alpha =1;enemyThreeLife = 0;powerUp.alpha = 1;powerUp.y = -50; enemyTwo.x = enemyOne.x + enemyOne.width + 65; enemyThree.x = enemyOne.x - enemyOne.width - 65;enemyDeploy.delay -= 2; var somepassed:Timer = new Timer(levelupdelay, 2); somepassed.addEventListener(TimerEvent.TIMER_COMPLETE, redeploy); somepassed.start(); } private function lifeMeterChange(thebar:Sprite, lifeleft:Number):void { /* max 115 */ thebar.graphics.clear(); thebar.graphics.lineStyle(0, 0xFF0000); thebar.graphics.beginFill(0xFF0000); thebar.graphics.drawRect(2, 1, lifeleft, 17); thebar.graphics.endFill(); } private function lifeMeterCreate(thebar:Sprite, lifeleft:Number):Sprite { /* max is 115 */ thebar = new Sprite(); thebar.graphics.clear(); thebar.graphics.lineStyle(0, 0xFF0000); thebar.graphics.beginFill(0xFF0000); thebar.graphics.drawRect(2, 1, lifeleft, 17); thebar.graphics.endFill(); return(thebar); } /* govern the enemys travel and anything that falls down give points and powerUping this function is tied closely to theGame function this is the function of the falldown or enemy timeline enemyDeploy in this way the swf has more than one timeline */ private function enemyGo(event:TimerEvent):void { enemyOne.y += 20; if (enemyOne.y >= 110 && enemyOne.alpha > 0.2) {enemyOneBaby.y += 60;} else {enemyOneBaby.y = enemyOne.y;enemyOneBaby.alpha = 0;} enemyOne.alpha -= enemyOneLife;enemyOneBaby.alpha = enemyOne.alpha; if (enemyOne.y < 500) { if (enemyOne.alpha <= 0.2 && enemyOne.alpha > 0.01) {theScore += .5;changeStats("Enemy destroyed");} } enemyTwo.y += 20; enemyTwo.alpha -= enemyTwoLife; if (enemyTwo.y < 500) { if (enemyTwo.alpha <= 0.2 && enemyTwo.alpha > 0.01) {theScore += .5;changeStats("Enemy destroyed");} } enemyThree.y += 20; enemyThree.alpha -= enemyThreeLife; if (enemyThree.y < 500) { if (enemyThree.alpha <= 0.2 && enemyThree.alpha > 0.01) {theScore += .5;changeStats("Enemy destroyed");} } if (theScore >= 20 && theScore <= 24) { if (powerUp.y < 500+powerUp.height) {powerUp.y += 30;} else {powerUp.y = -50;} } if (theScore >= 45 && theScore <= 49) { if (powerUp.y < 500+powerUp.height) {powerUp.y += 38;} else {powerUp.y = -50;} } if (powerUp.x >= theShip.x - 20 && powerUp.x <= theShip.x + 20 && powerUp.y >= theShip.y - 20 && powerUp.y < 500+powerUp.height && powerUp.y <= theShip.y + 20) {pelletPower += .008;changeStats("shot power up");upThePellets();} } /* stop game */ private function stopGame():void { gameStarted = "no"; Mouse.show(); shotGo.removeEventListener(TimerEvent.TIMER, seeShot); shotGo.removeEventListener(TimerEvent.TIMER_COMPLETE, resetShot); enemyDeploy.removeEventListener(TimerEvent.TIMER, enemyGo); enemyDeploy.removeEventListener(TimerEvent.TIMER_COMPLETE, resetEnemys); if (enemyDeploy.running == true) {Timer(enemyDeploy).stop();} } /* start game */ private function startGame():void { gameStarted = "yes"; Mouse.hide(); shotGo.addEventListener(TimerEvent.TIMER, seeShot); shotGo.addEventListener(TimerEvent.TIMER_COMPLETE, resetShot); enemyDeploy.addEventListener(TimerEvent.TIMER, enemyGo); enemyDeploy.addEventListener(TimerEvent.TIMER_COMPLETE, resetEnemys); if (enemyDeploy.running == false) {Timer(enemyDeploy).start();} } /* animation and main game if thens always happening */ private function theGame(event:Event):void { if (mouseActive =="yes") {theShip.x = mouseX;theShip.y = mouseY;} pellet.x = theShip.x;pelletTwo.x = theShip.x;pelletThree.x = theShip.x; pellet.y = theShip.y - shotDistance; if (pelletTwoGo == "yes") {pelletTwo.y = theShip.y - shotDistance + pellet.width*3;} else {pelletTwo.y = theShip.y;} if (pelletThreeGo == "yes") {pelletThree.y = theShip.y - shotDistance + pellet.width*3 + pelletTwo.width*3;} else {pelletThree.y = theShip.y;} if (gameStarted == "yes") { if (enemyOne.hitTestObject(pellet) || enemyOne.hitTestObject(pelletTwo) || enemyOne.hitTestObject(pelletThree)) {enemyOneLife += enemyOneToughness+pelletPower;enemyOne.y -= 5;} if (enemyTwo.hitTestObject(pellet) || enemyTwo.hitTestObject(pelletTwo) || enemyTwo.hitTestObject(pelletThree)) {enemyTwoLife += enemyTwoToughness+pelletPower;enemyTwo.y -= 5;} if (enemyThree.hitTestObject(pellet) || enemyThree.hitTestObject(pelletTwo) || enemyThree.hitTestObject(pelletThree)) {enemyThreeLife += enemyThreeToughness+pelletPower;enemyThree.y -= 5;} if (theShip.hitTestObject(enemyOne)) {enemyOne.y -= 10;} if (theShip.hitTestObject(enemyTwo)) {enemyTwo.y -= 10;} if (theShip.hitTestObject(enemyThree)) {enemyThree.y -= 10;} if (theShip.hitTestObject(enemyOne) && enemyOne.alpha > 0.3) { if (playerLife > 0) {playerLife -=5;lifeMeterChange(lifeMeter, playerLife);changeStats("Ship damage!");} } if (theShip.hitTestObject(enemyTwo) && enemyTwo.alpha > 0.3) { if (playerLife > 0) {playerLife -=5;lifeMeterChange(lifeMeter, playerLife);changeStats("Ship damage!");} } if (theShip.hitTestObject(enemyThree) && enemyThree.alpha > 0.3) { if (playerLife > 0) {playerLife -=5;lifeMeterChange(lifeMeter, playerLife);changeStats("Ship damage!");} } if (theShip.hitTestObject(powerUp)) {powerUp.alpha -= .08;} if (theShip.hitTestObject(enemyOneBaby) && enemyOneBaby.alpha > 0.2) { if (playerLife > 0) {playerLife -=5;lifeMeterChange(lifeMeter, playerLife);changeStats("Ship damage!");} } var alphaMargin:Number = playerLife -15; theShip.alpha = alphaMargin/100 + .17; if (playerLife < 35 && playerLife > 0) {playerLife -= .05;lifeMeterChange(lifeMeter, playerLife);changeStats("Critical ship damage!");} else {playerLife = playerLife;} if (playerLife < 1) {stopGame();changeStats("Your ship has been evaporated!");} if (enemyOne.alpha <= 0 && enemyTwo.alpha <= 0 && enemyThree.alpha <= 0) {resetEnemysAndTimer();} } if (pellet.y == theShip.y - 20) {pellet.alpha = 0;} else {pellet.alpha += .05;} if (pelletTwo.y == theShip.y) {pelletTwo.alpha = 0;} else {pelletTwo.alpha += .05;} if (pelletThree.y == theShip.y) {pelletThree.alpha = 0;} else {pelletThree.alpha += .05;} } private function firePelletHandler(event:MouseEvent):void { mouseActive = "yes"; if (shotDistance > 20 && pelletTwoGo == "no") {pelletTwoGo = "yes";Timer(shotGo).reset();changeStats("2/3 powered shot");shotNoise.play();} if (pelletTwoGo == "yes" && pelletTwo.y < theShip.y) {pelletThreeGo = "yes";Timer(shotGo).reset();changeStats("3/3 powered shot");shotNoise.play();} if (shotGo.running == false) {Timer(shotGo).reset();Timer(shotGo).start();} } private function keyboardFirePellet():void { /* this is for the keyboard event space bar 32 */ if (shotDistance > 20 && pelletTwoGo == "no") {pelletTwoGo = "yes";Timer(shotGo).reset();changeStats("2/3 powered shot");shotNoise.play();} if (pelletTwoGo == "yes" && pelletTwo.y < theShip.y) {pelletThreeGo = "yes";Timer(shotGo).reset();changeStats("3/3 powered shot");shotNoise.play();} if (shotGo.running == false) {Timer(shotGo).reset();Timer(shotGo).start();} } private function seeShot(event:TimerEvent):void { shotDistance += 20; } private function resetShot(event:TimerEvent):void { shotDistance = 20; pelletTwoGo = "no";pelletThreeGo = "no"; } } }
Complex AS3 form
 


The Code:      object types/classes  events  properties, methods, declarative words  functions/operational methods


Overview:
This form shows the beginnings of a complex AS3 form.

We start by adding the display of the form.
In this case embeded images are used to give the input boxes a little shadow effect.
(The flash.filters package could be used to accomplish the same effect.)
Unlike the basic form, this form uses a self made function to make some of the
TextFields instead of repeating the same thing over.

To help ensure the form is used only in the wrapper, a check of the loaderInfo.url is done,
and a JavaScript function in the wrapper is set up to be the real trigger for posting.
Simple validation of the input is done before posting.

A server request is defiend, and a loader for it; headers and variables are added,
then the data goes to a server page and a function gets the response from the server.
(In the basic form the data was simply sent to another page)


package { import flash.display.Sprite; import flash.display.Graphics; import flash.net.URLRequest; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.URLVariables; import flash.net.URLRequestHeader; import flash.net.URLRequestMethod; import flash.text.TextField; import flash.text.TextFormat; import flash.text.TextFormatAlign; import flash.text.TextFieldType; import flash.text.TextFieldAutoSize; import flash.events.Event; import flash.events.MouseEvent; import flash.events.IOErrorEvent; import flash.external.ExternalInterface; public class ComplexForm extends Sprite { private var firstWordField:TextField; private var lastWordField:TextField; private var emailField:TextField; private var commentlField:TextField; private var theTXTFormat:TextFormat = new TextFormat(); private var errorTXT:TextField; private var noCacheHeader:URLRequestHeader = new URLRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate"); private var cacheControlHeader:URLRequestHeader = new URLRequestHeader("Cache-Control", "post-check=0, pre-check=0"); private var expiresHeader:URLRequestHeader = new URLRequestHeader("Expires", "Tue, 24 April 1994 04:00:00 GMT"); private var pragmaHeader:URLRequestHeader = new URLRequestHeader("Pragma", "no-cache"); private var myHome:String = loaderInfo.url; /* if this file were loaded by another swf we would use loaderInfo.loaderURL instead */ [Embed(source="../testimages/shadeinbox.png")] private var BoxBack:Class; [Embed(source="../testimages/shadeinboxcm.png")] private var CommentBoxBack:Class; public function ComplexForm() { theTXTFormat.font = "Arial"; theTXTFormat.color = 0x000000; theTXTFormat.size = 12; theTXTFormat.align = TextFormatAlign.LEFT; var fnLabelTXT:TextField = new TextField(); fnLabelTXT.selectable = false; fnLabelTXT.text = "First Name:"; fnLabelTXT.x = 10; fnLabelTXT.y = 20; addChild(fnLabelTXT); var fwBox:Sprite = new Sprite(); fwBox.addChild(new BoxBack()); firstWordField = makeATXTField(TextFieldType.INPUT, 20, 20, 150); fwBox.addChild(firstWordField); fwBox.x = fnLabelTXT.x;fwBox.y = fnLabelTXT.y + 15; addChild(fwBox); var lnLabelTXT:TextField = new TextField(); lnLabelTXT.selectable = false; lnLabelTXT.text = "Last Name:"; lnLabelTXT.x = fwBox.x; lnLabelTXT.y = fwBox.y + 25; addChild(lnLabelTXT); var lwBox:Sprite = new Sprite(); lwBox.addChild(new BoxBack()); lastWordField = makeATXTField(TextFieldType.INPUT, 20, 20, 150); lwBox.addChild(lastWordField); lwBox.x = lnLabelTXT.x; lwBox.y = lnLabelTXT.y + 15; addChild(lwBox); var emLabelTXT:TextField = new TextField(); emLabelTXT.selectable = false; emLabelTXT.text = "Email:"; emLabelTXT.x = fnLabelTXT.x + emLabelTXT.width + 70; emLabelTXT.y = fnLabelTXT.y; addChild(emLabelTXT); var eBox:Sprite = new Sprite(); eBox.addChild(new BoxBack()); emailField = makeATXTField(TextFieldType.INPUT, 35, 20, 150, false, "a-zA-Z@."); eBox.addChild(emailField); eBox.x = emLabelTXT.x; eBox.y = emLabelTXT.y + 15; addChild(eBox); var cmLabelTXT:TextField = new TextField(); cmLabelTXT.selectable = false; cmLabelTXT.text = "Comments:"; cmLabelTXT.x = eBox.x; cmLabelTXT.y = eBox.y + 25; addChild(cmLabelTXT); var cBox:Sprite = new Sprite(); cBox.addChild(new CommentBoxBack()); commentlField = makeATXTField(TextFieldType.INPUT, 100, 70, 170, true, "a-zA-Z0-9 "); cBox.addChild(commentlField); cBox.x = cmLabelTXT.x; cBox.y = cmLabelTXT.y + 15; addChild(cBox); var submitButton:Sprite = new Sprite(); submitButton.graphics.lineStyle(1, 0x000000); submitButton.graphics.beginFill(0x000000, .2); submitButton.graphics.drawRect(0, 0, 40, 17); submitButton.buttonMode = true; var subTXT:TextField = new TextField(); subTXT.selectable = false; subTXT.text = "Submit"; submitButton.x = lwBox.x; submitButton.y = lwBox.y + 33; subTXT.x = submitButton.x +2;subTXT.y=submitButton.y; submitButton.addEventListener(MouseEvent.CLICK, subStartHandler); addChild(subTXT); addChild(submitButton); /* I've called the response text field errorTXT because any post errors would be shown in it as well and the text color is red */ errorTXT = new TextField(); errorTXT.autoSize = TextFieldAutoSize.LEFT; errorTXT.selectable = false; errorTXT.textColor = 0xFF0000; errorTXT.text = ""; errorTXT.x = submitButton.x; errorTXT.y = submitButton.y + 43; addChild(errorTXT); } private function makeATXTField(tftype:String, tfmax:Number, tfh:Number, tfw:Number, tfmulti:Boolean = false, tfrestrict:String = "a-zA-Z", tftxt:String = ""):TextField { var fieldToCreate:TextField = new TextField(); fieldToCreate.type = tftype; fieldToCreate.defaultTextFormat = theTXTFormat; fieldToCreate.maxChars = tfmax; fieldToCreate.border = true; fieldToCreate.height = tfh; fieldToCreate.width = tfw; fieldToCreate.wordWrap = true; fieldToCreate.multiline = tfmulti; fieldToCreate.restrict = tfrestrict; fieldToCreate.background = false; fieldToCreate.backgroundColor = 0xFFFFFF; fieldToCreate.text = tftxt; return(fieldToCreate); } private function subStartHandler(event:MouseEvent):void { errorTXT.text = "posting"; var shouldBeThis:RegExp = /http:[\/]{2}[w\.\/]{0,}actiontad[\.\/]{1}/i; if (!myHome.match(shouldBeThis)) {errorTXT.text = "wrong location "+myHome;} else { if (ExternalInterface.available) { ExternalInterface.addCallback("backfromjs", validateTXT); ExternalInterface.call("outtojs"); } else {errorTXT.text = "No external interface available.";} } } private function validateTXT(fname:String = "", lname:String = "", themail:String = "", comms:String = ""):void { fname = firstWordField.text; lname = lastWordField.text; themail = emailField.text; comms = commentlField.text; var badWords:RegExp = /f[ ]{0,}u[ ]{0,}c[ ]{0,}k|s[ ]{0,}h[ ]{0,}i[ ]{0,}t|b[ ]{0,}itch|a[ ]{0,}s[ ]{0,}s/i; var anEmail:RegExp = /[0-9]{0,}[a-z]{4,21}[0-9]{0,}[\@]{1}[a-z]{3,}[\.]{1}[comnetrgdu]{3}/i; if (fname.length < 3) {errorTXT.text = "First name must be 3 or more letters";return;} if (lname.length < 3) {errorTXT.text = "Last name must be 3 or more letters";return;} if (themail.length > 0 && !themail.match(anEmail)) {errorTXT.text = "Email must be valid.";return;} var allFieldsTXT:String = ""+fname+lname+themail+comms+""; if (allFieldsTXT.match(badWords)) {errorTXT.text = "No bad words please.";return;} doSubmit(fname, lname, themail, comms); } private function doSubmit(frn:String, lsn:String, em:String, commen:String):void { var holdResponse:URLLoader = new URLLoader(); holdResponse.addEventListener(Event.COMPLETE, computeResponse); holdResponse.addEventListener(IOErrorEvent.IO_ERROR, sayError); var theHeaders:Array /* of URLRequestHeader */ = [noCacheHeader, cacheControlHeader, expiresHeader, pragmaHeader]; var theRequest:URLRequest = new URLRequest("responsivepage.php"); var varsToSend:URLVariables = new URLVariables(); varsToSend.frname = frn; varsToSend.lsname = lsn; varsToSend.emailis = em; varsToSend.comments = commen; theRequest.data = varsToSend; theRequest.method = URLRequestMethod.POST; theRequest.requestHeaders = theHeaders; holdResponse.load(theRequest); } private function computeResponse(event:Event):void { var theResponse:URLLoader = URLLoader(event.target); errorTXT.text = theResponse.data+""; } private function sayError(event:IOErrorEvent):void { errorTXT.text = "There was an error while posting."; } } }

The JavaScript code used with this example:
//this is the function called from the form

function outtojs()
{
//complexer is the id of the swf object in this case
tellingflash("complexer");
}

//tads js-to-as communication try catch function
//this is used for backwards compatability
//and to ensure that js to swf communication will happen in most browsers
//please see the wrappers section for more info on this

function tellingflash(thisid)
{

  try
  {
  var fcontenter=window.document.getElementById(thisid);
  }
  catch(e)
  {
    try
    {
     var fcontenter=window.document.thisid;
    }
    catch(e)
    {
       var movie=thisid;
       
       if (navigator.appName.indexOf("Microsoft")!=-1 || navigator.appName.indexOf("MSIE")!=-1)
       { 
          if (window.document[movie])
          {var fcontenter=window.document[movie];}
          else
          {var fcontenter=window[movie];};
       }else{
         if (document.embeds[movie])
         {var fcontenter=document.embeds[movie];}
         else
         {var fcontenter=document[movie];};
       }
    }
  }
  try
  {
  fcontenter.backfromjs();
  }
  catch(e)
  {
    //nothing happens, in this case, if communication fails
    var nojstoflerthreeas="yes";
  }
}



The php code used with this example:
responsivepage.php

<?php
if (isset($_POST["frname"]))
{
 //of course one would do something with frname and the rest of the data
 //like put it in a database
 //but this is just to show you what the server is doing in this case
  //and also it is important to note that you should always validate any input
  echo("Your information has been posted.");
  exit;

}
?>

JavaScript from AS3
 


The Code:      Object types  events  properties, methods, declarative words  functions/operational methods

package
{
    
    import flash.display.Sprite;
    import flash.display.Graphics;
    import flash.external.ExternalInterface;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.text.TextFieldType;
    
    
    public class ActionScriptToJavaScript extends Sprite 
    {
        
        private var wordInput:TextField;
        
        
        public function ActionScriptToJavaScript()
        {
            
            
            wordInput = new TextField();
            wordInput.type = TextFieldType.INPUT; 
            wordInput.maxChars = 20;
            wordInput.border = true;
            wordInput.restrict = "a-z";
            wordInput.height = 20;
            wordInput.width = 120;
            wordInput.background = true;
            wordInput.backgroundColor = 0xFFFFFF;
            addChild(wordInput);
            
            
            var theButton:Sprite = new Sprite();
            theButton.graphics.lineStyle(0x000000);
            theButton.graphics.beginFill(0x000000, .2);
            theButton.graphics.drawRect(0, 0, 85, 20);
            theButton.buttonMode = true;
            
            var ButtonTXT:TextField = new TextField();
            ButtonTXT.selectable = false;
            ButtonTXT.text = "alert my words";
            
            theButton.x = wordInput.x+130;
            ButtonTXT.x = theButton.x+5;
            
            addChild(ButtonTXT);
            addChild(theButton);
            
            theButton.addEventListener(MouseEvent.CLICK, doAlertHandler);
            
        }
        
        private function doAlertHandler(event:MouseEvent):void 
        {
            
            if (ExternalInterface.available)
            {ExternalInterface.call("alertthese", wordInput.text);}
            
        }
        
    }
    
}


The Javascript used with this example :
function alertthese(words)
{
alert(words);
}


Race car basics: simple speed simulation
 


The Code:      object types/classes  events  properties, methods, declarative words  functions/operational methods
package
{
    
    import flash.display.Sprite;
    import flash.display.DisplayObject;
    import flash.display.Graphics;
    import flash.events.TimerEvent;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.utils.Timer;
    import flash.text.TextField;
    
    [SWF(width = '500', height = '550')]
    
    /* a (t)a.d as3 tutorial */

    
    public class RaceCarBasics extends Sprite 
    {
        
        [Embed(source="carstart.png")]
        private var TheCar:Class;
        
        private var carPicture:DisplayObject = new TheCar();
        
        [Embed(source="grass1.jpg")]
        private var GrassOnePicture:Class;
        
        [Embed(source="grass2.jpg")]
        private var GrassTwoPicture:Class;
        
        [Embed(source="grass3.jpg")]
        private var GrassThreePicture:Class;
        
        [Embed(source="street.jpg")]
        private var TheStreet:Class;
        
        private var roadway:DisplayObject = new TheStreet();
        
        private var grassOneA:DisplayObject = new GrassOnePicture();
        private var grassOneB:DisplayObject = new GrassOnePicture();
        private var grassTwoA:DisplayObject = new GrassTwoPicture();
        private var grassTwoB:DisplayObject = new GrassTwoPicture();
        private var grassThreeA:DisplayObject = new GrassThreePicture();
        private var grassThreeB:DisplayObject = new GrassThreePicture();
        
        
        
        private var bounds:Sprite = new Sprite();
        private var roadLines:Sprite = new Sprite();
        private var roadLinesMirror:Sprite = new Sprite();
        private var carSpeed:Number = 5;
        private var theRoad:Sprite = new Sprite();
        private var slowDown:Timer = new Timer(500, 15);
        private var speedUp:Timer = new Timer(500, 15);
        private var stillDriving:Boolean = false;
        private var yourCar:Sprite = new Sprite();
        private var MPHField:TextField = new TextField();
        private var grassDelay:Number = 500;
        private var grassMove:Timer;
        
        public function RaceCarBasics()
        {
            
            grassMove = new Timer(grassDelay, 0);
            
            theRoad.graphics.lineStyle(2, 0x000000);
            theRoad.graphics.drawRect(0, 0, 500/2, 550+10);
            theRoad.x = 500/2 - theRoad.width/2;theRoad.y = -2;
            this.addChild(theRoad);
            
            roadway.x = theRoad.x;
            this.addChild(roadway);
            
            grassOneA.x = theRoad.x - grassOneA.width;
            grassTwoA.x = grassOneA.x;
            grassThreeA.x = grassTwoA.x;
            this.addChild(grassThreeA);
            this.addChild(grassTwoA);
            this.addChild(grassOneA);
            grassOneB.x = theRoad.x + theRoad.width;
            grassTwoB.x = grassOneB.x;
            grassThreeB.x = grassTwoB.x;
            this.addChild(grassThreeB);
            this.addChild(grassTwoB);
            this.addChild(grassOneB);
            
            roadLinesMirror.graphics.lineStyle(1, 0x000000);
            roadLinesMirror.graphics.beginFill(0xFFFFFF);
            
            roadLines.graphics.lineStyle(1, 0x000000);
            roadLines.graphics.beginFill(0xFFFFFF);
            
            
            for (var i:int = 0; i<550; i += 25)
            {roadLines.graphics.drawRect(0, i, 5, 15);
            roadLinesMirror.graphics.drawRect(0, i, 5, 15);}
            
            roadLines.x = 500/2 - roadLines.width/2;roadLines.y = 0;
            this.addChild(roadLines);
            
            roadLinesMirror.x = 500/2 - roadLinesMirror.width/2;
            roadLinesMirror.y = 0-roadLinesMirror.height-10;
            this.addChild(roadLinesMirror);
            
            yourCar.addChild(carPicture);
            yourCar.x = 500/2 - yourCar.width/2+42;
            yourCar.y = 550-115;
            this.addChild(yourCar);
            
            MPHField.text = "MPH: ";
            MPHField.y = 35;
            MPHField.x = theRoad.x + 25;
            this.addChild(MPHField);
            
            stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPresses);
            stage.addEventListener(KeyboardEvent.KEY_UP, keyReleases);
            slowDown.addEventListener(TimerEvent.TIMER, slowIt);
            speedUp.addEventListener(TimerEvent.TIMER, speedIt);
            stage.addEventListener(Event.ENTER_FRAME, movementGovern);
            
            grassMove.addEventListener(TimerEvent.TIMER, theGrassMovement);
        }
        
        
        private function theGrassMovement(event:TimerEvent):void 
        {
            
            swapChildren(grassOneA, grassTwoA);swapChildren(grassOneB, grassTwoB);
            swapChildren(grassTwoA, grassThreeA);swapChildren(grassTwoB, grassThreeB);
            
            
        }
        
        private function slowIt(event:TimerEvent):void 
        {
            
            if (carSpeed >= 6)
            {carSpeed -= 1;}
            
        }
        
        
        private function speedIt(event:TimerEvent):void 
        {
            
            if (carSpeed <= 15)
            {carSpeed += 1;}
            
        }
        
        
        private function movementGovern(event:Event):void 
        {
            
            grassDelay = Number(300 - Math.floor(carSpeed*20));
            if (stillDriving == true)
            {roadLines.y += carSpeed;roadLinesMirror.y += carSpeed;grassMove.start();}
            else


            {
                if (slowDown.running!=false)
                {roadLines.y += carSpeed;roadLinesMirror.y += carSpeed;}
                else 
                {grassMove.stop();}
            }
            
            if (roadLines.y > 550)
            {roadLines.y = 0;roadLinesMirror.y = 0-roadLinesMirror.height-10;}
            
            var themph:String = carSpeed-5 +"0";
            MPHField.text = "MPH: "+themph;
            
        }
        
        
        
        private function keyReleases(event:KeyboardEvent):void 
        {
            
            if (event.keyCode == 38)
            {
                stillDriving = false;
                if (speedUp.running == true)
                {speedUp.stop();speedUp.reset();}
                if (slowDown.running == false)
                {slowDown.reset();slowDown.start();}
                else 
                {slowDown.stop();slowDown.reset();slowDown.start();}
            }
            
        }
        
        
        
        private function keyPresses(event:KeyboardEvent):void 
        {
            
            var thekey:String = "" + event.keyCode + "";
            if (thekey == "38" || thekey == "37" || thekey == "39")
            {
                
                if (thekey == "38") {
                    if (slowDown.running == true)
                    {slowDown.stop();slowDown.reset();}
                    stillDriving = true;
                    if (speedUp.running == false)
                    {speedUp.reset();speedUp.start();}
                }
                
                if (thekey == "37")
                {yourCar.x -= 10;}
                
                if (thekey == "39")
                {yourCar.x += 10;}
                
            }
            
            
            if (thekey == "40")
            {roadLines.y -= carSpeed;roadLinesMirror.y -= carSpeed;stillDriving = false;}
            
            if (thekey == "40" && roadLines.y < 0)
            {roadLines.y = 550;roadLinesMirror.y = 550-roadLinesMirror.height-10;}
            
            
        }
        
        
        
        
        
        
    }
    
}

Basic Sound Mixing
 


The Code:      Object types  events  properties, methods, declarative words  functions/operational methods
package 
{
    
    import flash.display.Sprite;
    import flash.display.Graphics;
    import flash.display.GradientType;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.events.TimerEvent;
    import flash.media.Sound;
    import flash.media.SoundTransform;
    import flash.media.SoundMixer;
    import flash.media.SoundChannel;
    import flash.geom.Rectangle;
    import flash.geom.Matrix;
    import flash.utils.Timer;
    import flash.utils.ByteArray;
    import flash.text.TextField;
    import flash.ui.Mouse;
    
    [SWF(backgroundColor = '#c8c8c8', width = '500', height = '500')]
    
    
    public class SimpleSoundMixer extends Sprite  
    {
        
        [Embed(source="soundsers.mp3")]
        private var TheAmbience:Class;
        
        private var ambience:Sound = new TheAmbience();
        
        [Embed(source="drumsers.mp3")]
        private var TheDrums:Class;
        
        private var drums:Sound = new TheDrums();
        
        private var animationTimer:Timer = new Timer(100, 0);
        
        private var mixerTop:Sprite = new Sprite();
        
        private var mixerBottom:Sprite = new Sprite();
        
        private var theMixHolder:Sprite = new Sprite();
        
        private var ambienceControl:SoundChannel = new SoundChannel();
        private var drumControl:SoundChannel = new SoundChannel();
        
        private var ambienceVolume:Number = 0.5;
        private var drumsVolume:Number = 0.8;
        
        private var soundPan:Number = 0;
        
        private var volumeOneLine:Sprite;private var volumeOneFader:Sprite;
        private var volumeTwoLine:Sprite;private var volumeTwoFader:Sprite;
        
        private var ambienceTransform:SoundTransform;
        private var drumsTransform:SoundTransform;
        
        
        public function SimpleSoundMixer() 
        {
            
            /* to change volume and control each sound */

            ambienceTransform = new SoundTransform(ambienceVolume, soundPan);
            drumsTransform = new SoundTransform(drumsVolume, soundPan);
            
            /* top part of mixer box */
            mixerTop.graphics.lineStyle(0, 0x000000);
            mixerTop.graphics.drawRect(0, 0, 256, 100);
            mixerTop.x = 500/2-mixerTop.width/2; mixerTop.y=10;
            
            /* bottom part of mixer box */

            mixerBottom.graphics.lineStyle(0, 0x000000);
            mixerBottom.graphics.drawRect(0, 0, 256, 230);
            mixerBottom.x=mixerTop.x;mixerBottom.y=mixerTop.y+mixerTop.height;
            addChild(mixerTop);addChild(mixerBottom);
            
            /* the mix hold positions the graph
            the graph will be inside of theMixHolder */

            theMixHolder.x=mixerTop.x;
            theMixHolder.y=mixerBottom.y;
            addChild(theMixHolder);            
            
            /* catcher for whem mouse not over a fader yet fader still dragging */
            var catchMouse:* = new Sprite();
            catchMouse.graphics.beginFill(0xc8c8c8, 0.1);
            catchMouse.graphics.drawRect(0, 0, mixerBottom.width, mixerBottom.height);
            catchMouse.x=mixerBottom.x;catchMouse.y=mixerBottom.y;
            catchMouse.addEventListener(MouseEvent.MOUSE_UP, volumeStopMoveHandler);
            addChild(catchMouse);
            
            
            /* volume lines and faders */

            volumeOneLine=makeAVolumeLine();
            volumeOneLine.x=mixerBottom.x+25;volumeOneLine.y=mixerBottom.y+35;
            addChild(volumeOneLine);
            
            volumeTwoLine=makeAVolumeLine();
            volumeTwoLine.x=volumeOneLine.x+50;volumeTwoLine.y=volumeOneLine.y;
            addChild(volumeTwoLine);
            
            volumeOneFader=makeAFader();
            volumeOneFader.x=volumeOneLine.x-volumeOneFader.width/2;volumeOneFader.y=volumeOneLine.y+ambienceVolume*100;
            addChild(volumeOneFader);
            
            volumeTwoFader=makeAFader();
            volumeTwoFader.x=volumeTwoLine.x-volumeTwoFader.width/2;volumeTwoFader.y=volumeTwoLine.y+drumsVolume*100;
            addChild(volumeTwoFader);
            
            var soundLabel:* = new TextField();
            soundLabel.selectable = false;
            soundLabel.text = "synth";soundLabel.height = 20;
            soundLabel.x = volumeOneLine.x - 15;
            soundLabel.y = volumeOneLine.y - 20;
            soundLabel.addEventListener(MouseEvent.MOUSE_OVER, volumeStopMoveHandler);
            addChild(soundLabel);
            
            var drumLabel:* = new TextField();
            drumLabel.selectable = false;drumLabel.height = 20;
            drumLabel.text = "drums";
            drumLabel.x = volumeTwoLine.x - 15;
            drumLabel.y = volumeTwoLine.y - 20;
            drumLabel.addEventListener(MouseEvent.MOUSE_OVER, volumeStopMoveHandler);
            addChild(drumLabel);
            
            
            /* play and stop buttons */

            var playButton:Sprite = new Sprite();
            playButton.graphics.beginFill(0x6495ed);
            playButton.graphics.lineStyle(0, 0x000000);
            playButton.graphics.moveTo(0, 0);
            playButton.graphics.lineTo(0, 12);
            playButton.graphics.lineTo(10, 6);
            playButton.graphics.lineTo(0, 0);
            playButton.graphics.endFill();
            playButton.buttonMode = true;
            playButton.x = volumeTwoLine.x + 75;
            playButton.y = volumeTwoLine.y;
            
            addChild(playButton);
            playButton.addEventListener(MouseEvent.CLICK, playHandler);
            
            
            var stopButton:Sprite = new Sprite();
            stopButton.graphics.beginFill(0x000000);
            stopButton.graphics.lineStyle(0, 0x000000);
            stopButton.graphics.drawRect(0, 0, 10, 10);
            stopButton.graphics.endFill();stopButton.buttonMode = true;
            
            stopButton.x = playButton.x;
            stopButton.y = playButton.y +25;
            addChild(stopButton);
            stopButton.addEventListener(MouseEvent.CLICK, stopHandler);
            
            
            /* all other events added */

            volumeOneFader.addEventListener(MouseEvent.MOUSE_DOWN, volumeMoveHandler);
            volumeOneFader.addEventListener(MouseEvent.MOUSE_UP, volumeStopMoveHandler);
            volumeOneFader.addEventListener(MouseEvent.CLICK, volumeStopMoveHandler);
            
            volumeTwoFader.addEventListener(MouseEvent.MOUSE_DOWN, volumeMoveHandler);
            volumeTwoFader.addEventListener(MouseEvent.MOUSE_UP, volumeStopMoveHandler);
            volumeTwoFader.addEventListener(MouseEvent.CLICK, volumeStopMoveHandler);
            
            /* volume control */

            addEventListener(Event.ENTER_FRAME, volumeControl);            
            
            /* initialize */
            startsounds();
            
            animationTimer.addEventListener(TimerEvent.TIMER, makeMixBars);
            drums.addEventListener(Event.SOUND_COMPLETE, stopBars);
            animationTimer.start();
            
            
        }
        
        private function playHandler(event:MouseEvent):void 
        {
                if (animationTimer.running == false)
                {startsounds();animationTimer.start();}
        }
        
        private function stopHandler(event:MouseEvent):void 
        {
             
                if (animationTimer.running == true)
                {ambienceControl.stop();drumControl.stop();animationTimer.stop();}         
        }
        
        private function startsounds():void 
        {
            /* add each sound to its own channel
            and set them playing from the beginning, and to loop 500 times
            using their individual soundTransform objects */

            
            ambienceControl = ambience.play(0, 500, ambienceTransform);
            drumControl = drums.play(0, 500, drumsTransform);
        }
        
        
        private function makeAFader():Sprite 
        {
            var vfader:Sprite = new Sprite();
            vfader.graphics.lineStyle(0, 0x6495ed);
            vfader.graphics.beginFill(0x000000);
            vfader.graphics.drawRect(0, 0, 30, 5);
            vfader.buttonMode = true;
            return(vfader);
        }
        
        
        private function makeAVolumeLine():Sprite 
        {
            var voline:Sprite = new Sprite();
            voline.graphics.lineStyle(1, 0x000000);
            voline.graphics.lineTo(0, 100);
            return(voline);
        }
        
        
        private function volumeStopMoveHandler(e:MouseEvent):void 
        {
            volumeOneFader.stopDrag();
            volumeTwoFader.stopDrag();
        }
        
        
        private function volumeMoveHandler(event:MouseEvent):void 
        {
            var xposition:Number =  
            (event.target.x == volumeOneFader.x) ? volumeOneLine.x-event.target.width/2 : volumeTwoLine.x-event.target.width/2;
            var draglock:Rectangle = 
            new Rectangle(xposition, volumeOneLine.y, volumeOneLine.width, volumeOneLine.height);
            event.target.startDrag(true, draglock);
        }
        
        
        
        private function volumeControl(e:Event):void 
        {
            /* 145 is the top y position of each volume line
            each volume line has a length of 100
            so at the bottom of each volume line the y position is 245
            
            the vfader y number gets greator as the fader moves down
            so at the bottom it is 245 minus 245
            at the top 245 minus 145 */

            
            var synthvol:Number = 245-volumeOneFader.y;
            var drumsvol:Number = 245-volumeTwoFader.y;
            
            /* convert to decimal */

            
            drumsVolume = drumsvol/100;
            ambienceVolume = synthvol/100;
            
            /* apply the above to each sounds volume
            the faders y position can fall below zero
            so have volume just stay at zero and not below
            this happens on enter frame thereby changing volume levels */
            
            ambienceTransform.volume = ambienceVolume<=0 ? 0 : ambienceVolume;
            ambienceControl.soundTransform = ambienceTransform;
            
            drumsTransform.volume = drumsVolume<=0 ? 0 : drumsVolume;
            drumControl.soundTransform = drumsTransform;
        }
        
        
        private function makeMixBars(event:TimerEvent):void 
        {
            var soundbytes:ByteArray = new ByteArray();
            /* the computeSpectrum method is doing most of the work for the graph
            returning the sound playing as binary data
            either a frequency spectrum  true
            or the raw wave data  false */

            SoundMixer.computeSpectrum(soundbytes, true, 0);
            
            var gra:Graphics = theMixHolder.graphics;
            gra.clear();gra.lineStyle(0, 0x6495ed);
            
            /* draw bars to go along with the bytes
            giving the bars a gradient top via the Matrix and beginGradientFill methods */
            
            var coluni:Array /* of hex values */ = [0x000000, 0x6495ed];
            var gramatrix:Matrix = new Matrix();
            
            var sh:*;
            for (var i:int = 0; i < 256; i+=4) {
                sh = (soundbytes.readFloat() * 95);
                gramatrix.createGradientBox(i, -sh-3, Math.PI/2, 0, 0);
                gra.beginGradientFill(GradientType.LINEAR, coluni, [1, 1], [127, 255], gramatrix);
                gra.drawRect(i, 0, 4, -sh-3);
            }
            
            gra.endFill();
            
        }
        
        
        
        private function stopBars(event:Event):void  
        {
            animationTimer.stop();           
        }
        
        
        
    }
    
}



AS3 wrapper to server and back bridge via ExternalInterface
 


The Code:      object types/classes  events  properties, methods,
declarative words
  functions/operational methods



Overview:
This is a basic example of using a swf file as a bridge between the server and the wrapper.
Doing things this way is much like ajax.

The same methodology is used by this section to change content.
The banner above acting as the bridge to the database that holds each example.


The example below shows just the basics of an AS3 bridge method.
Because the swf is used only as a bridge, its size does not matter, neither does its visibility.
In this example the swf is a little square just so you can see it.

package { import flash.display.Sprite; import flash.external.ExternalInterface; import flash.events.Event; import flash.net.URLRequest; import flash.net.URLLoader; import flash.net.URLVariables; import flash.net.URLRequestMethod; public class ActionScriptBridge extends Sprite { public function ActionScriptBridge() { if (ExternalInterface.available) { /* we are using this file only as the transport between wrapper and server in the wrapper a function will be set up to call jsinitiate */ ExternalInterface.addCallback("jsinitiate", theBridge); } else { /* external interface fallback options would go here */ } } private function theBridge(thisFile:String):void { var getThis:URLLoader = new URLLoader(); getThis.addEventListener(Event.COMPLETE, showDataGot); var theVars:URLVariables = new URLVariables(); theVars.needforpost="avar"; var theRequest:URLRequest = new URLRequest(thisFile); theRequest.data=theVars; theRequest.method = URLRequestMethod.POST; getThis.load(theRequest); } private function showDataGot(event:Event):void { /* this function gives the response to the wrapper by calling thedatagot with the response as the arg */ var dataGot:URLLoader = URLLoader(event.target); ExternalInterface.call("thedatagot", dataGot.data); } } }

The JavaScript used with this example:
function bridgecrosser(thisfile)
{

  try
  {
  var fcontenterj=window.document.getElementById('tbridge');
  }
  catch(e)
  {
    try
    {
     var fcontenterj=window.document.tbridge;
    }
    catch(e)
    {
       var movie=tbridge;
       
       if (navigator.appName.indexOf("Microsoft")!=-1 || navigator.appName.indexOf("MSIE")!=-1)
       { 
          if (window.document[movie])
          {var fcontenterj=window.document[movie];}
          else
          {var fcontenterj=window[movie];};
       }else{
         if (document.embeds[movie])
         {var fcontenterj=document.embeds[movie];}
         else
         {var fcontenterj=document[movie];};
       }
    }
  }
  try
  {
  fcontenterj.jsinitiate(thisfile);
  }
  catch(e)
  {
    var nojstoflerthreeas="yes";
  }
}

function getinputthencross()
{

var firstnum = document.getElementById("fnum").value;
var secondnum = document.getElementById("snum").value;

bridgecrosser("responsivepage.php?numf="+firstnum+"&nums="+secondnum);

}


function thedatagot(fjdata)
{

document.getElementById('fjholder').innerHTML=fjdata;

}

The php used with this example:
if (isset($_GET["numf"]) && isset($_GET["nums"]))
{

$firstn=strip_tags(urldecode($_GET["numf"]));
$secn=strip_tags(urldecode($_GET["nums"]));

//validation...

$additionre = $firstn + $secn;
$subtractre = $firstn-$secn;
$multiplyre = $firstn*$secn;

echo("your numbers when: <br>added = ".$additionre."<br>subtracted = ".$subtractre."<br>multiplyed = ".
$multiplyre."<br><br> the epox time is now: ".time());
exit;

}

The Action (t)ad animation
 


The Code:      Object types  events  properties, methods, declarative words  functions/operational methods
package
{
    
    import flash.display.Sprite;
    import flash.events.TimerEvent;
    import flash.utils.Timer;
    
    public class atadAnimation extends Sprite 
    {
        
        private var atadMain:Timer = new Timer(100, 19);
        private var glowTimer:Timer = new Timer(100, 78);
        private var loopTime:Number = 0;
        private var fromTtoA:Timer = new Timer(100, 9);
        
        
        [Embed(source="pieces/1ani.swf")]
        private var The1ani:Class;
        
        private var ani1er:Sprite = new The1ani();
        
        [Embed(source="pieces/2ani.swf")]
        private var The2ani:Class;
        
        private var ani2er:Sprite = new The2ani();
        
        [Embed(source="pieces/a.swf")]
        private var Thea:Class;
        
        private var aer:Sprite = new Thea();
        
        [Embed(source="pieces/ad.swf")]
        private var Thead:Class;
        
        private var ader:Sprite = new Thead();
        
        [Embed(source="pieces/c.swf")]
        private var Thec:Class;
        
        private var cer:Sprite = new Thec();
        
        [Embed(source="pieces/d.swf")]
        private var Thed:Class;
        
        private var der:Sprite = new Thed();
        
        [Embed(source="pieces/firstt.swf")]
        private var Thefirstt:Class;
        
        private var firstter:Sprite = new Thefirstt();
        
        [Embed(source="pieces/i.swf")]
        private var Thei:Class;
        
        private var ier:Sprite = new Thei();
        
        [Embed(source="pieces/leftb.swf")]
        private var Theleftb:Class;
        
        private var leftber:Sprite = new Theleftb();
        
        
        [Embed(source="pieces/n.swf")]
        private var Thenn:Class;
        
        private var ner:Sprite = new Thenn();
        
        
        [Embed(source="pieces/o.swf")]
        private var Theo:Class;
        
        private var oer:Sprite = new Theo();
        
        [Embed(source="pieces/on.swf")]
        private var Theon:Class;
        
        private var oner:Sprite = new Theon();
        
        [Embed(source="pieces/rightb.swf")]
        private var Therightb:Class;
        
        private var rightber:Sprite = new Therightb();
        
        [Embed(source="pieces/t.swf")]
        private var Thet:Class;
        
        private var ter:Sprite = new Thet();
        
        [Embed(source="pieces/spacelight.swf")]
        private var Thesp:Class;
        
        private var sper:Sprite = new Thesp();
        
        
        [Embed(source="pieces/glow1.swf")]
        private var Thegone:Class;
        
        private var glowone:Sprite = new Thegone();
        
        
        [Embed(source="pieces/glow2.swf")]
        private var Thegtwo:Class;
        
        private var glowtwo:Sprite = new Thegtwo();
        
        
        [Embed(source="pieces/glow3.swf")]
        private var Thegtree:Class;
        
        private var glowtree:Sprite = new Thegtree();
        
        
        [Embed(source="pieces/glow4.swf")]
        private var Thegfour:Class;
        
        private var glowfour:Sprite = new Thegfour();
        
        
        
        
        
        public function atadAnimation()
        {
            
            /* note: This is also an example of setting up a file to be loaded by another.
To do so, one must do away with all stage references.
When loaded by another swf that loader swf is the parent and it has the stage.
There can only be one stage, so after this file is loaded by a parent swf,
it is the parents stage that is holding 'this' child. 
So to be sure of child placement we use this.addChildAt.
'this' to refer to the current display object container, not the stage.
And in this way even when this file is loaded by another swf, it will display properly,
and run on its own as a child. */

            
            
            /* the animation sequence order
            ani1er ani2er cer firstter ier oer oner ner sper leftber ter rightber aer ader der ader aer             rightber ter */
            
            
            this.addChildAt(ani1er, 0);
            
            this.addChildAt(ani2er, 1);
            
            this.addChildAt(cer, 2);
            
            this.addChildAt(firstter, 3);
            
            this.addChildAt(ier, 4);
            
            this.addChildAt(oer, 5);
            
            this.addChildAt(oner, 6);
            
            this.addChildAt(ner, 7);
            
            this.addChildAt(sper, 8);
            
            this.addChildAt(leftber, 9);
            
            this.addChildAt(ter, 10);
            
            this.addChildAt(rightber, 11);
            
            this.addChildAt(aer, 12);
            
            this.addChildAt(ader, 13);
            
            this.addChildAt(der, 14);
            
            
            this.addChildAt(glowone, 15);
            this.addChildAt(glowtwo, 16);
            this.addChildAt(glowtree, 17);
            this.addChildAt(glowfour, 18);
            
            makeAllNotVisible();
            
            atadMain.addEventListener(TimerEvent.TIMER, goMainAnimation);
            glowTimer.addEventListener(TimerEvent.TIMER, doTheGlow);
            fromTtoA.addEventListener(TimerEvent.TIMER, goFromTtoA);
            atadMain.addEventListener(TimerEvent.TIMER_COMPLETE, function ():void {glowTimer.start();} );
            atadMain.start();
            
        }
        
        
        private function goMainAnimation(e:TimerEvent):void 
        {
            
            loopTime = 0;
            var animationCount:Number = e.target.currentCount;
            
            /* first 15 children */

            var aniStart:Number = 15 - animationCount;
            
            var aniEnd:Number = 14 - aniStart;
            
            var endNum:Number;
            
            for (var vi:int=0;vi<=19;vi++)
            {
                
                /* from the a to the d */

                if (vi==aniEnd && vi<=14) {this.getChildAt(vi).alpha=1;}
                else

                {if (vi<=14 && vi!=aniEnd && aniEnd<=14) {this.getChildAt(vi).alpha=0;} }
                /* into the parens */ 
                if (vi==15)endNum=2;
                if (vi==16)endNum=4;
                if (vi==17)endNum=6;
                if (vi==18)endNum=8;
                if (vi>=15 && vi==aniEnd) {this.getChildAt(vi-endNum+1).alpha=0;this.getChildAt(vi-endNum).alpha=1;}
                /* end on the t in the parens */

                if (vi==18 && aniEnd==18)this.getChildAt(10).alpha=1;
                
            }
            
            
            
        }
        
        
        private function goFromTtoA(ta:TimerEvent):void 
        {
            
            switch (ta.target.currentCount) 
            {
              case 1:
              { 
                makeGlow(10, 9);
                break;
              }
              case 2:
              { 
                makeGlow(9, 8);
                break;
              }
              case 3:
              { 
                makeGlow(8, 7);
                break;
              }
              case 4:
              { 
                makeGlow(7, 6);
                break;
              }
              case 5:
              { 
                makeGlow(6, 5);
                break;
              }
              case 6:
              { 
                makeGlow(5, 4);
                break;
              }
              case 7:
              { 
                makeGlow(4, 3);
                break;
              }
              case 8:
              { 
                makeGlow(3, 2);
                break;
              }
              case 9:
              { 
                makeGlow(2, 1);atadMain.start();
                break;
              }
            }
            
            
        }
        
        
        
        private function makeGlow(tpof:Number, bton:Number):void 
        {
            
            this.getChildAt(tpof).alpha = 0;
            this.getChildAt(bton).alpha = 1;
            
        }
        
        
        private function doTheGlow(eg:TimerEvent):void 
        {
            
            var theCount:Number = eg.target.currentCount;
            
            switch (theCount) 
            {
              case 1: 
	      {
                makeGlow(10, 15);
                break;
              }
              case 2: 
              {
                makeGlow(15, 16);
                break;
              }
              case 3: 
              {
                makeGlow(16, 17);
                break;
              }
              case 4: 
              {
                makeGlow(17, 18);
                break;
              }
              case 5: 
              {
                makeGlow(18, 17);
                break;
              }
              case 6: 
              {
                makeGlow(17, 16);
                break;
              }
              case 7: 
              {
                makeGlow(16, 15);
                break;
              }
              case 8: 
              {
                makeGlow(15, 10);
                break;
              }
            }
            
            
            if (theCount==70)
            {
                
                loopTime += 1;
                if (loopTime<=2)
                {
                 atadMain.reset();fromTtoA.stop();fromTtoA.reset();glowTimer.stop();
                 glowTimer.reset();glowTimer.start();
                }
                else


                {
                 eg.target.stop();eg.target.reset();atadMain.stop();
                 atadMain.reset();fromTtoA.stop();fromTtoA.reset();fromTtoA.start();
                }
                
            }
            
            
        }
        
        
        
        private function makeAllNotVisible():void 
        {
            var allImages:Number = this.numChildren;
            for (var i:int = 0;i<allImages;i++)
            {this.getChildAt(i).alpha=0;}
            
        }
        
        
        
    }
    
    
}


About the author
 


a bit on me:
Bachelor Comm. Arts
Working with Flash and ActionScript since '01
Coding since seventh grade