Time (ActionScript 3.0)

1.Open Flash and start a new Flash File (ActionScript 3.0). Now click the Properties tab, set size to 1020 wide x 250 high and the background to black.
2.OK, so the first thing to do would be to get the all the coloured blocks showing. Select frame 1, click the Actions tab, and paste in the following code:
// Setup the X & Y position arrays of all 42 boxes
var boxXs = [0,0,0,90,150,210,90,150,210,90,150,210,300,360,300,360,300,360,450,510,570,450,510,570,450,510,570,660,720,660,720,660,720,810,870,930,810,870,930,810,870,930];
var boxYs = [0,60,120,0,0,0,60,60,60,120,120,120,0,0,60,60,120,120,0,0,0,60,60,60,120,120,120,0,0,60,60,120,120,0,0,0,60,60,60,120,120,120];

// Create a variable for the boxClip as a movieclip
var boxClip:MovieClip;

// Now create new movieclips, name them, fill them with a coloured box & add them to the stage
for(var i = 0; i <= boxXs.length-1; i++) {
boxClip = new MovieClip();
boxClip.name = ‘box’+i;
if (i>=0) {boxClip.graphics.beginFill(0xFF0000)};
if (i>=3) {boxClip.graphics.beginFill(0x00FF00)};
if (i>=12) {boxClip.graphics.beginFill(0x0000FF)};
if (i>=18) {boxClip.graphics.beginFill(0xFFFF00)};
if (i>=27) {boxClip.graphics.beginFill(0x00FFFF)};
if (i>=33) {boxClip.graphics.beginFill(0xFF00FF)};
boxClip.graphics.drawRect(20, 20, 50, 50);
boxClip.graphics.endFill();
stage.addChild(boxClip);
}

// Now position all those boxes X & Y coords
for(i = 0; i < stage.numChildren; i++){
if(stage.getChildAt(i).name!=’root1′) {
stage.getChildAt(i).x = boxXs[i-1];
stage.getChildAt(i).y = boxYs[i-1];
}
}

3.Now when you test the movie (press CTRL+Enter), it will create all of the boxes.

TIX Clock with full display

Pretty cool huh? OK, here’s whats happening:

The first couple of lines creates 2 new arrays – boxXs and boxYs, each containing 42 values.  These values are the X & Y positions of each of the boxes. So, the first box’s X & Y position is 0,0 the next one is 0,60, the next 0,120 and so on. Next we setup a variable called boxClip and set it to be a movieclip, essentially it’s a blank movieclip we’ll be using repeatedly as a starting point in the next bit.

The next section is a for loop which repeats from 0 to the length of the boxXs array, minus one. The reason for doing this is that arrays work from 0 as the first number, so instead of 1-42, think in terms of 0-41, as the for loop will run according to that.  So with the for loop starting from 0 and running to 41 and using ‘i’ to track where we are in the looping, we create a new movieclip based on boxClip and name it ‘box’+i, so they’ll be named box0, box1, box2 and so on.

Next, based on where we are in the repeating process, we’ll decide the colour of the box, so there are 6 if statements, one for each section of blocks – red, green, blue, yellow, cyan and magenta. Depending on the count number in ‘i’, this will determine which colour the newly created box will be. Now it’s decided which colour it needs to be,  we’ll draw a box from 20,20 to 50,50, ie a 30 pixel square, in the chosen colour. Lastly, we’ll end the fill and add that boxClip to the stage.

The thing is, all 42 boxes are in exactly the same place – so the last section is needed to place the boxes according to the values in the boxXs and boxYs arrays. This again is a for loop, which is from 0 to the number of children on the stage (each child being a movieclip we’ve created). However, it will also count a system created ‘root1′ movieclip, so it will actually find 43 children – 1 system movieclip and 42 which we created. Anyway, lets push on.

When we get each child, we set it’s X & Y position according to the same number in the boxXs and boxYs arrays minus 1. So our first box is when i=1 but we want to look at array position 0, so we’ll need to deduct 1 from the count when looking for the position in the arrays.  Lastly, we have an if statement wrapped around this so only if the child isn’t named ‘root1′, we can apply the positioning. This stops anything happening to root1, which we course don’t want to change at all.

4.OK, now we need to actually get the time and make things work. Below all the ActionScript you’ve already inserted, add this:

// Create a new variable as a textfield with no text, position it & add it to the stage
var nTime:TextField = new TextField();
nTime.text = ”;
nTime.x = 480;
nTime.y = 220;
addChild(nTime);

// Give the textfield some styling
var format:TextFormat = new TextFormat();
format.font = ‘Verdana’;
format.size = 12;
format.color = 0xFFFFFF;
nTime.setTextFormat(format);

// Create a variable again as a textfield with no text, this will store the previous time
var oldTime:TextField = new TextField();
oldTime.text = ”;

// Cre`te a function which gets the time and sets it as a the text for our nTime variable
function doTime(event:Event) {
var myTime:Date = new Date();
var nHours:Number = myTime.getHours();
var nMinutes:Number = myTime.getMinutes();
var nSeconds:Number = myTime.getSeconds();
nTime.text = String(nHours) + ‘:’ + String(nMinutes) + ‘:’ + String(nSeconds);
nTime.setTextFormat(format);
}

// Add an event listener to trigger a function each time we enter a frame
addEventListener(Event.ENTER_FRAME,doTime);

Press CTRL+Enter to test the movie and you should find that you now have the time being displayed below your boxes.

Time displayed within Flash

How was this done? Well, firstly, we create a new variable called nTime as a textfield. It gives it no text to display, sets the X & Y position so that it’ll display in roughly the bottom centre and adds it to the stage. The next section builds up a new variable called format as a textformat and applies a verdana 12px white style to it. It then applies this style to our nTime variable, which will set the styling on the textfield. We’ll need to store the previous time as well (we’ll see why shortly), so in much the same way we create a new, blank textfield variable called oldTime and apply it to the stage, though it doesn’t need any styling, so we’ll leave that.

The next section a function called doTime. In this function, we set a new variable called ‘myTime’ and set it’s value to be the date & time right now. When we do that, it will get the full date & time in a long format, such as ‘Sun Oct 24 12:32:27 GMT+0100 2010′. This is obviously a lot more then we need so we create 3 new variables – nHours, nMinutes and nSeconds, setting each one as a specific portion from the long date & time we’ve just established. Now we have exactly what we need to work with, we can set the value of nTime to be the hours, minutes and seconds, seperated by colons. We also set the styling again as it’ll forget it otherwise!

Now we have a function to do exactly what we’d like, we need to trigger it. By adding an event listener to trigger our function, every time it enters a frame, it’ll be repeatedly running that function. So, if you have a frame rate of 12 FPS, it’ll enter our single frame 12 times a second and therefore trigger the event listener (and therefore the function), 12 times per second.

You may notice that the hours, minutes or seconds are single digits. ie, if we’re 7 minutes past the hour,it will show 7 instead of 07. We don’t need to worry about this as the clock is for our testing purposes only and being a single digit will actually be an advantage to us (we’ll see why later).

5.Hopefully all has gone well and you’re now ready to randomly show our boxes according to the time.  Above our last couple of lines of code (the addEventListener lines), add the following (as it’s always best to have all your functions defined before you do any live stuff such as event listeners – that should be last)…

function randomNumber(low:Number, high:Number):Number {
return Math.floor(Math.random() * (1+high-low)) + low; }

function generateUniques(arrayStart,arrayEnd,uniquesNeeded) {
var tempBoxArray:Array = new Array();
for(var a=arrayStart;a<=arrayEnd;a++) {
tempBoxArray.push(a);
}
this['boxesArray'] = new Array();
for(var j=0;j<uniquesNeeded;j++) {
var randNum = randomNumber(0, tempBoxArray.length-1);
this['boxesArray'].push(tempBoxArray[randNum]);
tempBoxArray.splice(randNum,1)
}
for(var m=0;m<(arrayEnd-arrayStart)+1;m++) {
stage.getChildByName(‘box’+[m+arrayStart]).alpha = 0;
}
for(var k=0;k<this['boxesArray'].length;k++) {
stage.getChildByName(‘box’+this['boxesArray'][k]).alpha = 1;
}
}

The first section here is a function which will return us a random number between two numbers we pass it – a low number and a high number. The Math.floor bit is applied after it picks the random number so that the number is reduced downwards to a whole number. For instance, the randomiser may actually pick 5.2665843944996595 as our number but then it’ll reduce that down automatically to 5.

The next section defines another function called generateUniques, which expects 3 values, arrayStart, arayEnd and uniquesNeeded. arrayStart is the first box number, arrayEnd is the last box number and the generateUniques is the number of unique boxes we’d like selected from that range of boxes. So if our numbers were 10, 18, 3 respectively, we’d be wanting to have 3 boxes selected between box 10 and box 18. OK, now to make that happen.

We create a new variable tempBoxArray as an array and fill it with numbers from the startArray number to the endArray number. So, in the case of out 10, 18, 3 example, it will loop from 10 through to 18, ie, 9 times inclusively and ‘push’ our number onto the end of the array. So, by the time it’s finished, tempBoxArray will be 10,11,12,13,14,15,16,17,18.

