Web games, Flash and Actionscript.

Learning AS2 Classes Part 2

In the last lesson we went over what a class is, touched on the types of functions you can do and created a static class with some commonly used math routines.

This time we’ll get into object based classes.

Object based classes are built the same way as any class. The main difference is in the way you declare and call their functions.

Here is an example of an object class:

class StopWatch {

var brand:String = ‘Timex’;
private var startTime:Number;
private var stopTime:Number;
private var displayTime:String;
private var memory:Number;

function StopWatch()
{

resetTimer();

}

function startTimer()
{

var date:Date = new Date();
if (!this.startTime and !this.stopTime) {

this.startTime = date.getTime();

} else if (this.stopTime) {

this.startTime = date.getTime()-this.memory;
this.stopTime = null;

}

}

function stopTimer()
{

if (!this.stopTime) {

var date:Date = new Date();
this.stopTime = date.getTime();
this.memory = this.stopTime-this.startTime;

}

}

function resetTimer()
{

this.displayTime = “00:00:00.00″;
this.startTime = null;
this.stopTime = null;

}

function readTimer()
{

var total_time:Number;

if (this.startTime) {

if (this.stopTime) {

total_time = this.stopTime - this.startTime;

} else {

var date:Date = new Date();
total_time = date.getTime() - this.startTime;

}
var seconds:Number = total_time/1000;
total_time = (total_time/1000)-seconds;

// round decimals to 2 places
seconds = Math.round(seconds*100)/100;

var minutes:Number = total_time%60;
total_time = (total_time-minutes)/60;

var hours:Number = total_time;

var secondparts:Array = String(seconds).split(”.”);
if (!secondparts[1]) {

secondparts[1] = “00″;

}

var s_seconds:String = formatNumber(secondparts[0])+”.”+formatNumber(secondparts[1]);
var s_minutes:String = formatNumber(minutes);
var s_hours:String = formatNumber(hours);

this.displayTime = s_hours+”:”+s_minutes+”:”+s_seconds;

}

return (this.displayTime);

}

private function formatNumber(number)
{

var string:String = String(number);
while (string.length < 2) {

string = ‘0′+string;

}
return(string);

}

}

This class is the brains of a stopwatch. If you save this into your classpath folder as StopWatch.as you can use it as an object on your timeline (or in other classes ).

Open up a new Flash Movie and put this code on your timeline:

watch = new StopWatch();

Now, anytime you use the variable ‘watch’ on this part of your movie, it will have all the methods and properties of your class.

To see what brand the watch is, run this code:

watch = new StopWatch();

trace(”my watch is a “+watch.brand);

At the start of the StopWatch class you see we have “var brand:String = ‘Timex’;”. Because we didn’t define it as a private var (yes, vars can be private just like functions!), we are able to access it from outside of the class.

The next few lines are our private vars. These keep track of all the timestamps the watch uses to get the nice readable display.

After our variable declarations, we have a function called StopWatch. This function has the same name as the class and it is called a constructor. Constructor functions automatically run whenever you make an instance of the class.

So, when we put “watch = new StopWatch();”, the StopWatch class runs the resetTimer() function, which sets the display time to “00:00:00.00″.

So we now have our var defs and our constructor, the rest of the class contains our methods. You will notice none of the functions have the word ’static’ in them.

Static functions could be thought of as global functions. No matter where in your movie you are, or what variable you are using, they run from the base class and will always behave the same.

Non-static functions are carbon copied for each instance. If you were to add “clock = new StopWatch();”, for example, it would be able to run without effecting any of the settings in ‘watch’.

Additionally, you can’t call non static functions directly through the class; StopWatch.startTimer() would do nothing.

So, lets try this code out on our timeline:

watch = new StopWatch();
trace(”I am starting my “+watch.brand+” watch”);
watch.startTimer();

Key.addListener(this);
onKeyDown = function() {

if (Key.getCode() == Key.SPACE) {

watch.stopTimer();
trace(”You stopped the watch at “+watch.readTimer());
trace(”restarting the timer…”);
watch.resetTimer();
watch.startTimer();

}

}

When you test your movie, an instance of the stopwatch class gets created, it tells you what brand the watch is, and it starts the timer.

When you hit space, the timer is stopped and you are told how much time has passed. Then the timer is reset and started again.

If we change the code to look like this:

watch = new StopWatch();
trace(”I am starting my “+watch.brand+” watch”);
watch.startTimer();

clock = new StopWatch();
trace(”I am starting my “+clock.brand+” clock”);
clock.startTimer();

Key.addListener(this);
onKeyDown = function() {

if (Key.getCode() == Key.SPACE) {

watch.stopTimer();
trace(”You stopped the watch at “+watch.readTimer());
trace(”restarting the watch…”);
watch.resetTimer();
watch.startTimer();

}

if (Key.getCode() == Key.SHIFT) {

clock.stopTimer();
trace(”You stopped the clock at “+clock.readTimer());
trace(”restarting the clock…”);
clock.resetTimer();
clock.startTimer();

}

}

Now we have the same setup, but we have added an instance of StopWatch called ‘clock’, and can control it with the SHIFT key. Testing this script will show you how object based classes use a common rule-set, but run independently.

Grab the sample file for this tutorial and you can see this class in a more practical application.

In the next lesson, we’ll get into extending classes!

1 Comment so far

  1. Joi @ June 9th, 2008

    Ahh, back to the days of CS 251. It’s been some time since I did any serious coding, but once again the fire has been lit for some code binging. Several of the staff guys at hyperfuntime.com are leagues ahead of me and for some reason diss me for using Ruby instead of Python. Sad times.

Leave a reply