7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
  1. Code
  2. Games

Using the Kongregate API in Your Flash Games

Scroll to top
Read Time: 16 mins

Kongregate is one of the largest Flash game portals on the net, and has its own API that can be integrated into your games (for which Kongregate even rewards you financially). In this tutorial, I'll show you how to implement the Kongregate API into your games, and also go into detail about what the API is capable of and why you should use it.

(Note that this tutorial assumes you already have a Kongregate account; if you don't, then please create one now.)

Final Result Preview

Let's take a look at what the API enables us to do:


Mass Messages

High Scores

There's another big reason to implement the API...

Step 1: Let's Get Motivated

Before we dive into the technical aspects of implementing the Kongregate API, let's get ourselves hyped up a little bit, and make sure that we actually want to implement it.

There are many reasons to implement the API, but to most developers, nothing speaks louder than money, and there's plenty of that involved. When you upload your game to Kongregate, you automatically earn 25% of all ad revenue generated by your game's page.

It gets better; if you implement their “Statistics & Challenges API”, you'll receive an additional 10%! Finally, if your game is exclusive to Kongregate, or sponsored by them, you receive an additional 15%. This gives you the opportunity to earn up to 50% of the ad revenue for your game on Kongregate. If you're wondering how much that is, check out some of my personal stats:

Step 2: Setting Up Our Work Environment

For this tutorial, we'll be using FlashDevelop, a free (and amazing) open source editor for developers. We'll be doing everything in simple .as files, so if you'd like to follow along using the Flash IDE, you shouldn't have any trouble. If you'd like to use FlashDevelop and are unfamiliar with it, check out this excellent FlashDevelop beginner guide to get you started on what I would consider the best AS3 editor out there.

To begin, open FlashDevelop, go to the Project tab, and select “New Project”. From here, select “AS3 Project with Pre-Loader”. Alternatively, you can grab the Preloader.as and Main.as files from the source download, and simply follow along.

Your file should be a barebones Main.as file, like this:

Nothing above should be new to you; if it is, all you need to know is that this file is the entry point for our program, this is where it all begins. If you compile this with FlashDevelop, you should get a blank white screen, with no compiler errors.

Step 3: Let's Get Connected

Before we dive into all the cool features of the API, we need to make sure that we have the API up and running.

Unlike many sponsor APIs, the Kongregate API isn't a standalone set of files that we need to compile with our project. The API is actually stored on the Kongregate server, and we load it in at runtime. There's a number of ways to do this in your projects, but for the sake of this tutorial, we'll simply connect within our Main.as, and a save a reference to it there.

To start, copy the following code into our Main.as file just below the existing imports:

The above are just a few simple imports that will allow us to use the necessary classes for loading in the Kongregate API.

Next, we'll add a variable to store our reference to the Kongregate API. Go ahead and add the following right above the constructor of our Main.as file.

Notice that the data type of our kongregate variable is *. If you're unfamiliar with this, we're simply telling the compiler that the kongregate variable will accept any data type, much like a wild card.

(Also, note that in a real game you'd want to store your reference to the API somewhere that your entire project has access to, such as a public static const. This reference is needed so that you can use the API from anywhere in your project, for any purpose, rather than just in the Main.as file when we first start up.)

This next piece of code will be contained in a custom function by the name of initKongregateAPI(). This isn't actually necessary, but I prefer to encapsulate ideas when writing code, as it helps keep the code readable and easy to work with.

Go ahead and add this function below the init function in Main.as.

While that may look like a lot of code, it's really not much, and with the comments, it's quite easy to follow.

As you'll see, in the first part we're creating a variable to store the API path from the FlashVars (if you don't know what these are, look them up really quick, they're a great thing to understand).

In the second chunk, we determine whether the SWF is on the Kongregate website or running locally, and we assign the proper information to the apiPath variable.

Next, we give the API access to the SWF, with a simple security.allowDomain call, where we pass in the apiPath as the parameter.

We then create a new URLRequest object, which gets the apiPath passed in to the constructor, a new Loader object, and add an event listener for the loader which will call loadComplete when done.

Last, we call loader.load and pass in our request (the newly created URLRequest object, which contains the apiPath of the Kongregate API). If you understand what just happened, great; if not, don't sweat it, as you won't have to touch this again.

Don't Forget to Call It!

Now that the initKongregateAPI function is created, and contains all of the connection code, we should probably make sure this function actually gets called! Simply go back to the init function that our Main.as file already contained, and add a function call to initKongregateAPI after the line that "entry point" line, like so,

Finally, we need to add that loadComplete function, to be called when the COMPLETE event is fired from our previous code. Add this function below the initKongregateAPI function in Main.as.

The above code is super simple; let's go over it. We start off by saving a reference to the Kongregate API. As you can see, we're referencing the Kongregate API through the passed in event parameter, via event.target.content - simple enough.

Now all we have to do is connect, and our SWF is good to go. As you can see, we connect by calling the kongregate.services.connect method. No arguments required.

While that may have seemed like a lot of work, it really wasn't. I simply went over the connection process in a lot of detail, so that you can understand how we're actually gaining access to the API, rather than just having that access and using it. Now that you understand it, you can use all the above as boilerplate code.

Step 4: The Statistics & Challenges API

Now that we're connected, we can take a look at the most important feature of the entire API: the Statistics & Challenges portion. This API sends player related stats to the Kongregate server, which enables a number of things.

First off, this is the most basic way to allow users to compete for high scores on Kongregate. With the API integrated, the Kongregate side bar will include a new tab labeled “ACHIEVEMENTS”, which can be found next to the “CHAT” tab. Players can view leaderboards for any stat you send to the servers, which could be anything from a basic high score to the total number of enemies defeated.

The second and far more important use, is to allow Kongregate to use the stats you submit to create "badges" for your games. Badges are a central part of the Kongregate user experience, and are much like the achievement systems on platforms such as Xbox LIVE.

The best part about having badges added to your game is that your game will become featured for a short duration, greatly increasing the number of views you get, and thus greatly increasing your ad revenue. Even after your game is out of the spotlight, all badged games on Kongregate continue to receive increased views over normal games, which gives you an excellent long tail revenue stream.

Note that badges aren't added by developers, but are instead created by the Kongregate staff. You'll need a high rated game to get selected, but you'll also need the API to be set up - so let's get that half the battle out of the way!

Step 5: Back-End Preparation

To actually use the stats that we'll be sending, Kongregate first requires us to let their server know what information it should be prepared to receive from us.

To do this, we simply go to the Statistics page for our game on the Kongregate website. This can be found in the "Edit Game" page, or by adding /statistics to the end of your game's URL (for example, http://www.kongregate.com/games/EpicShadow/pixel-purge/statistics). For this tutorial, we'll simply upload our test SWF as the “game”.

Before adding any stats to the Statistics & Challenges API, we need to first understand the four types of stats that can be used, and the rules that they are bound to. Values must be positive, and must be whole integers. The four types are as follows:

  • Max: The value on the server will be replaced if the new value is higher than the stored value. For example, a high score of 152,000 would replace an old high score of 120,000.
  • Min: The value on the server will be replaced if the new value is lower than the stored value. For example, in a racing game, a lap time of 31 seconds would replace an older value of 35.
  • Add: The new value will be added to the stored value. A common use of this would be total enemies defeated, player deaths, etc. Too many requests to the server may result in inaccurate data, so it's advised that data is only sent in bulk, such as when a level is completed or when the player dies.
  • Replace: The new value will replace the stored value no matter what. This can be used for a number of things, such as average survival time or player ranking.

Knowing which of the above types you need to use for each of your game stats is extremely important, so make sure you familiarize yourself with the above list. You'll obviously want a list of stats that you want your game to send to Kongregate, so make sure that you have those prepared before you dive into the next step when actually submitting a game.

For the sake of this tutorial, we'll simply use the following stats:

  • Total Clicks (Add)
  • Max Clicks (Max)
  • Last X (Replace)

Once your list is prepared, head to the Statistics page of your game, and input the required data. Once the back-end work is done on the Statistics page, the game will be ready to submit data to the Kongregate server.

Step 6: How to Send Stats

To actually send data to the server, we simply call the "submit" function, which looks like this:

As you can see, the function takes two parameters:

  • statName is the name of your stat. It's very important that the String passed is identical (case sensitive) to the name of the stat you listed in the previous step when prepping the server to handle your stats.
  • value is the actual numeric value to be passed. Even though the data type is Number, remember that your value must be a positive, whole integer.

To call this function in your game, simply do the following:

Even though we had four different types of stats we could send, this function only sends the value; the server itself will look at the information we provided in the previous step to determine how to treat the incoming data. It's as simple as that; now we know how to send data to the server.

Step 7: Prepping Our Project to Send Stats

Now that we've prepped the back-end on the Kongregate website, and we now know how to send data, let's give this project a go.

The first thing we need to do is add some code to our project to actually send our stats. Since the easiest thing to track is mouse input, I've chosen mouse-related stats. As you saw in our previous step, I chose Max Clicks, Total Clicks, and Last X.

Max Clicks will be the high score for how many times we click in a single game, to demonstrate the Max type; Total Clicks will be the grand total of all clicks we've done, to demonstrate the Add type; and Last X will be the x-position of our most recent click, to demonstrate the Replace type.

To track our Mouse clicks, we'll need import the MouseEvent class. Go back to Main.as, and add the following to your imports:

Now we're going to need to add a variable for our Max Clicks stat, to keep track of the total number of clicks per game session. Right below where we added the kongregate reference variable (of data type *), add the following:

We're going to need an Event Listener to listen for our clicks, so we'll add that now. In the init function, right below the call to initKongregateAPI, add the following:

As you can see in the above code, the function called whenever the event it fired is called clicked. Let's go ahead and create that function. Add the following below your loadComplete function:

All we're doing here is incrementing the maxClicks variable by 1, and then submitting all the required information to the Kongregate server. This will add 1 to the Total Clicks stat, send the current maxClicks variable to the server, which will then determine if it's higher than the previous value and replace it if so, and send the x-position of our previous click, which will automatically replace the previous value.

Our SWF may just be a blank screen, but a lot is going on, and we're about to see it in action. Make sure you compile the project before moving on.

Step 8: Testing Our Project

Now it's time to actually upload our project, and see it in action.

Go back to the Kongregate website, head to your game page, and upload the final version of our project. Once you've uploaded the project, you'll be brought to a preview screen, where we can test our project before publishing it. To save the Kongregate staff a lot of time and energy, do everyone a favor and do not press publish on your test SWF. (If you're working on a real game, go ahead, but for the sake of this tutorial we will not be publishing this project.)

Once you're on the test page, give the game a few clicks. Refresh the page, and you should now see that there is a “HIGH SCORES” tab next to the “CHAT” and “GAME” tab. If you've done everything correctly up to this point, you should have a drop down box that currently reads “Last X” that also contains “Max Clicks” and “Total Clicks”. Note that clicking quickly will result in innacurate stats, as the server can't keep up with all the requests, so click slowly for best results. This is why I advised earlier that you send large batches of data upon death, or level completion, when possible.

Well, there you go: you've now got the most important portion of the Kongregate API up and running. If your project isn't working at this point, make sure that your Kongregate back-end stat names are typed exactly as they are in your submit function - case-sensitive - as that's usually the problem.

You can also find the completed code in the final files folder in the source download, so compare your code to that if you're still having issues.

Step 9: Mass Message Communications

Ever released a game, then later, really wanted to reach out to all of your fans? Well, with the Kongregate API, you can do just that - at least, for all of your Kongregate fans.

There are some restrictions on who can do this, but these restrictions are very much in the best interest of both developers and players. In order to qualify, your game must receive a 3.75 rating or higher, and have at least 10k gameplays.

You can send an “active players” message at most once every seven days. These messages will be sent to any players who have played the game at least three times ever, and at least once within the last ten days.

You can send an “inactive players” message at most once every 30 days. These messages will be received by any players who have played at least five times total, but not within the last ten days.

There are many of reasons to send these messages to your players, such as alerting them of bug fixes, or perhaps informing them of an upcoming sequel. Regardless of what you use this for, it's an incredibly useful system that can really help you leverage your fans.

For more information, see this guide.

So Much More...

While we've covered a lot in this tutorial, the Kongregate API is capable of doing much more. Unfortuantely, I'd have to write a small book to go over all of the features, especially those that are useful for web based MMOs. If you're interested in checking out what other features the API has to offer, I recommend checking out the Kongregate Developers Center for more.

Now that you know how to get the Kongregate API up and running, I strongly encourage you to add it to all of your future games; if you're lucky, you might even get some badges, and that's when the real fun begins.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.