The next part within this function creates a new variable called ‘boxesArray’ as an array. Next, we have a for loop which will run from 0 up to (but not including) however many uniques we need (in our example case 3). Within this loop we set a new variable called randNum and tell it to be a random number between 0 and however many numbers are in our tempBoxArray (9), by calling our already made function – randomNumber and passing through those numbers to it.

Now we have a uniquely chosen number, we push onto the end of our boxesArray array whatever value is at that position from tempBoxArray. The next line removes that randomly chosen number from tempBoxArray so it can’t be chosen again. In essence, we have a sequence of numbers, are picking a random one from it and transferring it into the other list. In this way, we never pick the same number twice by picking numbers from what remains.

The last couple of for loops here deal with making visible and hiding box numbers selected and stored in our boxesArray. We loop through from 0 to however many numbers we had to choose from initially (ie, 9) and set each box to alpha = 0, which will make all boxes in this range invisible. In our case, it will set that on boxes 10-18. OK, now we’ve reset all those boxes to invisible, the next for loop runs as many times as there numbers in our chosen list and sets those specific chosen boxes to alpha = 1, which will make them visible. ie, if we’ve chosen boxes 12, 14, 17, those numbers will be in boxesArray, so when this loop runs through (3 times), it will set each of those specific boxes to alpha = 1.

6.The last step now would be to pass appropriate numbers to this function according to our time. So, back within our doTime function, after we’ve established the time & displayed it, we want to look at each of the digits in HH:MM:SS and trigger those functions with the values. So, just before the last curly bracket in the doTime function, add the following:

if (oldTime.text!=nTime.text) {
if (String(nHours).length==2){generateUniques(0,2,String(nHours).substring(0,1))}
else {generateUniques(0,2,0)};
if (String(nHours).length==2){generateUniques(3,11,String(nHours).substring(1,2))}
else {generateUniques(3,11,String(nHours))};
if (String(nMinutes).length==2){generateUniques(12,17,String(nMinutes).substring(0,1))}
else {generateUniques(12,17,0)};
if (String(nMinutes).length==2){generateUniques(18,26,String(nMinutes).substring(1,2))}
else {generateUniques(18,26,String(nMinutes))};
if (String(nSeconds).length==2){generateUniques(27,32,String(nSeconds).substring(0,1))}
else {generateUniques(27,32,0)};
if (String(nSeconds).length==2){generateUniques(33,41,String(nSeconds).substring(1,2))}
else {generateUniques(33,41,String(nSeconds))}
oldTime.text=nTime.text;
}

This big if statement states if oldTime doesn’t equal nTime (the current time), then do a whole load of things and then set oldTime.text to whatever nTime.text is (done right at the bottom of this bit of code). This means that this whole if statement only happens once a second, as nTime rolls over to a new value each time a the next second passes, oldTime is no longer the same as it, so it does all of these things and then sets it to be the same value at the end. So, if we have a 12 FPS framerate, with every second that passes, we do these things and set it to be the same, so then for the rest of the second we don’t. ie, 1 of the 12 frames will run all the code and the other 11 don’t. This will stop this code being run 12 times a second and giving people a headache when looking at it! With this code in place it’ll just happen once a second.

OK, so what’s happening within this if statement? Well, we’re looking at each of the 6 digits in HH:MM:SS and have a seperate if statement to deal with it. The first if statement deals with the first digit in the hours, and we’re stating that if the length of nHours is 2 ie, if there are 2 digits, call the generateUniques function to turn off and on boxes from 0 to 2 and the number of boxes to be randomly picked is the first digit from HH. This is done by considering at nHours as a string (so we can work with it) and looking at the character between spaces 0 and 1 (ie, the first character). There is an else statement on this so if there aren’t 2 digits in HH, there must be just one and so by calling generateUniques(0,2,0) we’ll be resetting all boxes and selecting none, which effectively clears that digit of any previous choices.

The next 5 if statements do much the same and deal with the other 5 digits in HH:MM:SS. Each one again considers if there are 1 or 2 digits and passes through specific start & end box numbers along with the number of unique boxes to choose, based on the digit we’ve established (or 0 if there isn’t a digit).

OK, that should be it! Now when you press CTRL+Enter you should see that each of the sections of coloured boxes hides & shows the appropriate number of boxes to display the time.

The finished TIX Clock

Hopefully this has given you an insight into how to do certain things with just a few lines of code and produce a very cool clock in the process.

Time (ActionScript 3.0) Rating: 4.5 Diposkan Oleh: Catatanku