How to Add the Kongregate API to Your Game

by Michael James Williams on May 13, 2009 · 45 comments

in Avoider Game Extras,Tutorial

screenshot

I take it you’ve heard of Kongregate. They’re one of the big, free Flash game portals, and describe themselves as “the YouTube of videogames”.

They allow developers to tap into their system to save high scores, grab data about the players and implement badges (well, for the lucky devs!) All of this is done through the Kongregate API — essentially a set of functions that can be accessed via code.

Kongregate have actually provided a decent set of instructions for using their AS3 API, but they can be a little confusing to follow if you’ve never worked with an API before.

By following this tutorial, you’ll learn how to add Kongregate’s AS3 API to your game, and how to use high scores, player info and badge statistics.

Click the image below to check out these features inside the game:

screenshot

I’ll use the game from my AS3 Avoider Game Tutorial as a base for this. If you followed that tutorial, you can follow along with the game you made; if not, you can grab the zip file containing all the game’s files from here — it’ll be easy enough to understand how they all work.

Installing the API

The official documentation lists a few ways to get the API into your game, but I’m just going to explain the simplest: installing it as a component using the Adobe Extension Manager. This requires you to have Flash CS3 or CS4 — if you don’t have it, follow Step 3 of the official instructions, and skip to “Using the API Inside the Game” in this tutorial.

First, you’ll need to download the manager; go to this page to do so. If you’re using Flash CS3, scroll down to where it says “Extension Manager 1.8″ and download that instead. Flash CS4 users should get “Extension Manager CS4 2.0″.

Once you’ve downloaded it, install it as you would any program and run it:

screenshot

As you can see, I’ve already installed a number of extensions (I’ve written up a list of my favourites here). Now, download the “.MXP component installer package” from Step 2a of the official instructions. Depending on the browser you’re using, you might get a message like this:

screenshot

If so, just click “Open with Extension Manager”. If not, save it to your hard drive, switch to the Extension Manager, click File > Install Extension and find the MXP file you just downloaded. Either way, you’ll get a Disclaimer:

screenshot

If you’re happy with it, accept it; you’ll get a message telling you that the extension was successfully installed.

Adding the API Component to Your Game

Open your FLA file in Flash (if you already had Flash open, it’s a good idea to close it and re-open it at this point).

Click Window > Components to make the Components panel appear. Click the little plus sign next to Kongregate to expand it:

screenshot

Now drag and drop KongregateAPI to your Library:

screenshot

Time for some code! Open DocumentClass.as. We need to import the API class:

?View Code ACTIONSCRIPT3
9
import com.kongregate.as3.client.KongregateAPI;

We’re going to have to create an instance of KongregateAPI and add it to the stage, just as we do with the various screens and the loading bar. So, first create a new public var of type KongregateAPI:

?View Code ACTIONSCRIPT3
13
14
15
16
17
public var menuScreen:MenuScreen;
public var playScreen:AvoiderGame;
public var gameOverScreen:GameOverScreen;
public var loadingProgress:LoadingProgress;
public var kongregate:KongregateAPI;

The question is, whereabouts in the code do we addChild() it to the stage? I think the best place is after the game’s completely downloaded but before the menu screen appears — i.e. the onCompletelyDownloaded() function:

?View Code ACTIONSCRIPT3
30
31
32
33
34
35
36
37
public function onCompletelyDownloaded( event:Event ):void
{
	removeChild( loadingProgress );
	gotoAndStop(3);
	kongregate = new KongregateAPI();	//instantiate API
	addChild( kongregate );		//add API to stage
	showMenuScreen();
}

The API can detect that it’s been added to the stage, and it automatically connects to Kongregate (or fakes a connection, if you’re testing your game offline). We can’t use the API until it’s connected, so just to be on the safe side let’s not show the menu screen until this has happened. (Don’t worry, it’s fairly quick.)

How can we tell that it’s connected? An event listener, of course! Import the KongregateEvent class in your document class:

?View Code ACTIONSCRIPT3
10
import com.kongregate.as3.client.events.KongregateEvent;

…listen for the COMPLETE event, which tells us the API has connected to Kongregate:

?View Code ACTIONSCRIPT3
public function onCompletelyDownloaded( event:Event ):void
{
	removeChild( loadingProgress );
	gotoAndStop(3);
	kongregate = new KongregateAPI();	//instantiate API
	kongregate.addEventListener( KongregateEvent.COMPLETE, onKongregateConnected );
	addChild( kongregate );		//add API to stage
	showMenuScreen();
}

…and create an event handler:

?View Code ACTIONSCRIPT3
41
42
43
44
public function onKongregateConnected( kongregateEvent:KongregateEvent ):void
{
 
}

Oh, we need to move the showMenuScreen() call from onCompletelyDownloaded() to onKongregateConnected():

?View Code ACTIONSCRIPT3
40
41
42
43
public function onKongregateConnected( kongregateEvent:KongregateEvent ):void
{
	showMenuScreen();
}

(Make sure you remove it from onCompletelyDownloaded().)

Test the game. It won’t look any different, but the Output window will show this:

Alert: Kongregate API could not be loaded, due to local testing. API will load when the game is uploaded.

Kongregate Shadow Services instantiated for local development..

Phew! Seems like a lot of work for little benefit, but remember it won’t take anywhere near as much time next time you do it.

Using the API Inside the Game

Every function we’ll need to use is accessed through this KongregateAPI instance that we’ve created. For example, we can get the player’s username like so:

?View Code ACTIONSCRIPT3
var playerName:String = kongregate.user.getName();

We might want to use it in every screen:

  • Menu screen: display the user’s name, like “Hi, MichaelJWilliams!”
  • Play screen: submit stats, like number of enemies avoided so far
  • Game over screen: submit score, and possibly display a score board

Trouble is, we’ve only instantiated the API in the document class, so it looks like we’ll have to either:

  • Create a new instance of the API separately in each of the screens we want to use it
  • Pass the single instance of the API from document class to screen to document class to screen to…
  • Dispatch events from each of the screens requesting and passing information, and listen for and react to these events in the document class

Each of these three methods would work, but they’re going to be a bit messy and a bit of a pain. Fortunately, the API is a special type of class called a Singleton that lets us avoid these problems.

If you followed Part 12 of the base tutorial, you’ll know that typing kongregate = new KongregateAPI() inside the document class doesn’t mean that kongregate is an object inside the document class. It actually means that kongregate points to a specific instance of the KongregateAPI class.

Singletons only allow a single instance of their class to be created (hence the name). The class itself then contains a function (a static function) that allows any other class to access this one instance. This way, every screen can easily access the Kongregate API.

Don’t worry if that sounds complicated in theory; in practise it’s actually very easy to use. Here, let me show you. We’ll add a greeting to the player on the menu screen.

Open your MenuScreen symbol from the Library. I’ve modified mine a bit to make it more Kongregate-y:

screenshot

You can download their logo from this page. Add a new text field, set it to Dynamic Text and give it an instance name of greetingText. Type “Hi!” into it for now:

screenshot

Don’t forget to embed the font, turn “selectable” off, and so on. Now open MenuScreen.as. Remember, we need to create a variable for this new text field, so do that now:

?View Code ACTIONSCRIPT3
8
9
10
11
public class MenuScreen extends MovieClip 
{
	public var startButton:SimpleButton;
	public var greetingText:TextField;

…and that means we need to import flash.text.TextField as well.

It’s time to create that pointer to the Kongregate API singleton instance. First, let’s import the API:

?View Code ACTIONSCRIPT3
3
4
5
6
7
8
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.ui.Mouse;
import flash.text.TextField;
import com.kongregate.as3.client.KongregateAPI;

Next, we create the variable that will point to the API instance:

?View Code ACTIONSCRIPT3
12
13
14
public var startButton:SimpleButton;
public var greetingText:TextField;
public var kongregate:KongregateAPI;

Finally, we use the static function of the KongregateAPI class to access the instance of that class that we created in DocumentClass:

?View Code ACTIONSCRIPT3
16
17
18
19
20
21
public function MenuScreen() 
{
	kongregate = KongregateAPI.getInstance();	//getInstance() is a static function
	Mouse.show();
	startButton.addEventListener( MouseEvent.CLICK, onClickStart, false, 0, true );
}

Was that clear enough? Please leave a comment if not!

Getting the Player’s Name

Since we don’t create the menu screen until the Kongregate API object has connected (or fake-connected), we know it’s safe to use inside the menu.

All information about the player is stored in the kongregate.user object. We can access the player’s username with the kongregate.user.getName() function. So to create a personalised greeting, all we need to do is this:

?View Code ACTIONSCRIPT3
16
17
18
19
20
21
22
public function MenuScreen() 
{
	kongregate = KongregateAPI.getInstance();	//getInstance() is a static function
	greetingText.text = "Hi, " + kongregate.user.getName() + "!";	//greet the user
	Mouse.show();
	startButton.addEventListener( MouseEvent.CLICK, onClickStart, false, 0, true );
}

If you test the game now, the API will detect that you’re running it offline, and will just return “Guest” as your username:

screenshot

Pretty cool! We can’t do much else with the API until we have uploaded our game to Kongregate, so let’s do that next.

Uploading to Kongregate

Log in to Kongregate, then choose Developers > Upload Game on the main menu. There’s a whole bunch of information to add in, like the name of your game and a description and so on.

Once you’ve entered this info, you get to upload your game. Find the SWF file on your hard drive for this. In the API section, tick both the High Scores and Statistics box — we’ll add those in a bit.

Click Upload, and:

screenshot

Tada! Hey, look, it’s greeting me with my actual username.

Nobody else can play your game until you click the Publish link above your game. This means we can add more API features and test them until they work exactly as we like. So let’s do that.

Adding Badge Support

Some games get the honour of having “badges” added to their game — tasks like “complete hard mode” or “defeat fifty bad guys” that win the player some points and a badge for their profile. We can’t add badges directly to our games, but we can specify the stats that the admins can use to add badges later, if the game is popular enough to be chosen.

We have to use the Kongregate website to define these statistics before adding them to the code. We can do this by clicking the Edit link that appears when we preview our game, but that involves some messing about, ticking boxes we’ve already ticked, and there is an easier way. All you have to do is add /statistics to the URL of your preview game.

For example, my preview game is at http://www.kongregate.com/games/MichaelJWilliams/avoider-game-tutorial-kongregate-edition_preview so to edit the badge stats, I just need to go to http://www.kongregate.com/games/MichaelJWilliams/avoider-game-tutorial-kongregate-edition_preview/statistics. Easy! I’m greeted with this page:

screenshot

Click “Add a statistic” to bring up a list of options:

screenshot

Obviously there are a lot of things you could measure, but I’m just going to add “number of smilies avoided across all games”:

screenshot

Click Save Changes and you’re set. Now to get this into the game.

Open up AvoiderGame.as. I’m going to say that the player has successfully avoided a smiley when the smiley moves off the bottom of the screen and is removed. That’s this bit of code here:

?View Code ACTIONSCRIPT3
172
173
174
175
176
if ( enemy.y > 350 )
{
	removeChild( enemy );
	army.splice( i, 1 );
}

Naturally yours could be different if you’ve modified your game.

Before doing anything, we need to create a variable that points to the Kongregate API instance. So, just as before, you need to:

  • Import com.kongregate.as3.client.KongregateAPI
  • Create public var kongregate:KongregateAPI
  • Point kongregate = KongregateAPI.getInstance() (in the constructor function)

Once you’ve done all that, it’s easy to add the stat.

All stat-related functions are in the kongregate.stats object. To submit a statistic, we just need to call kongregate.stats.submit( "NameOfStatistic", Number ). So for this “smilies avoided” stat, all we have to add is this one line:

?View Code ACTIONSCRIPT3
175
176
177
178
179
180
if ( enemy.y > 350 )
{
	removeChild( enemy );
	army.splice( i, 1 );
	kongregate.stats.submit( "AvoidedTotal", 1 );
}

Note that AvoidedTotal was the name I gave my stat on the Kongregate page (see above). Because I set the type of this stat to Add, it’ll increase my record by one every time I avoid an enemy, no matter how long it’s been since I last played.

Test the game. You’ll notice this line appears in the Output panel every time an enemy reaches the bottom of the screen:

Kongregate API: IStatServices.submitStat(AvoidedTotal,1) 

Now we can upload this new version to the Kongregate site and try it out for real. Just click “upload new version” when previewing your game — yes, you have to tick all those boxes again, but never mind.

Play the game online, and check out what happens:

screenshot

Great! That proves it’s working. If you don’t want the player to be able to see this stat, edit it on the website and uncheck the “Display in Leaderboards” option. Add some more stats if you like — how about the best score, or the top level reached, or the total number of seconds played?

Adding High Scores

If you think about it, scores are really just another kind of statistic, “number of points attained”, so it seems odd to deal with them in a different way. But treating high scores differently lets us view them differently, in a score table, either inside or alongside the game. Players see scores as different to other stats, so we should too.

Anyway, scores are easier to code than stats because we don’t need to define them on the website. We just submit the score (and difficulty mode, if your game has them) and let Kongregate take care of the rest. It actually creates a statistic to track the high scores.

The best place to do this is in the game over screen, so open GameOverScreen.as. As usual, import the KongregateAPI class, create a new public variable called kongregate, and set it to point to KongregateAPI.getInstance() in the constructor function.

All the score-related functions are in the kongregate.scores object, not surprisingly. To submit a new score of 100 points, we just call:

kongregate.scores.submit( 100 );

To specify a difficulty mode, like “easy”, we can call:

kongregate.scores.submit( 100, "easy" );

We already have a function that gets the final score and saves it to the user’s hard drive — it’s called setFinalScore(). Let’s use this same function to save the score to the Kongregate website:

?View Code ACTIONSCRIPT3
33
34
35
public function setFinalScore( scoreValue:Number ):void
{
	kongregate.scores.submit( scoreValue );

Test the game, and when you get game over you’ll see a message like this in the Output panel:

Kongregate API: IHighScoreServices.submit(130) 

Upload your game to Kongregate, ticking all those boxes again, and test it online:

screenshot

Awesome — I’ve never had the top score on any Kongregate game before ;)

Wrapping Up

There’s more you can do with the API, like access the player’s avatar picture, and display the high score table directly in your game rather than just alongside it, but I’ll leave you to check that out on your own. All relevant pages of the official documentation are linked to from this page, so check them out.

You can download a zip of all the files I used in this tutorial from this link.

Also, you can check out the game I made by clicking on this image:

screenshot

Vote 5 pls ;)

Kongratulations on adding the Kongregate API! Any komments?

{ 44 comments… read them below or add one }

dVyper May 14, 2009 at 8:48 am

Quite a nice n simple tutorial! :)

Michael Williams May 14, 2009 at 11:12 am

Thanks, dVyper :)

Brandon May 15, 2009 at 5:45 am

Looks good Michael : ) I got an email from Kongregate saying that they prefer you use the manual loading, just to prevent a couple of issues. But I looked at it and it doesn’t really flow too well with me. I think I’ll stick with the component method for now : )
Question though: would it be better to use the method you described in your Avoider tutorial for ALL data storage, or should you store some on the API (site), like past scores, and not bother loading them from your own local file? It does solve the problem of using CCleaner, and it would let the user find his own past data from ANY computer. Do you think it would slow things down? How about adding it as a saving feature?

-Brandon

Michael Williams May 15, 2009 at 10:27 am

They prefer the manual loading? Dang, wish I’d known. Any idea what the issues were?

Interesting question (though what do you mean by the CCleaner problem?). I never thought about storing actual save game data to Kongregate. Looking at the docs, I don’t think it’s possible, unfortunately, as I can’t see any functions for retrieving the user’s best score or a list of the user’s stats — it seems to be a one-way process.

I could be wrong, though, and if I am that’d be great, because as you say it’d be fantastic to be able to load data from any computer. If you happen to find out more about this, please let me know :)

Brandon May 15, 2009 at 3:41 pm

Well if you say its one way, then I believe you ; ) Just from the sounds from it, it was two way ; ) The ccleaner problem, or it could be called the junk file problem, is that the temp files that flash data is stored on is considered junk. CCleaner and other applications will clean it up when running a junk scan, thus loosing your save games.
I don’t think Kongregate would appreciate some people saving their games on the server though ; ) They probably don’t have as many servers as World of Warcraft does : P

And the issues with non-manual loading all seem to be “ominous” and “glitches”, without specifying what they were. I think they were past problems. I’m just restating the email they sent me:
[quote]
“I do want to encourage you to use the manual loading of the API
(http://www.kongregate.com/forums/4/topics/3064#posts-46479) rather
than the component method, which sometimes has some glitches and can
be difficult to debug.”
[/quote]

Snurre May 16, 2009 at 1:13 pm

Well, there is an option for savning data on the internet. Use Nonoba! They allow you to save data like this on their servers :)

Michael Williams May 16, 2009 at 3:10 pm

I didn’t know that about CCleaner. Ugh, how annoying… it’s not like Flash is brand new, is it?

Hmm that’s irritating about the API component being glitchy. Maybe I’ll come back later and re-write that part of the tutorial. Still, having the Extension Manager installed is useful anyway.

Snurre, thanks for the tip on Nonoba! I didn’t know they allowed for save data, I only knew about their multiplayer API.

Brandon May 16, 2009 at 6:35 pm

The “glitchiness” they claim is not concrete. Its just potential. But after the latest fix, I haven’t even heard of someone having a glitch with the component. I think they’re just saying that it could be glitchy, since it wasn’t modularily developed and you’re just implementing the api, not fully importing it.

Michael Williams May 17, 2009 at 8:21 pm

Rats. OK I guess I’ll have to look into that some time. Thanks for letting me know.

Glitcched June 5, 2009 at 10:25 pm

One question, I got the Total Kills showing up under achievments, but no highscore? Why is that?

Michael Williams June 6, 2009 at 12:37 pm

Hmm, that’s odd. Do you see the:

Kongregate API: IHighScoreServices.submit(130) 

line in your Output panel when you test the game within Flash?

Glitcched June 6, 2009 at 12:42 pm

Yeah I do.. So it doesn’t seem like there’s and error on the game itself

Michael Williams June 6, 2009 at 12:44 pm

OK. Do you have any other stats set up, like Smilies Avoided in my game, and do they work fine?
Also, if you look at the Kong leaderboards for your game, does the “Mode” drop-down list have an option for high scores?

Glitcched June 6, 2009 at 12:45 pm

I have a few stats and they work fine. They drop down in leaderboards and so on, but highscore does not appear in the leaderboard

Glitcched June 6, 2009 at 12:53 pm

Jut to make sure, should Highscore appear automatically? Because that what it seemed like in your tutorial, and I dont see any other reason for a separate score function…

Michael Williams June 6, 2009 at 12:55 pm

Yeah it should be automatic, at least it was for me.

Are you passing a mode, like “easy”?

Glitcched June 6, 2009 at 12:57 pm

Yeah I have Easy, Normal and Hard.

However, i set them when the player choose difficulty in the beginning of the game, not when submitting the score.

Michael Williams June 6, 2009 at 1:02 pm

I’ve just noticed someone post on the Kong forums with a similar problem:
http://www.kongregate.com/forums/4/topics/3064?page=5

So you do something like:

kongregate.scores.setMode ( "Hard" );

at the start of the game, and then:

kongregate.scores.submit ( scoreValue ); 

at the end?

If so, try this:

kongregate.scores.submit ( scoreValue, "Hard" );  

at the end. I know this isn’t a solution, but it’ll help to narrow down the problem.

Glitcched June 6, 2009 at 1:13 pm

Yeah thats how I did.

So i tried what you said, got

Kongregate API: IHighScoreServices.submit(305,Normal)
in output. However, when I uploaded the game and played I still don’t got any Highscore list

Michael Williams June 6, 2009 at 1:20 pm

Rats. OK, I guess you can change it back to the way it was before.

I’ve got an idea. Go to the page you use to set up statistics and create a new one:

Name: HighScore-Normal
Description: HighScore-Normal
Max Type: Selected
Display in Leaderboards: Yes
Display Name: HighScore-Normal

Repeat for your other difficulty modes, with obvious changes. Does that help?

Glitcched June 6, 2009 at 1:33 pm

Heh that actually worked. Thanks a bunch ^^

Michael Williams June 6, 2009 at 1:35 pm

Awesome! Not exactly an elegant solution, but I’m glad it worked :)

Suran37 August 12, 2009 at 8:46 pm

I followed the Tut. but for some reason i am getting this issue on the score submit part

TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at GameOverScreen/setFinalScore()
    at DocumentClass/onAvatarDeath()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at AvoiderGame/onTick()
    at flash.utils::Timer/_timerDispatch()
    at flash.utils::Timer/tick()

Michael Williams August 13, 2009 at 4:57 pm

Hey Suran37,

Can’t do much without having the specific line/function, I’m afraid! Please narrow it down ;)

Suran37 August 13, 2009 at 8:12 pm

Ahh it seems that in the line

kongregate.scores.submit( scoreValue );

kongregate is null but i did place the KongregateAPI.getInstance() inside the the public function GameOverScreen

Michael Williams August 15, 2009 at 12:14 am

Hmm that’s odd. Do the other Kongregate things work, like getting the player’s name?

Would you mind pasting your GameOverScreen() function here so I can take a look?

Suran37 August 15, 2009 at 2:32 am

package 
{
    import com.kongregate.as3.client.KongregateAPI;
    import com.kongregate.as3.client.events.KongregateEvent;
    import flash.display.MovieClip;
    import flash.display.SimpleButton;
    import flash.events.MouseEvent;
    import flash.ui.Mouse;
    import flash.text.TextField;
    import flash.net.SharedObject;

public class GameOverScreen extends MovieClip 
{
    public var kongregate:KongregateAPI;
    public var sharedObject:SharedObject;
    public var restartButton:SimpleButton;
    public var finalScore:TextField;
    public var bestScore:TextField;
    public var finalClockTime:TextField;
    public var scoreValue:Number;

    public function GameOverScreen() 
    {
        KongregateAPI.getInstance()
        Mouse.show();
        restartButton.addEventListener( MouseEvent.CLICK, onClickRestart );
        sharedObject = SharedObject.getLocal( "mjwScores" );
    }

    public function onClickRestart( mouseEvent:MouseEvent ) 
    {
        dispatchEvent( new NavigationEvent( NavigationEvent.RESTART ) );
    }

    public function setFinalScore( scoreValue:Number ):void
    {
        kongregate.scores.submit( scoreValue );

        finalScore.text = scoreValue.toString();
        if ( sharedObject.data.bestScore == null )
        {
            sharedObject.data.bestScore = scoreValue;
        }
        else if ( scoreValue > sharedObject.data.bestScore )
        {
            sharedObject.data.bestScore = scoreValue;
        }
        bestScore.text = sharedObject.data.bestScore.toString();
        sharedObject.flush();
    }


    public function setFinalClockTime( clockValue:Number ):void
    {
        finalClockTime.text = Math.floor( clockValue / 1000 ).toString();
    }
}

}

Suran37 August 15, 2009 at 5:20 am

Ahh ha i did a little tracing and back tracking!
Found i had to add var kongregate:KongregateAPI = KongregateAPI.getInstance();
to the line before the score submission and it works now!

Michael Williams August 16, 2009 at 5:58 pm

Ah, excellent! :)

DudexD January 31, 2010 at 4:19 pm

Got 2 issues,

  1. My game sometimes starts lagging like headbang

  2. The highscore does not show up in the High Scores tab

I got no errors or anything, and i did everything as in the tutorial… I think… :P

DudexD January 31, 2010 at 5:58 pm

I did find the mistake i did with the High score and fixed it… But now instead i get this in the outpu channel when the avatar hit an enemy

TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at GameOverScreen/setFinalScore()
    at DocumentClass/onAvatarDeath()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at AvoiderGame/onTick()
    at flash.utils::Timer/_timerDispatch()
    at flash.utils::Timer/tick()

