Tutorial Details
- Program: Flash
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 you’ll create a reusable Score class that counts up to the new total when points are added (instead of jumping up to the new score). We’ll cover graphics creation as well as code.
Final Result Preview
In some games when you gain points, you’ll see your score immediately jump to the new total. I think it’s much cooler if the score counts up one by one, so the player can “rack up points”. That’s what we’ll be making here.
Here’s an example of the score class in action:
The main idea behind this tutorial is to teach you how to program the “counting up” functionality, but I’ll also show you how to create the cool LED display seen in the preview. We’ll start by designing the numbers:
Step 1: Set up Your Flash File
Create a new Flash file (ActionScript 3.0). Your movie settings will vary depending on your game. For this demo I’m setting up my movie as 500×300, black background, and 30 fps.

Step 2: Create the Digit Symbol
Create a new Movie Clip symbol (Insert > New Symbol). Give this symbol the name “digit”.

Step 3: Create the Digit Text Field
Inside the digit movie clip use the Text tool to add a number 0 to the symbol. I’m using a font called Digital Readout, but any LED-style font should work.
Set the text size to 40 pt and make it a light amber/orange color (#F4C28B). Set the Paragraph Format to centered.

Step 4: Add Glows
Add two separate glow filters to your text field. Set the color to red (#FF0000) for both and set the Strength of both to 200%.
Check the Inner Glow checkbox for one and set the Blur to 2px. Leave the other at 5px Blur.

You can use a different color if you want (blue or green would both look cool). The trick in getting it to look realistic is to make the text color a little washed out and set the glows to a more saturated color. This makes it look like it’s emitting light.
Step 5: Add More Numbers
Create keyframes on frames 1-10 of the digit movie clip. An easy way to do this is to select frames 1-10 (click frame 1, then Shift-click frame 10) and press F6.
You should now have 10 frames, each with a keyframe with your glowing 0 text field. Go through each frame and change the numbers so you have the digits 0-9. Frame 1 will have “0″, frame 2 will have “1″, frame 3 will have “2″, etc.

Name this layer “numbers”.
Step 6: Add the LED Background
We’ll now add an “off” state for the LED numbers, so you’ll be able to see the unlit segments of the LED display.
Copy your 8 digit (in frame 9). Create a new layer named “background”. With the new layer selected use Paste in Place (Edit > Paste in Place) to paste the 8 digit in the exact position as the one we copied.
Remove the glows from the new 8 digit and change its color to dark grey (#333333). Add a blur filter with the Blur set to 3px. Move this layer underneath the “numbers” layer.

Now you can scrub through the frames and see how the unlit segments of the LED show behind each number.
Step 7: Add the Stop Action
Create another new layer named “actions”. Open the Actions Panel and add a stop() action on frame 1.

This will keep the display showing ’0′ until we tell it otherwise.
Step 8: Why Frames?
Why are we manually putting each digit on its own frame instead of using a dynamic text field? Good question.
The main reason is that doing so makes it more flexible for updating the graphics later. If you wanted to change the design and use bitmaps for the numbers, or have each digit displayed in a different font or color this makes it easy to do that.
Also, if designers and developers are working together on a project it’s best to create things in a way that gives designers easy access to as much of the graphics as possible.
I feel this setup does that more than using dynamic text.
Step 9: Create the Score Movie Clip
Create a new movie clip named “Score”. Check ‘Export for ActionScript’ and set the class name to “Score” also.

Drag the digit movie clip from the Library into the Score movie clip. Duplicate the digit clip (Edit > Duplicate) six times (so you have seven digits) and space them evenly.
Since we only have seven digits the maximum score we’ll be able to display is 9,999,999. If your game will need to accommodate higher scores add more digits accordingly.
Add a bit more space between every third digit to allow for comma separators.

Step 10: Name the Digit Clips
Select the leftmost digit movie clip and give it the instance name “digit1″. Name the next one to the right “digit2″, then “digit3″ and so on.

Step 11: Add Commas
Create a new layer called “commas”.
The easiest way to get the commas to look exactly like the numbers is to go into one of the digit clips and copy one of the number text fields.
Back inside the Score movie clip, paste the text field into the commas layer, and change the number to a comma. Duplicate it and move it as many times as you need.

Step 12: Add a Background
For the Score background we’ll just add a simple rounded rectangle.
Create a new layer called “background” and place it behind the numbers and commas layers. Select the Rectangle Tool and Option-click (Alt-click) the stage. Make a rectangle 200px x 40px with 3px corners (make yours longer if you have more digits). Make the fill black and the stroke 1px grey (#666666).

For some reason Flash always distorts strokes on rounded rectangles. To get around this, select the stroke and choose Modify > Shape > Convert Lines to Fills. This converts the stroke from a line to a filled shape and it will no longer distort.

If you think this is a total hack of a workaround for basic functionality that should have been fixed years ago, I urge you to contact Adobe and let them know.
Step 13: Add Shine
What graphic would be complete without some iPhone-esque shine?
Create a new layer above everything else called “shine”. Add a new rounded rectangle, slightly smaller than the background one. This time give it no stroke and fill it with a white gradient from 20% Alpha to 0% Alpha.

Step 14: Create the Score Class
Create a new Actionscript file named “Score.as”. Save it in the same directory as your main Flash file. Since the name of this class and the Export Class name of our Score movie clip are the same, Flash will automatically link them.
Add this code to the Score.as file:
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Score extends MovieClip {
// CONSTRUCTOR
public function Score() {
}
}
}
This is just an empty shell of a class for now. We have to extend the MovieClip class since this class is linked to a movie clip in the library, so we also have to import the MovieClip class. We’ll be using the ENTER_FRAME event, so we import the Event class as well.
Step 15: Add Variables and Constants
Add these two lines to the Score class just above the constructor function.
private const SPEED:int = 1; // how fast to count private const NUM_DIGITS:int = 7; // how many digits there are in the score
These are two constants – kind of like settings for the class.
- The first, SPEED, controls how fast the score counts. I have it set to count one by one, but if your game uses higher scores this might be too slow. You can change this to 5 or 10 or 50 to count up by those increments.
- The second constant, NUM_DIGITS, defines how many digits we have in our Score movie clip. If you added more (or less) than 7 digits you’ll need to change this.
Now let’s add a couple of variables. Put these just below the constants:
private var _totalScore:int = 0; private var _displayScore:int= 0;
These variables will hold the two different versions of our score. “_totalScore” will be the actual score. “_displayScore” will be the number that is currently
being shown on the LED display. If I add 50 to the score, the _totalScore will immediately be 50, but the _displayScore will be 1, then 2, then 3, until it reaches 50.
If you ever need to know the actual score (like to send to your high score boards) you’ll use _totalScore since _displayScore might not be accurate.
I’m using underscores at the beginning of the variable names to denote that these are private variables.
Step 16: Add the totalScore Accessor Method
So if _totalScore is a private variable, how will we access from outside the Score class? We’ll use an “accessor” or “getter” method.
Add this method below the constructor function:
// public accessor for totalScore
public function get totalScore():int {
return _totalScore;
}
This method simply returns the value of the _totalScore variable. It gives us a way to access that value without having to expose it as a public variable.
Step 17: Add the add Method
We’ll need a way to add points to the score. Add this method:
// add an amount to the score
public function add(amount:int):void {
_totalScore += amount;
addEventListener(Event.ENTER_FRAME, updateScoreDisplay); // start the display counting up
}
This method accepts an integer “amount” which it adds to the _totalScore variable. The second line starts an ENTER_FRAME event that calls a method called updateScoreDisplay every frame. We’ll add that next.
Step 18: Add the updateScoreDisplay Method
Now add a the updateScoreDisplay method. This is where all of the cool counting-up functionality will happen. It needs to accept an Event since it’s getting called from an ENTER_FRAME event.
// this runs every frame to update the score
private function updateScoreDisplay(e:Event):void {
}
Now let’s add some functionality. The first thing this method will do is to increment the _displayScore variable by the amount we set in our SPEED constant:
// increment the display score by the speed amount _displayScore += SPEED;
There’s a potential problem here though. What if our speed is set to 10 and we try to add 5 to the score? The displayScore will be higher than the totalScore. Let’s add a couple lines to fix that:
// make sure the display score is not higher than the actual score
if(_displayScore > _totalScore){
_displayScore = _totalScore;
}
That checks if the displayScore is higher than the totalScore and if so, sets the displayScore to be equal to the totalScore.
Next we need to add the leading zeros to the score. We’ll do this by converting the displayScore to a String and adding zeros until the length equals the number of digits defined by the NUM_DIGITS constant:
var scoreStr:String = String(_displayScore); // cast displayScore as a String
// add leading zeros
while(scoreStr.length < NUM_DIGITS){
scoreStr = "0" + scoreStr;
}
Now to actually display the score we’re going to loop through each of our digit clips (remember we named then “digit1″, “digit2″, etc.) and use the corresponding number from the score string to set the frame number of the clip:
// loop through and update each digit
for (var i:int = 0; i < NUM_DIGITS; i++) {
var num = int(scoreStr.charAt(i));
this["digit"+(i+1)].gotoAndStop(num+1);// set the digit mc to the right frame
}
The charAt method retrieves the character from a String at the specified position. This lets us go character by character through the score string.
The brackets in the next line allow us to dynamically create the clip name. The code, this["digit"+(i+1)] accesses the clip with the name “digit1″ or “digit2″, etc., depending on the value of i.
We’re using “num+1″ as the frame number because the frame numbers are offset by 1 from the digits they contain (frame 1 shows 0, frame 2 shows 1, etc.)
The last thing we need to do in this method is check to see if the displayScore and the totalScore are equal. If so, we can remove the listener and stop calling this method for now.
// if the display score is equal to the total score remove the enterframe event
if(_totalScore == _displayScore){
removeEventListener(Event.ENTER_FRAME, updateScoreDisplay);
}
If you got lost anywhere in that step you can check out the source files to see the completed class.
Step 19: The Score Class in Use
To use this class drag the Score movie clip from the Library onto the Stage and give it the instance name “myScore”. You can add points to your score by using this line in your Document Class:
myScore.add(50);
You can see an example of this in the source files. I’m adding to the score when the bumper buttons are clicked, but you’ll more likely be calling add() when events in your game occur.
If you need to know the player’s score you can get the totalScore by using:
myScore.totalScore
This will call the accessor method and return the value of _totalScore.
Conclusion
You now have a reusable counting Score class that you can use in any of your games.
I think the LED look is cool, but you should definitely alter the design to fit the look of your game. Here are a couple ideas for different designs to get you started:

Thanks for reading this tutorial. Let me know what you think!
thanks for this. Short, but however, it’s helpful
it´s free!
does the getter function automatically get called when accessing myScore.totalScore?
Yes. When you use the AS3 getter and setters you can use the name of the function like a property. So if you made a method like:
public set function totalScore(val:int):void
You could also set the property using:
myScore.totalScore = 30;
Pretty cool right?
oh totalScore is a function, of course!
Wow, its like you read my mind… I was just looking for a way to do this for a site i am building right now. Awesome, thanks! Great job of explaining everything :)
It is so freaking helpful! You can make soooo many fu**ing awesome flash games based on this points scoring!
Thanks, Thanks, Thanks, Thanks Thanks, Thanks, Thanks, Thanks Thanks, Thanks, Thanks, Thanks Thanks, Thanks, Thanks, Thanks Thanks, Thanks, Thanks, Thanks Thanks, Thanks, Thanks, Thanks Thanks, Thanks, Thanks, Thanks and Thanks again!
Um, you’re welcome. :)
I’m glad you like it.
Fun little tutorial. Thanks for the graphics tips as well.. nice effects!
Very nice
very nice tutorial.thanks for it
One thing i thought in first is “why using timeline”, but it´s explained and i agree about this, maybe a short tutorial but it´s veryy usefull, congratulations and thanks!!
It would be pretty simple to change this to use a dynamic text field instead of frames if people prefer to do it that way.
First you would remove all but the first frame in the digit Movie Clip. Then change the text field to dynamic (remember to embed the font). Give it an instance name ‘myTextField’.
Then change line 51 to set the text of that text field instead of navigating to the frame. Something like this:
this["digit"+(i+1)].myTextField.text = num;
You lose a little control over the design of each number, but it might be easier to quickly change the design if you want to reuse the score class a lot.
Ive been wondering how to do this for a bit, thanks.
Wow! What a cool tutorial. It is way beyond my skill level – but I am going to share it with some fellow Pinball enthusiasts who will also find it interesting – and useful!
add is not a function.
It would be nice if you summarized the entire code in the conclusion because you haven’t told us where to put most of it.
It all goes inside the Score class.
If you want to see the completed file you can download the source at the top of the page. It will show you the entire Score class and some sample code on how to use it.
Sorry for the confusion.
hi, thanks a lot!
but how can this counter be modified, so that it will remember the last score?
I’m not really sure what you mean. You want it to remember the most recent amount added to it, or you want it to remember the score from a previous game?
This class is really meant to just display the score in a neat way, not store it.
If you want to show the score from the previous game you can use the totalScore getter method to get the score at the end of the game and store it somehow (either on a server, or in a local SharedObject). Then at the start of each new game, you’ll look for that value and use the Score class to display it. You’ll probably want to add a totalScore setter method to the score class so that you can send in the initial value without having to show it count all the way up.
Great tutorial!
I liked the design so much, that I recreated the the score counter in flex using mxml, so it’s using less code.
Check it out at http://flexwiz.amosl.com/as3/animated-score-made-easy/
Very cool.
I like the idea of using a tweener to animate the value. It makes it a lot simpler, and you can use easing to make it count really fast at the start and then slow down as it gets closer to the actual value.
Fantastic tutorial and it works perfectly.
I am using this for a game which has negative values, so far I am struggling to get this to work. What would I need to edit to make the negative symbol appear? At the moment I get the correct number but without the negative sign, even though if I trace the variable the negative is there.
Any help would be much appreciated!
Yeah, that’s one of the downsides of using keyframes to display the numbers instead of a dynamic text field.
Here’s an idea for a quick fix:
Add another frame to the digit movieclip (on frame 11). Put the negative symbol here.
Then alter the for loop in the updateScore function to check for the negative symbol and display that frame if it finds it. Something like this should work:
// loop through and update each digit
for (var i:int = 0; i < NUM_DIGITS; i++) {
var char:String = scoreStr.charAt(i); // the current character in the scoreStr
if(char == "-"){
this["digit"+(i+1)].gotoAndStop(11);// set the digit mc to the negative frame
} else {
var num = int(scoreStr.charAt(i));
this["digit"+(i+1)].gotoAndStop(num+1);// set the digit mc to a number frame
}
}
Depending on the formatting for your score that might look a bit wacky though. The minus sign will appear as a digit within the score, separated by the commas.
A better solution might be to just have a graphic at the far left of the score display that will either display a plus or minus. You can just check if _displayScore is greater or less than zero and set the display of that graphic accordingly. You could even do something cool like change the score numbers from green to red when it goes negative.
Thanks Cadin, adding the extra frame worked perfectly!
I think I may have found a bug. I was using this to animate some calculations and it seems like it won’t display really high numbers correctly.
I added 10 text fields and changed NUM_DIGITS to 10 too. I then did this calculation
1500000 * 7.2 * 300 which equals 3285000000
However, the counter shows this 0100996729 :S But if I trace the variable it does show the correct value.
Do you have any idea why this would happen?
Thanks!
It’s because I’m using the datatype int to store the score.
The maximum value an int can hold is 2,147,483,647.
If you need to use numbers that big (really?) you can use the Number datatype instead.
Change the _displayScore and _totalScore variables to be of type Number.
Also change the add() function to accept a Number instead of an int.
If you make those changes it should work.
Also, 1500000 * 7.2 * 300 = 3240000000
;)
this is fantastic. I however, am less so.
I have worked through the script to some extent (with minimal script skill) but am struggling to get it to do what I want. I need the score to run both up (add) and down (subtract).
I get that I need to add the Subtract Method, which is straightforward (i think)
but after that I get confused. do I need to duplicate the rest of the script to reverse the process to ‘take away” the score? and if so, do I need to call a different event?
I hope that question makes sense. Any help would be massively appreciated
Luke
I’m not sure there’s a simple fix for what you want to do since the Score class wasn’t designed to go down, just up.
You actually don’t need to add the subtract() method. You can just send a negative number to the add() method. Adding a negative number to _totalScore is the same as subtracting from it.
From that point though you’ll need to modify the updateScoreDisplay method to be able to detect if it should be counting up or down and to either add or subtract the SPEED constant from _displayScore.
A simpler (in some ways) solution might be to use a tweening library like Tweener or TweenLite to tween the _displayScore variable to the _totalScore value. This way it will handle the counting up/down for you automatically.
That will however require you to download and import the library, which is a bit too much to go into here, if you’re not familiar with that process.
Check out Amos’ comment above for a good example of this.
If you want to send me an email (hit the link in my name and find my email address on my website) I can try to send you some sample code to work with.
Thanks for the reply, i will have a crack at using the basic code first, that is probably just within my ability
if not, easing the counter sounds like fun too!
thanks very much, and kudos again on the fantastic tutes
Is there a way to make each digit count to say 23 before the next digit turns over to 1?
I’ve setup my digit to be dynamic and made the field large enough for 2 numbers. Any thoughts would be great thanks.
This is really a Good example. Worked for me. Thanks a lot !!!
But I am having problem settingg up font for it. I have created the Movie and added it in to my fla.
Also installed and added font to fla. Still I cant see the effect in SWF when run on other machine.
I am not sure if I missed anything. I am new to flash.
Please suggest if you have solution.
Thanks in advance.
Atul