31 October 2009

Level Timer code explained



It seems like my code in How To Create Flash Game Level Timer post is not as straightforward as I thought, because it was rejected as Tutorial on one of the directories, so I decided to give detailed explanation of it.

var count:Number = 0;
// this is a counter variable

var maxCount:Number = 75;
// maxCounter is duration of level in seconds

var intervalID:Number;
// Identification variable for repeating interval function

var timerStarted = false;
// variable which tells us if timer has started or not

var temp:Number;
// variable for shortening code writing

// next, we format and display seconds left
if(maxCount < 60) {
// if we have less then 60 seconds,

timeleft.text = "0 : "+maxCount;
// we display '0 minutes' in our Text Field 'timeleft' and concatenate maxCount seconds

} else {
// but if we have more than 60 seconds left

if((maxCount%60)<10) {
// and if we have to display seconds as one cipher number

timeleft.text = Math.floor((maxCount/60))+" : 0"+(maxCount%60);
// we display zero

} else {
// otherways,

timeleft.text = Math.floor((maxCount/60))+" : "+(maxCount%60);
// if we have two cipher number for seconds, we don't display zero

}
}

startlevel.onRelease = function() {
// when click is released on startlevel button

if(!(timerStarted)) {
// if timerStarted variable is false (we don't want to duplicate interval)

intervalID = setInterval(_root, "hronos", 1000);
// we set interval function 'hronos' to repeat once every second to act as counter

timerStarted = true;
// we declare that timer has started

this._alpha = 0;
// and we make invisible startLevel button.
// We chould also remove it from stage!

}
}

function hronos():Void {
// function hronos repeats every second

if(count < maxCount) {
// if counter is still less than maxCounter

count++;
// we increase counter by 1

temp = maxCount - count;
// temp variable holds seconds left until level end

// next piece of code is for formating and displaying purposes,
// same as above except instead maxCount we have temp variable.
if(temp < 60) {
if(temp < 10) {
timeleft.text = "0 : 0"+temp;
} else {
timeleft.text = "0 : "+temp;
}
} else {
if((temp%60)<10) {
timeleft.text = Math.floor((temp/60))+" : 0"+(temp%60);
} else {
timeleft.text = Math.floor((temp/60))+" : "+(temp%60);
}
}
} else {
// if counter is greater than maxCounter

clearInterval(intervalID);
// we clear our interval

timerStarted = false;
// we declare that timer is out of business

count = 0;
// we set counter to 0 so we can use it again

startlevel._alpha = 100;
// and we make startLevel button visible again

}
}

I hope this explanation is clear enough. If you have any questions, don't hesitate to ask.

*_*

0 comments:

 

template by blogger templates