package 
{
    import flash.display.MovieClip;
    import flash.display.SimpleButton;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.ui.Mouse;
    import flash.net.SharedObject;
    import com.kongregate.as3.client.KongregateAPI;

public class GameOverScreen extends MovieClip 
{
    public var sharedObject:SharedObject;
    public var kongregate:KongregateAPI;

    public function GameOverScreen() 
    {
        Mouse.show();
        var kongregate:KongregateAPI = KongregateAPI.getInstance();
        restartButton.addEventListener( MouseEvent.CLICK, onClickRestart );
        sharedObject = SharedObject.getLocal( "krdScores" );
    }

    public function onClickRestart( mouseEvent:MouseEvent ):void 
    {
        dispatchEvent( new NavigationEvent( NavigationEvent.RESTART ) );
    }


    public function setFinalScore( scoreValue:Number ):void
    {
        kongregate.scores.submit( scoreValue );
        finalScore.text = scoreValue.toString();
        try
        {
            if ( sharedObject.data.bestScore == null )
            {
                sharedObject.data.bestScore = scoreValue;
            }
            else if ( scoreValue > sharedObject.data.bestScore )
            {
                sharedObject.data.bestScore = scoreValue;
            }
            bestScore.text = sharedObject.data.bestScore.toString();
            sharedObject.flush();
        }
        catch ( sharedObjectError:Error )
        {
            trace( "Caught this error:", sharedObjectError.name, sharedObjectError.message );
            bestScore.text = "???";
        }
    }

    public function setFinalClockTime( clockValue:Number ):void
    {
        finalClockTime.text = Math.floor( clockValue / 1000 ).toString();
    }
}

}

DudexD January 31, 2010 at 6:05 pm

Never mind i found the problem :P

i had put

Var infront of kongregate:KongregateAPI = KongregateAPI.getInstance(); :S

DudexD January 31, 2010 at 6:12 pm

Hmm well the Score does still not show up on kong tho :S

Michael Williams February 2, 2010 at 7:10 pm

Once again, nice work fixing it :)

I’ve seen the score not show up before; it’s weird and I don’t know why it happens.

An inelegant fix which I posted above is to manually create a new statistic, within Kong, with the same name as your high score. Have you tried that?

DudexD February 2, 2010 at 7:56 pm

Tryed the option posted above, but can’t get it to work.

I guess i have to fix something in the gameoverscreen.as to make this work, but i’m not totaly sure what to do :(

Michael Williams February 2, 2010 at 7:58 pm

Can you get it to post statistics OK?

DudexD February 2, 2010 at 8:18 pm

I got my total Dodge to work, and aslo i got a Total Kills, and they both work but all my tries at adding HighScore failes :S
I did try to add it the same way as Totals but it did not work :S

Michael Williams February 4, 2010 at 3:13 pm

Weird. Sorry, I really don’t know why this would be :S

Have you asked on the Kong forums? It’s possible they changed the API since I wrote this.

ayumilove May 1, 2010 at 10:07 am

good tutorial :D
I made my own kongregate api, much more easier to work with their api services now :)

Michael Williams May 7, 2010 at 9:13 pm

Nice one, ayumilove :)

Joey Clover January 23, 2011 at 6:31 pm

Hey, I am using this method.

1) Anyway to GET the highscores?
2) How do I access the ‘Avatars’ and ‘MicroTransactions’ and things?

Gabriel July 1, 2011 at 9:37 am

Nice tutorial. Ah, the KongregateAPI.mxp is not avaible :(

UnknownGuardian August 26, 2012 at 3:28 pm

It looks like a lot of the API links are broken, since the API documentation has since changed and Kongregate wanted to remove old API threads to not mislead people.

If you want quick Kongregate API integration check out QuickKong.as, a quick wrapper I wrote to load the API in 1 line of code and submit statistics in 1 line of code.

Michael James Williams September 1, 2012 at 8:37 pm

Thanks for this!

Leave a Comment

Writing code? Write <pre> at the start and </pre> at the end to keep it looking neat.

Anti-Spam Protection by WP-SpamFree

{ 1 trackback }

Previous post:

Next post: