How to create a leaderboard in your Flash game with Scoreoid

Some days ago I showed you how to save and show the best score in your game with Scoreoid.

Now it’s time to make something more interesting, such as a top 5 leaderboard. If you followed the first step, you should know one of the best Scoreid features is there isn’t any SDK since the Scoreoid Open Web API is based on the standard RESTful HTTP/HTTPS protocol.

Anyway, this is the new version of the game, with the top 5 at the bottom right of the stage:

You know how to play: mouse button to turn on engines, avoid the squares, collect the circles and travel as far as you can. Notice the leaderboard in the bottom right corner.

I just created another sprite called Leaderboard with a dynamic text in it, and made some changes to the main class. In the script, I highlighted the changes from the previous version.

package {
	import flash.display.Sprite;
	import flash.filters.GlowFilter;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.net.URLLoader;
	import flash.net.URLRequestMethod;
	import flash.net.URLLoaderDataFormat;
	public class Main extends Sprite {
		private var shipFilter:GlowFilter=new GlowFilter(0x00ff00,0.8,4,4,2,3,false,false);
		private var smokeFilter:GlowFilter=new GlowFilter(0xff0000,0.8,4,4,2,3,false,false);
		private var fuelFilter:GlowFilter=new GlowFilter(0x00ffff,0.8,4,4,2,3,false,false);
		private var rockFilter:GlowFilter=new GlowFilter(0xffffff,0.8,4,4,2,3,false,false);
		private var gravity:Number=0.1;
		private var thrust:Number=0.25;
		private var yspeed:Number=0;
		private var xspeed:Number=5;
		private var distance:Number=0;
		private var smokeInterval:Number=10;
		private var framesPassed:Number=0;
		private var fuelFrequency:Number=10;
		private var gasoline:Number=500;
		private var rockFrequency:Number=50;
		private var engines:Boolean=false;
		private var ship:Ship=new Ship();
		private var score:Score=new Score();
		private var leaderboard:Leaderboard=new Leaderboard();
		private var rockCanvas:Sprite=new Sprite();
		private var fuelCanvas:Sprite=new Sprite();
		private var smokeCanvas:Sprite=new Sprite();
		private var fuelVector:Vector.<Fuel>=new Vector.<Fuel>();
		private var rockVector:Vector.<Rock>=new Vector.<Rock>();
		private var smokeVector:Vector.<Smoke>=new Vector.<Smoke>();
		public function Main() {
			getBest();
			addChild(ship);
			ship.x=120;
			ship.y=240;
			ship.filters=new Array(shipFilter);
			addChild(rockCanvas);
			addChild(fuelCanvas);
			addChild(smokeCanvas);
			addChild(score);
			addChild(leaderboard);
			addEventListener(Event.ENTER_FRAME,update);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,engineOn);
			stage.addEventListener(MouseEvent.MOUSE_UP,engineOff);
		}
		private function engineOn(e:MouseEvent):void {
			engines=true;
			framesPassed=smokeInterval;
		}
		private function engineOff(e:MouseEvent):void {
			engines=false;
			smokeInterval=10;
		}
		private function update(e:Event):void {
			if (Math.random()*1000<fuelFrequency) {
				var fuel:Fuel=new Fuel();
				fuel.y=Math.random()*400+40;
				fuel.x=650;
				fuel.filters=new Array(fuelFilter);
				fuelCanvas.addChild(fuel);
				fuelVector.push(fuel);
			}
			if (Math.random()*1000<rockFrequency) {
				var rock:Rock=new Rock();
				rock.y=Math.random()*400+40;
				rock.x=670;
				rock.rotation=Math.random()*360;
				rock.filters=new Array(rockFilter);
				rockCanvas.addChild(rock);
				rockVector.push(rock);
			}
			distance+=xspeed;
			score.scoreText.text="Distance: "+distance+"\nFuel: "+gasoline;
			if ((gasoline>0)&&(engines)) {
				yspeed-=thrust;
				smokeInterval-=0.25;
				gasoline-=1;
				framesPassed++;
				if (smokeInterval<framesPassed) {
					var smoke:Smoke=new Smoke();
					smoke.x=ship.x;
					smoke.y=ship.y;
					smoke.filters=new Array(smokeFilter);
					smokeCanvas.addChild(smoke);
					smokeVector.push(smoke);
					framesPassed=0;
					smokeInterval-=0.01;
				}
			}
			yspeed+=gravity;
			ship.y+=yspeed;
			angle=Math.atan2(yspeed,xspeed);
			ship.rotation=angle*180/Math.PI;
			for (var i:int=fuelVector.length-1; i>=0; i--) {
				fuelVector[i].x-=xspeed*1.2;
				var dist_x:Number=ship.x+28*Math.cos(angle)-fuelVector[i].x;
				var dist_y:Number=ship.y+28*Math.sin(angle)-fuelVector[i].y;
				var dist:Number = Math.sqrt(dist_x*dist_x+dist_y*dist_y);
				if (dist<10) {
					gasoline+=100;
					fuelCanvas.removeChild(fuelVector[i]);
					fuelVector.splice(i,1);
				}
				else {
					if (fuelVector[i].x<-10) {
						fuelCanvas.removeChild(fuelVector[i]);
						fuelVector.splice(i,1);
					}
				}
			}
			for (i=rockVector.length-1; i>=0; i--) {
				rockVector[i].x-=xspeed;
				if (rockVector[i].x<-20) {
					rockCanvas.removeChild(rockVector[i]);
					rockVector.splice(i,1);
				}
			}
			for (i=smokeVector.length-1; i>=0; i--) {
				smokeVector[i].x-=xspeed;
				smokeVector[i].width+=0.2;
				smokeVector[i].height+=0.2;
				smokeVector[i].alpha-=0.04;
				if (smokeVector[i].alpha<0) {
					smokeCanvas.removeChild(smokeVector[i]);
					smokeVector.splice(i,1);
				}
			}
			if (ship.y>480 || ship.y<0 || rockCanvas.hitTestPoint(ship.x+28*Math.cos(angle), ship.y+28*Math.sin(angle), true) || rockCanvas.hitTestPoint(ship.x+8*Math.cos(angle+Math.PI/2), ship.y+8*Math.sin(angle+Math.PI/2), true) || rockCanvas.hitTestPoint(ship.x+8*Math.cos(angle-Math.PI/2), ship.y+8*Math.sin(angle-Math.PI/2), true)) {
				postScore();
				yspeed=0;
				ship.y=200;
				gasoline=500;
				distance=0;
				rockVector=new Vector.<Rock>();
				removeChild(rockCanvas);
				rockCanvas=new Sprite();
				addChild(rockCanvas);
				fuelVector=new Vector.<Fuel>();
				removeChild(fuelCanvas);
				fuelCanvas=new Sprite();
				addChild(fuelCanvas);
				smokeVector=new Vector.<Smoke>();
				removeChild(smokeCanvas);
				smokeCanvas=new Sprite();
				addChild(smokeCanvas);
			}
		}
		private function postScore():void {
			var url:String="https://www.scoreoid.com/api/createScore";
			var request:URLRequest=new URLRequest(url);
			var requestVars:URLVariables = new URLVariables();
			request.data=requestVars;
			requestVars.api_key="ab6df379525fea384c690532df9550e38c948707";
			requestVars.game_id="690bf9d6ab";
			requestVars.response="XML";
			requestVars.username="Demo name";
			requestVars.score=distance;
			request.method=URLRequestMethod.POST;
			var urlLoader:URLLoader = new URLLoader();
			urlLoader = new URLLoader();
			urlLoader.dataFormat=URLLoaderDataFormat.TEXT;
			urlLoader.addEventListener(Event.COMPLETE, scorePosted);
			urlLoader.load(request);
		}
		private function scorePosted(event:Event):void {
			getBest();
		}
		private function loaderCompleteHandler(event:Event):void {
			var xml:XML=new XML(event.target.data);
			leaderboard.scoreText.text="TOP SCORES\n\n";
			for (var i:Number=0; i<5; i++) {
				var player:XML=xml.child("player")[i];
				leaderboard.scoreText.appendText((i+1)+") "+player.child("score").attribute("score")+"\n");
			}
		}
		function getBest():void {
			var url:String="https://www.scoreoid.com/api/getScores";
			var request:URLRequest=new URLRequest(url);
			var requestVars:URLVariables = new URLVariables();
			request.data=requestVars;
			requestVars.api_key="xxxxx";
			requestVars.game_id="yyyyy";
			requestVars.response="XML";
			requestVars.order_by="score";
			requestVars.order="desc";
			requestVars.limit="5";
			request.method=URLRequestMethod.POST;
			var urlLoader:URLLoader = new URLLoader();
			urlLoader = new URLLoader();
			urlLoader.dataFormat=URLLoaderDataFormat.TEXT;
			urlLoader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
			urlLoader.load(request);
		}
	}
}

