Home > Games, Programming > How to integrate the Kongregate AS3 API into your game at runtime

How to integrate the Kongregate AS3 API into your game at runtime

December 6th, 2007

Kongregate as finally released an AS3 version of their API. There are two methods to integrate the API with your game. The first method is to download a component and compile it into your game. The second method is to load the API at runtime.

As easy as it is to integrate with the Kongregate API through their component, I prefer to do as much as I can through ActionScript without using the Flash IDE. Also, if you are a game developer that posts your game to multiple portals with their own APIs, you may want to only include the API for each domain as needed.

I’ve provided the source code below for how I integrated the API into my own games, and it can also be downloaded here.

Documentation for the KongregateApi can be found here.

com/digitalmachina/KongregateApiConnection.as

//==============================================================================
// Created by: Jeff Mastropietro
// http://www.digitalmachina.com/
//
// This work is licensed under a Creative Commons Attribution 3.0 United States
// License http://creativecommons.org/licenses/by-sa/3.0/us/
//==============================================================================

package com.digitalmachina
{
	import flash.display.LoaderInfo;
	import flash.display.Loader;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.system.Security;
	
	import com.digitalmachina.KongregateApiConnectionEvent;
	
	public class KongregateApiConnection extends flash.display.Loader
	{
		private var __api:Object;
		private var __loaded:Boolean;
		private var __type:String;
		private var __url:String;
		
		public function KongregateApiConnection(stage:Stage)
		{
			//trace("com.digitalmachina.KongregateApiConnection(" + stage + ")");
			
			this.__loaded = false;
			this.__type = "kongregate";
			
			// update the security settings to allow any kongregate domain
			flash.system.Security.allowDomain("*.kongregate.com");
			
			// see if api_path is set in FlashVars
			var params:Object = LoaderInfo(stage.loaderInfo).parameters;
			
			// set the correct api path 
			this.__url = (params.api_path != undefined) ? params.api_path : "http://www.kongregate.com/flash/API_AS3_Local.swf";
			
			// add a listener for when the api is loaded
			this.contentLoaderInfo.addEventListener(Event.COMPLETE, this.__loaderComplete);
			
			// add the loader to the stage
			stage.addChild(this);
		}
		
		public function get type():String
		{
			return this.__type;
		}
		
		public function get url():String
		{
			return this.__url;
		}
		
		public function get connected():Boolean
		{
			return (this.__api != null) ? this.__api.isConnected() : false;
		}
		
		public function get loaded():Boolean
		{
			return this.__loaded;
		}
		
		public function get services():Object
		{
			if (!this.loaded) {
				throw new Error("Kongregate API is not loaded.");
			}
			
			return this.__api.services;
		}
		
		public function get scores():Object
		{
			if (!this.loaded) {
				throw new Error("Kongregate API is not loaded.");
			}
			
			return this.__api.scores;
		}
		
		public function get stats():Object
		{
			if (!this.loaded) {
				throw new Error("Kongregate API is not loaded.");
			}
			
			return this.__api.stats;
		}
		
		public function get user():Object
		{
			if (!this.loaded) {
				throw new Error("Kongregate API is not loaded.");
			}
			
			return this.__api.user;
		}
		
		public function connect():void
		{
			//trace("com.digitalmachina.KongregateApiConnection.connect()");
			
			// if a connection has not already been established
			if (!this.connected) {
				
				// create url request with the correct path
				var request:URLRequest = new URLRequest(this.__url);
				
				// attempt to load the api
				this.load(request);
			}
		}
		
		private function __loaderComplete(event:Event):void
		{
			//trace("com.digitalmachina.KongregateApiConnection.__loaderComplete(" + event + ")");
			
			this.__loaded = true;
			
			// Save Kongregate API reference
			this.__api = event.target.content;
			
			// connect Kongregate services
			this.__api.services.connect();
			
			// dispatch a connected event
			var connectedEvent = new KongregateApiConnectionEvent(KongregateApiConnectionEvent.CONNECTED);
			this.dispatchEvent(connectedEvent);
		}
	}
}

com/digitalmachina/KongregateApiConnectionEvent.as

//==============================================================================
// Created by: Jeff Mastropietro
// http://www.digitalmachina.com/
//
// This work is licensed under a Creative Commons Attribution 3.0 United States
// License http://creativecommons.org/licenses/by-sa/3.0/us/
//==============================================================================

package com.digitalmachina
{
	import flash.events.Event;
	
	public class KongregateApiConnectionEvent extends flash.events.Event
	{
		public static const CONNECTED:String = "connected";
		
		public function KongregateApiConnectionEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false)
		{
			super(type, bubbles, cancelable);
		}
		
		override public function clone():Event
		{
			return new KongregateApiConnectionEvent(this.type, this.bubbles, this.cancelable);
		}
		
		override public function toString():String
		{
			return "[KongregateApiConnectionEvent type="" + this.type + "" bubbles=" + this.bubbles + " cancelable=" + this.cancelable + " eventPhase=" + this.eventPhase + "]";
		}
	}
}

This is an example of how to instantiate KongregateApiConnection. Place this code in your game where you want to create a connection to the API.

import com.digitalmachina.KongregateApiConnection;

var apiConnection:*;
if (stage.loaderInfo.url.indexOf("file://") == 0 || stage.loaderInfo.url.indexOf("kongregate") > 0) {
	apiConnection = new KongregateApiConnection(stage);
	apiConnection.connect();
}

This is an example of how to submit a score using KongregateApiConnection. Place this code in your game where you want to submit a score to the API.

if (apiConnection != null && apiConnection.type == "kongregate") {
	apiConnection.scores.submit(score);
}

Download the source here.

  1. December 12th, 2007 at 17:13 | #1

    hrm… I’m having problems.

    when I use your code, I receive the following error:

    ReferenceError: Error #1069: Property score not found on com.digitalmachina.KongregateApiConnection and there is no default value.
    at dream_fla::MainTimeline/onMouseClickEventScore()

  2. December 13th, 2007 at 09:15 | #2

    Sorry about that steven, there was a typo in the example code. I’ve corrected it to be the following:

    if (apiConnection != null && apiConnection.type == "kongregate") {
    	apiConnection.scores.submit(score);
    }
    
  3. December 13th, 2007 at 16:46 | #3

    thank you!! I figured it was just a small error.

    I really appreciate you taking the time to make this.

    In your article, you mentioned that this is useful when building a game for multiple networks… so I am assuming that if you are NOT playing this on Kongregate.com that there is no way to post a high score? Is this correct?

    Also, do you know if any other networks support as3 high scores?

    is the Kongregate highscore API secure?

  4. December 13th, 2007 at 20:20 | #4

    I’m actually not sure if Kongregate’s API works when your game isn’t hosted on their site. I haven’t tried. Their API only works if the player is logged in to their site though, so it probably wouldn’t be much use.

    MochiAds, the ad delivery network that many game developers use, also has an AS3 high score API available. It doesn’t have as many features as the Kongregate API, but they have plans to expand it. There may also be other portal sites that have APIs as well.

    If I get some more time, I want to do some more research on the other available APIs that are out there. Right now I’m spending most of my free time on my next game.

    As far as security is concerned for Kongregate’s API, it only works if the player has an active session on Kongregate, so it is more secure than a completely open high score API. I dedicated person could still probably get a bogus high score through, but Kongregate would probably catch it and nuke their account.

  5. December 13th, 2007 at 20:32 | #5

    Jeff, that is some very interesting information.

    keep an eye on this account for my first game before Monday, it’ll be using papervision 3d and as3.

    It’s called ‘Christmas Chaos’, and is more of an open test to see if these games can be a viable income or not. I will post the results on my website.

    http://www.kongregate.com/accounts/sstark

    Thanks again for all the help! 🙂

    good luck on your newest game.

  6. December 15th, 2007 at 02:12 | #6

    the game is online here:

    http://www.kongregate.com/games/sstark/christmas-chaos

    however I am having another problem… the posting of a high score only works once, then I have to refresh the page to have it work again. Any idea why?

    thanks!

Comments are closed.