logo
468x60-2-495


  • Home
  • Privacy Policy
  • About
search
Feb 20, 2011 Posted on Feb 20, 2011 in Hints and Tips | 10 comments

Protect Your Flash Files From Decompilers by Using Encryption

Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+. This tutorial was first published in February, 2010.

In this tutorial I will demonstrate a technique I use to protect code and assets from theft.

Decompilers are a real worry for people who create Flash content. You can put a lot of effort into creating the best game out there, then someone can steal it, replace the logo and put it on their site without asking you. How? Using a Flash Decompiler. Unless you put some protection over your SWF it can be decompiled with a push of a button and the decompiler will output readable source code.


Before We Begin

I used a small project of mine to demonstrate how vulnerable SWFs are to decompilation. You can download it and test yourself via the source link above. I used Sothink SWF Decompiler 5 to decompile the SWF and look under its hood. The code is quite readable and you can understand and reuse it fairly easily.


What Can We do About it?

I came up with a technique for protecting SWFs from decompilers and I’m going to demonstrate it in this tutorial. We should be able to produce this:

The code that is decompiled is actually the code for decrypting the content and has nothing to do with your main code. Additionally, the names are illegal so it won’t compile back. Try to decompile it yourself.

Before we get going, I want to point out that this tutorial is not suitable for beginners and you should have solid knowledge of AS3 if you want to follow along. This tutorial is also about low level programming that involves bytes, ByteArrays and manipulating SWF files with a hex editor.

Here’s what we need:

  • A SWF to protect. Feel free to download the SWF I’ll be working on.
  • Flex SDK. We will be using it to embed content using the Embed tag. You can download it from opensource.adobe.com.
  • A hex editor. I’ll be using a free editor called Hex-Ed. You can download it from nielshorn.net or you can use an editor of your choice.
  • A decompiler. Whilst not necessary, it would be nice to check if our protection actually works. You can grab a trial of Sothink SWF Decompiler from sothink.com

Step 1: Load SWF at Runtime

Open a new ActionScript 3.0 project, and set it to compile with Flex SDK (I use FlashDevelop to write code). Choose a SWF you want to protect and embed it as binary data using the Embed tag:

[Embed (source = "VerletCloth.swf", mimeType = "application/octet-stream")]
// source = path to the swf you want to protect
private var content:Class;

Now the SWF is embedded as a ByteArray into the loader SWF and it can be loaded through Loader.loadBytes().

var loader:Loader = new Loader();
addChild(loader);
loader.loadBytes(new content(), new LoaderContext(false, new ApplicationDomain()));

In the end we should have this code:

package
{
    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.system.ApplicationDomain;
    import flash.system.LoaderContext;

    [SWF (width = 640, height = 423)] //the dimensions should be same as the loaded swf's
    public class Main extends Sprite
    {
        [Embed (source = "VerletCloth.swf", mimeType = "application/octet-stream")]
        // source = path to the swf you want to protect
        private var content:Class;

        public function Main():void
        {
            var loader:Loader = new Loader();
            addChild(loader);
            loader.loadBytes(new content(), new LoaderContext(false, new ApplicationDomain()));
        }
    }

}

Compile and see if it works (it should). From now on I will call the embedded SWF the “protected SWF”, and the SWF we just compiled the “loading SWF”.


Step 2: Analyze the Result

Let’s try to decompile and see if it works.

Yey! The assets and the original code are gone! What’s shown now is the code that loads the protected SWF and not its content. This would probably stop most of the first-time attackers who are not too familiar with Flash but it’s still not good enough to protect your work from skilled attackers because the protected SWF is waiting for them untouched inside the loading SWF.


Step 3: Decompressing the SWF

Let’s open the loading SWF with a hex editor:

It should look like random binary data because it’s compressed and it should begin with ASCII “CWS”. We need to decompress it! (If your SWF begins with “FWS” and you see meaningful strings in the SWF it’s likely that it didn’t get compressed. You have to enable compression to follow along).

At first it might sound difficult but it’s not. The SWF format is an open format and there is a document that describes it. Download it from adobe.com and scroll down to page 25 in the document. There is a description of the header and how the SWF is compressed, so we can uncompress it easily.

What is written there is that the first 3 bytes are a signature (CWS or FWS), the next byte is the Flash version, the next 4 bytes are the size of the SWF. The remaining is compressed if the signature is CWS or uncompressed if the signature is FWS. Let’s write a simple function to decompress a SWF:

private function decompress(data:ByteArray):ByteArray
{
    var header:ByteArray = new ByteArray();
    var compressed:ByteArray = new ByteArray();
    var decompressed:ByteArray = new ByteArray();

    header.writeBytes(data, 3, 5); //read the uncompressed header, excluding the signature
    compressed.writeBytes(data, 8); //read the rest, compressed

    compressed.uncompress();

    decompressed.writeMultiByte("FWS", "us-ascii"); //mark as uncompressed
    decompressed.writeBytes(header); //write the header back
    decompressed.writeBytes(compressed); //write the now uncompressed content

    return decompressed;
}

The function does a few things:

  1. It reads the uncompressed header (the first 8 bytes) without the signature and remembers it.
  2. It reads the rest of the data and uncompresses it.
  3. It writes back the header (with the “FWS” signature) and the uncompressed data, creating a new, uncompressed SWF.

Step 4: Creating a Utility

Next we’ll create a handy utility in Flash for compressing and decompressing SWF files. In a new AS3 project, compile the following class as a document class:

package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.net.FileFilter;
    import flash.net.FileReference;
    import flash.utils.ByteArray;

    public class Compressor extends Sprite
    {
        private var ref:FileReference;

        public function Compressor()
        {
            ref = new FileReference();
            ref.addEventListener(Event.SELECT, load);
            ref.browse([new FileFilter("SWF Files", "*.swf")]);
        }

        private function load(e:Event):void
        {
            ref.addEventListener(Event.COMPLETE, processSWF);
            ref.load();
        }

        private function processSWF(e:Event):void
        {
            var swf:ByteArray;
            switch(ref.data.readMultiByte(3, "us-ascii"))
            {
                case "CWS":
                    swf = decompress(ref.data);
                    break;
                case "FWS":
                    swf = compress(ref.data);
                    break;
                default:
                    throw Error("Not SWF...");
                    break;
            }

            new FileReference().save(swf);
        }

        private function compress(data:ByteArray):ByteArray
       {
            var header:ByteArray = new ByteArray();
            var decompressed:ByteArray = new ByteArray();
            var compressed:ByteArray = new ByteArray();

            header.writeBytes(data, 3, 5); //read the header, excluding the signature
            decompressed.writeBytes(data, 8); //read the rest

            decompressed.compress();

            compressed.writeMultiByte("CWS", "us-ascii"); //mark as compressed
            compressed.writeBytes(header);
            compressed.writeBytes(decompressed);

            return compressed;
        }

        private function decompress(data:ByteArray):ByteArray
        {
            var header:ByteArray = new ByteArray();
            var compressed:ByteArray = new ByteArray();
            var decompressed:ByteArray = new ByteArray();

            header.writeBytes(data, 3, 5); //read the uncompressed header, excluding the signature
            compressed.writeBytes(data, 8); //read the rest, compressed

            compressed.uncompress();

            decompressed.writeMultiByte("FWS", "us-ascii"); //mark as uncompressed
            decompressed.writeBytes(header); //write the header back
            decompressed.writeBytes(compressed); //write the now uncompressed content

            return decompressed;
        }

    }

}

As you probably noticed I’ve added 2 things: File loading and the compress function.

The compress function is identical to the decompress function, but in reverse. The file loading is done using FileReference (FP10 required) and the loaded file is either compressed or uncompressed. Note that you have to run the SWF locally from a standalone player, as FileReference.browse() must be invoked by user interaction (but the local standalone player allows to run it without).


Step 5: Uncompressing the Loading SWF

To test the tool, fire it up, select the loading SWF and choose where to save it. Then open it up with a hex editor and scrub through. You should see ascii strings inside like this:


Step 6: Analyze Again

Let’s return back to step 2. While the decompiler didn’t show any useful info about the protected SWF, it’s quite easy to get the SWF from the now uncompressed loader; just search for the signature “CWS” (if the protected SWF is uncompressed search for “FWS”) and see the results:

What we found is a DefineBinaryData tag that contains the protected SWF, and extracting it from there is a piece of cake. We are about to add another layer of protection over the loading SWF : Encryption.


Step 7: Encryption

To make the protected SWF less “accessible” we will add some kind of encryption. I chose to use as3crypto and you can download it from code.google.com. You can use any library you want instead (or your own implementation, even better), the only requirement is that it should be able to encrypt and decrypt binary data using a key.


Step 8: Encrypting Data

The first thing we want to do is write a utility to encrypt the protected SWF before we embed it. It requires very basic knowledge of the as3crypto library and it’s pretty straightforward. Add the library into your library path and let’s begin by writing the following:

var aes:AESKey = new AESKey(binKey);
var bytesToEncrypt:int = (data.length & ~15); //make sure that it can be devided by 16, zero the last 4 bytes
for (var i:int = 0; i < bytesToEncrypt; i += 16)
        aes.encrypt(data, i);

What’s going on here? We use a class from as3crypto called AESKey to encrypt the content. The class encrypts 16 bytes in a time (128-bit), and we have to for-loop over the data to encrypt it all. Note the second line : data.length & ~15. It makes sure that the number of bytes encrypted can be divided by 16 and we don’t run out of data when calling aes.encrypt().

Note: It’s important to understand the point of encryption in this case. It’s not really encryption, but rather obfuscation since we include the key inside the SWF. The purpose is to turn the data into binary rubbish, and the code above does it’s job, although it can leave up to 15 unencrypted bytes (which doesn’t matter in our case). I’m not a cryptographer, and I’m quite sure that the above code could look lame and weak from a cryptographer’s perspective, but as I said it’s quite irrelevant as we include the key inside the SWF.


Step 9: Encryption Utility

Time to create another utility that will help us encrypt SWF files. It’s almost the same as the compressor we created earlier, so I won’t talk much about it. Compile it in a new project as a document class:

package
{
    import com.hurlant.crypto.symmetric.AESKey;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.net.FileReference;
    import flash.utils.ByteArray;

    public class Encryptor extends Sprite
    {
        private var key:String = "activetuts"; //I hardcoded the key
        private var ref:FileReference;

        public function Encryptor()
        {
            ref = new FileReference();
            ref.addEventListener(Event.SELECT, load);
            ref.browse();
        }

        private function load(e:Event):void
        {
            ref.addEventListener(Event.COMPLETE, encrypt);
            ref.load();
        }

        private function encrypt(e:Event):void
        {
            var data:ByteArray = ref.data;

            var binKey:ByteArray = new ByteArray();
            binKey.writeUTF(key); //AESKey requires binary key

            var aes:AESKey = new AESKey(binKey);
            var bytesToEncrypt:int = (data.length & ~15); //make sure that it can be divided by 16, zero the last 4 bytes
            for (var i:int = 0; i < bytesToEncrypt; i += 16)
                aes.encrypt(data, i);

            new FileReference().save(data);
        }

    }

}

Now run it, and make an encrypted copy of the protected SWF by selecting it first and then saving it under a different name.


Step 10: Modifying the Loader

Return back to the loading SWF project. Because the content is now encrypted we need to modify the loading SWF and add decryption code into it. Don’t forget to change the src in the Embed tag to point to the encrypted SWF.

package
{
    import com.hurlant.crypto.symmetric.AESKey;
    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.system.ApplicationDomain;
    import flash.system.LoaderContext;
    import flash.utils.ByteArray;

    [SWF (width = 640, height = 423)] //the dimensions should be same as the loaded swf's
    public class Main extends Sprite
    {
        [Embed (source = "VerletClothEn.swf", mimeType = "application/octet-stream")]
        // source = path to the swf you want to protect
        private var content:Class;

        private var key:String = "activetuts";

        public function Main():void
        {
            var data:ByteArray = new content();

            var binKey:ByteArray = new ByteArray();
            binKey.writeUTF(key); //AESKey requires binary key

            var aes:AESKey = new AESKey(binKey);
            var bytesToDecrypt:int = (data.length & ~15); //make sure that it can be divided by 16, zero the last 4 bytes
            for (var i:int = 0; i < bytesToDecrypt; i += 16)
                aes.decrypt(data, i);

            var loader:Loader = new Loader();
            addChild(loader);
            loader.loadBytes(data, new LoaderContext(false, new ApplicationDomain()));
        }
    }

}

This is the same as before except with the decryption code stuck in the middle. Now compile the loading SWF and test if it works. If you followed carefully up to now, the protected SWF should load and display without errors.


Step 11: Look Inside Using a Decompiler

Open the new loading SWF with a decompiler and have a look.

It contains over a thousand lines of tough looking encryption code, and it’s probably harder to get the protected SWF out of it. We’ve added a few more steps the attacker must undertake:

  1. He (or she) has to find the DefineBinaryData that holds the encrypted content and extract it.
  2. He must create a utility to decrypt it.

The problem is that creating a utility is as simple as copy-pasting from the decompiler into the code editor and tweaking the code a little bit. I tried to break my protection myself, and it was quite easy – I managed to do it in about 5 minutes. So we’re going to have to take some measurements against it.


Step 12: String Obfuscation

First we’d put the protected SWF into the loading SWF, then encrypted it, and now we’ll put the final touches to the loading SWF. We’ll rename classes, functions and variables to illegal names.

By saying illegal names I mean names such as ,;!@@,^#^ and (^_^). The cool thing is that this matters to the compiler but not to the Flash Player. When the compiler encounters illegal characters inside identifiers, it fails to parse them and thus the project fails to compile. On the other hand, the Player doesn’t have any problems with those illegal names. We can compile the SWF with legal identifiers, decompress it and rename them to a bunch of meaningless illegal symbols. The decompiler will output illegal code and the attacker will have to go over the hundreds of lines of code manually, removing illegal identifiers before he can compile it. He deserves it!

This is how it looks before any string obfuscation:

Let’s start! Decompress the loading SWF using the utility we created before and fire up a hex editor.


Step 13: Your First Obfuscation

Let’s try to rename the document class. Assuming you’ve left the original name (Main), let’s search for it in the uncompressed loader SWF with a hex editor:

Rename “Main” to ;;;;. Now search for other “Main”s and rename them to ;;;; too.

When renaming make sure that you don’t rename unnecessary strings or the SWF will not run.

Save and run the SWF. It works! And look what the decompiler says:

Victory!! :)


Step 14: Renaming the Rest of the Classes

Keep renaming the rest of your classes. Choose a class name and search for it, replacing it with illegal symbols until you reach the end of the file. As I said, the most important thing here is to use your common sense, make sure you don’t mess your SWF up. After renaming the classes you can start renaming the packages. Note that when renaming a package, you can erase the periods too and make it one long illegal package name. Look what I made:

After you finish renaming the classes and the packages, you can start renaming functions and variables. They are even easier to rename as they usually appear only once, in one large cloud. Again, make sure you rename only “your” methods and not the built-in Flash methods. Make sure you don’t wipe out the key (“activetuts” in our case).


Step 15: Compress the SWF

After you finish renaming you would probably want to compress the SWF so it will be smaller in size. No problem, we can use the compressing utility we created before and it will do the job. Run the utility, select the SWF and save it under another name.


Conclusion: Have a Final Look

Open it one last time and have a look. The classes, the variables and the method names are obfuscated and the protected SWF is somewhere inside, encrypted. This technique could be slow to apply at first, but after a few times it takes only a few minutes.

A while ago I created an automatic utility to inject the protected SWF for me into the loading SWF, and it worked fine. The only problem is that if it can be injected using an automatic utility, it can be decrypted using another utility, so if the attacker makes a utility for that he will get all your SWF easily. Because of this I prefer to protect the SWFs manually each time, adding a slight modification so it would be harder to automate.

Another nice application of the technique is Domain locking. Instead of decrypting the SWF with a constant string you can decrypt it with the domain the SWF is currently running on. So instead of having an if statement to check the domain, you can introduce a more powerful way to protect the SWF from placement on other sites.

Last thing, you may want to replace the encryption code with your own implementation. Why? We invested efforts in making the crypto code illegal, but the code we use is from a popular open source library and the attacker could recognize it as such. He will download a clean copy, and all the obfuscation work is rendered unnecessary. On the other hand, using your own implementation will require him to fix all the illegal names before he can continue.


Other Protection Methods

Because SWF theft is a big problem in the Flash world, there are other options for protecting SWFs. There are numerous programs out there to obfuscate AS on the bytecode level (like Kindisoft’s secureSWF). They mess up the compiled bytecode and when the decompiler attempts to output code it will fail, and even crash sometimes. Of course this protection is better in terms of security but it costs $$$, so before choosing how to protect your SWF consider the amount of security needed. If it’s about protecting a proprietary algorithm your 50-employee Flash studio has been developing for the past two years, you may consider something better then renaming the variables. On the other hand if you want to prevent the kiddies from submitting false high scores you may consider using this technique.

What I like about this technique is the fact that your protected SWF is left untouched when run. AS obfuscation tampers with the byte code and it could possibly damage the SWF and cause bugs (although I haven’t encountered any myself).

That’s all for today, hope you enjoyed the tutorial and learned something new! If you have any questions feel free to drop a comment.



View full post on Activetuts+

Jan 24, 2011 Posted on Jan 24, 2011 in Hints and Tips | 0 comments

Quick Tip: Auto Tab Between TextFields Using AS3

This Quick Tip will show you how to implement an Auto Tab between text fields. Doing so will set focus on the next defined text field when the maximum number of characters have been introduced in the previous one. Let’s get going!


Final Result Preview

Let’s take a look at the final result we will be working towards:


Step 1: Brief Overview

A series of TextFields will be placed on the stage, as well as a button. Using the length property we will check the maximum number of characters allowed in each field and change the active TextField using the focus property. The button will be hidden by default and revealed when all textfields are complete.


Step 2: Set up Your Flash File

Launch Flash and create a new Flash Document, set the stage size to 400x200px and the frame rate to 24fps.

Flash AS3 change textfield focus


Step 3: Interface

Flash AS3 change textfield focus

This is the interface we’ll be using, it includes three Input TextFields and a button. The TextFields are named txt1, txt2, and txt3 from left to right and the button is named okButton.

In order for the code to work, you need to set the Max Chars option in the Properties Panel of each TextField, in this example these numbers are 3, 3, and 4, respectively.

Recreate the interface yourself, or use the Source FLA.


Step 4: ActionScript

Create a new ActionScript Class (Cmd+N), save the file as Main.as and start writing:

package
{
	import flash.display.Sprite;
	import flash.events.KeyboardEvent;

	public class Main extends Sprite
	{
		public function Main():void
		{
			okButton.visible = false; //Hide the okButton
			stage.addEventListener(KeyboardEvent.KEY_UP, checkTextField); //Listen for key presses
		}

		private function autoTab(...textfields):void //Use the rest argument to include any number of textfields
		{
			var txtLen:int = textfields.length; //Declare the length of the textfields used

			for (var i:int = 0; i < txtLen; i++)
			{
				if (textfields[i].length == textfields[i].maxChars)
				{
					stage.focus = textfields[i + 1]; //Change focus to next textfield in the array
				}
				if (textfields[txtLen - 1].length == textfields[txtLen - 1].maxChars) //checks for the last textfield in the array
				{
					okButton.visible = true; //show the button
				}
			}
		}

		private function checkTextField(e:KeyboardEvent):void
		{
			autoTab(txt1, txt2, txt3); //executes the function every key press
		}
	}
}

This code checks the maximum number of characters allowed in each textfield, these fields are introduced in the autoTab function as parameters, then the focus changes if the max number is reached. If the last textfield in the parameters array is completed, the submit button is revealed.

The key line is stage.focus = textfields[i + 1];.

Again, don’t forget to set the Max Chars option in the Properties Panel of the TextField.


Step 5: Document Class

Remember to add the class name to the Class field in the Publish section of the Properties panel.

Flash AS3 change textfield focus

Conclusion

Try the demo and experiment with the uses of this feature!

I hope you liked this tutorial, thank you for reading!



View full post on Activetuts+

Jan 20, 2011 Posted on Jan 20, 2011 in Hints and Tips | 0 comments

Quick Tip: Change the Frame Rate at Runtime Using ActionScript 3

Dive into this Quick Tip and discover how to change the Frame Rate of your movie, while it’s running…


Final Result Preview

Let’s take a look at the final result we will be working towards:


Step 1: Brief Overview

We’ll make use of a Slider component to modify the stage framerate property and display a MovieClip to see the changes.


Step 2: Set Up Your Flash File

Launch Flash and create a new Flash Document, set the stage size to 400x200px and the frame rate to 25fps.


Step 3: Interface

This is the interface we’ll be using, it includes a Slider Component and a MovieClip taken from my Apple Preloader tutorial.

You’ll also notice some static text below the slider indicating the minimum and maximum FPS.


Step 4: Slider

Open the Components Panel (Cmd+F7) and drag the Slider component from the User Interface folder, align it to the center in the stage and click the Properties Panel to edit its parameters.

Use the data from the image above and prepare for some ActionScript 3…


Step 5: ActionScript

Create a new ActionScript Class (Cmd+N), save the file as Main.as and start writing:

package
{
	import flash.display.Sprite;
	import fl.events.SliderEvent;

	public class Main extends Sprite
	{
		public function Main():void
		{
			//Listen for slider movement
			slider.addEventListener(SliderEvent.CHANGE, changeFPS);
		}

		private function changeFPS(e:SliderEvent):void
		{
			//Change the frame rate using the slider value
			stage.frameRate = e.value;
		}
	}
}

Step 6: Document Class

Remember to add the class name to the Class field in the Publish section of the Properties panel.


Conclusion

Try the demo and experiment with the uses of this feature!

I hope you liked this Quick Tip, thank you for reading!



View full post on Activetuts+

Jan 5, 2011 Posted on Jan 5, 2011 in Hints and Tips | 0 comments

Quick Tip: Receive Output in the Browser Using Flash Tracer

In this really quick, but invaluable tip, we’ll look at how to view the output of your Flash movie trace calls in the browser.


Step 1: What is Flash Tracer?

Flash Tracer is a Firefox add-on. It lets you view the output of the trace() method used in your flash movies in the browser. This can be very helpful when testing your application online using browser related tasks like ExternalInterface for example.


Step 2: Requirements

To use Flash Tracer you will need Firefox 2.0 or later and the Flash Player Debug version installed. You can view a list of the available Flash Players at the Flash Player Support site.


Step 3: Features

Besides displaying the output generated, Flash Tracer supports other basic features like:

Pros:

  • Live Filters: Lets you filter the output using basic patterns.
  • Custom Styles: Applies a custom CSS formating to the output.

Step 4: Download it!

You can get Flash Tracer using the Mozilla add-ons website or at the author’s site.


Step 5: Testing

Time to try a SWF file to test Flash Tracer.

Select a file that outputs a value and navigate to it using Firefox to see the result:


Conclusion

This is an easy way to test your applications in the browser and still receive the output from trace calls, try it!

Thank you for reading!



View full post on Activetuts+

Dec 25, 2010 Posted on Dec 25, 2010 in Hints and Tips | 0 comments

Quick Tip: Create a Minimalistic SandClock Using ActionScript 3

Read through the easy steps in this Quick Tip to create a Minimalistic SandClock with ActionScript.


Final Result Preview

Let’s take a look at the final result we will be working towards:


Step 1: Brief Overview

Using Arrays and a premade square MovieClip we will create a SandClock that will be animated by a Timer.


Step 2: Set Up Your Flash File

Launch Flash and create a new Flash Document, set the stage size to 400x250px and the frame rate to 24fps.


Step 3: Interface

This is the interface we’ll be using, the squares in the image are actually one single blue square MovieClip exported for use with ActionScript, with a linkage name of Square. A simple button named startButton will be used to build and start the clock.


Step 4: ActionScript

Create a new ActionScript Class (Cmd+N), save the file as Main.as and write the following lines. Read through the comments in the code in order to fully understand the class behavior.

package
{
	import flash.display.Sprite;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import flash.events.MouseEvent;

	public class Main extends Sprite
	{
		private var clockArray:Array = [15,13,11,9,7,3,1];//Stores the number of squares per line
		private var top:Array = []; //will hold the squares on the top part of the sandclock
		private var container:Sprite = new Sprite(); //stores all the movieclips
		private var containerCopy:Sprite = new Sprite(); //will duplicate the top part to make the bottom
		private var timer:Timer = new Timer(1000); //a timer executed every second
		private var counter:int = 0; //will count the seconds, used to stop the timer

		public function Main():void
		{
			startButton.addEventListener(MouseEvent.MOUSE_UP, buildClock);//a listener in the start button
		}

		private function buildClock(e:MouseEvent):void
		{
			startButton.removeEventListener(MouseEvent.MOUSE_UP, buildClock); //disables the button
			startButton.enabled = false;

			var clockLength:int = clockArray.length;

			/* this double for browses through the clock array length AND the value of each array element
				creating 7 lines (length) of squares with 15, 13, 11(element value) and so on  */

			for (var i:int = 0; i < clockLength; i++)
			{
				for (var j:int = 0; j < clockArray[i]; j++)
				{
					var s:Square = new Square();
					var sc:Square = new Square();

					s.x = 70.5 + (s.width * j) + (1 * j) + (i * (s.width + 1));
					s.y = 84.5 + (s.height + 1) * i;
					sc.x = s.x;
					sc.y = s.y;

					if (i >= 5)
					{
						s.x = 70.5 + (s.width * j) + (1 * j) + (i * ((s.width) + 1)) + (s.width * 2 - 4);
						sc.x = s.x;
					}

					container.addChild(s);
					containerCopy.addChild(sc); //creates a copy for the bottom part

					top.push(s);
					sc.alpha = 0.2; //makes the bottom part semi transparent
				}

				addChild(container);

				containerCopy.x = 225; //positions and rotates the bottom part
				containerCopy.y = 247;
				containerCopy.rotation = 180;

				addChild(containerCopy);
			}

			timer.addEventListener(TimerEvent.TIMER, startClock); //start the timer
			timer.start();
		}

		/* this function executes every second, it changes the alpha of the corresponding square to make the sand effect.
			when the time is done stops the timer and calls a function */

		private function startClock(e:TimerEvent):void
		{
			container.getChildAt(counter).alpha = 0.2;
			containerCopy.getChildAt(counter).alpha = 1;
			counter++;

			//60 seconds

			if (counter >= 59)
			{
				timer.stop();
				timer.removeEventListener(TimerEvent.TIMER, startClock);
				timeComplete();
			}
		}

		private function timeComplete():void
		{
			//do something here
		}
	}
}

You can adjust the Timer and the counter value to make the sandclock duration greater or shorter.


Step 5: Document Class

Remember to add the class name to the Class field in the Publish section of the Properties panel.


Conclusion

Why not use this SandClock to give your application or game a nice touch?

I hope you liked this tutorial, thank you for reading!



View full post on Activetuts+

Page 5 of 14« First«...34567...10...»Last »
search search search search search
Find an Article
Categories
  • Flash Video Training
  • Hints and Tips
  • Recommended
Please Support Our Sponsors
Recent Posts
  • The Math and ActionScript of Curves: Drawing Quadratic and Cubic Curves
  • Weekend Lecture: Understanding Games, a Flash Game About Game Design
  • Weekend Lecture: Understanding Games, a Flash Game About Game Design
  • Workshop Coding Challenge: Fix This Breakout Game
  • Enable the Latest AIR SDK in Flash Professional CS5.5+
Tag Cloud
2011 ActionScript Active Activetuts+ Adobe animation Basic Basix Best Build Button Character Create Creating Critique Custom design Effect Effects Files Flash from Game Guide HTML5 Introduction Macromedia Motion Muzzle part Player Premium Professional Quick Silverlight Simple Text Tool Tutorial Tuts+ Tween Using Video website Workshop
About Our Site:

Hey there and welcome to "Flash Video Training Source", a resource for anybody interested in learning more about Adobe's great tool. We feature educational videos, which will help you master Adobe Flash and help you get to know all of its features. We at "Flash Video Training Source" believe that video training and video... more

Why don't you follow us on Twitter and get the latest video tutorials twitted to your account. Just click on the floating twitter bar to your right!

Go Back In Time
May 2012
M T W T F S S
« Apr    
 123456
78910111213
14151617181920
21222324252627
28293031  
Pretty Blank Box
top

Blogroll

  • Development Blog
  • Documentation
  • Plugins
  • Suggest Ideas
  • Support Forum
  • Themes
  • WordPress Planet

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Archives

  • May 2012
  • April 2012
  • March 2012
  • February 2012
  • January 2012
  • December 2011
  • November 2011
  • October 2011
  • September 2011
  • August 2011
  • July 2011
  • June 2011
  • May 2011
  • April 2011
  • March 2011
  • February 2011
  • January 2011
  • December 2010
  • November 2010
  • October 2010
  • September 2010
  • August 2010
  • July 2010
  • June 2010
  • May 2010
  • April 2010
Powered by WordPress  |  Designed by Elegant Themes  |  Lightning Fast Hosting by Site 5 Hosting