As you can see, it’s just a matter of using getScores() method to retrieve a number (requestVars.limit) of game scores ordered by a desired way (requestVars.order_by) in a particular order (requestVars.order).

You will get an XML like this one:

<scores>
  <player username="Demo Name" email="" first_name="" last_name="" platform="">
    <score score="42185" difficulty="0" platform="" leaderboard="" created="2013-06-07 18:32:42" data=""/>
  </player>
  <player username="Demo Name" email="" first_name="" last_name="" platform="">
    <score score="42085" difficulty="0" platform="" leaderboard="" created="2013-06-05 21:14:17" data=""/>
  </player>
  <player username="Demo Name" email="" first_name="" last_name="" platform="">
    <score score="41940" difficulty="0" platform="" leaderboard="" created="2013-06-11 00:00:33" data=""/>
  </player>
  <player username="Demo Name" email="" first_name="" last_name="" platform="">
    <score score="39175" difficulty="0" platform="" leaderboard="" created="2013-06-06 13:10:19" data=""/>
  </player>
  <player username="Demo Name" email="" first_name="" last_name="" platform="">
    <score score="38540" difficulty="0" platform="" leaderboard="" created="2013-06-11 00:44:44" data=""/>
  </player>
</scores>

Which is pretty easy to parse by loaderCompleteHandler function. Refer to understanding AS3 and XML if you don’t know how to parse XML.

And that’s another great Scoreoid feature unveiled, next time I am going to show you even more.

No need to download anything, just copy/paste this code in the file you can get from the original prototype, just remember to use your own game id and api key.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers