Guide to Mochi Media services – Leaderboards

Once you are able to set up a game with Mochi Media and enable it for live update and connect with Mochi Services and use Link Tracking, it’s time to learn something which will tie players in front of their monitors until they show the world how much they rock: leaderboards.

Mochi Media offers to developers a great set of features, allowing them to create they own leaderboards with all kind of social options.

First things first, so let’s start from the game dashboard, with the Scores section yet to be activated. Click on ACTIVATE and you are ready to enter the world of leaderboards.

In the Mochi Scores API landing page, it will be asked to create a new leaderboard. Click on CREATE LEADERBOARD.

Now you have a list of options to custom your leaderboard as you want.

Let’ see them:

Title: the title of the leaderboard, will appear in the top of it.

Description: an optional description. Since you are allowed to create more leaderboards in a single game adding a brief description for your own use is not a bad idea.

Type of scoring: this is where you will decide if your score is numeric or represents time (like in racing games), if the higher the better or the lower the better, you can give your score a label such as “Score”, “Points”, “Lap time” and so on, and you can optionally set achievements. Such achievements are not part of the Achievement API, they are just three medals, Bronze, Silver and Gold, you can earn if you reach a certain score.

Time Period Display: leaderboards can show daily, weekly, monthly and overall scores, now you are deciding which of them to display once the leaderboard opens.

Background Style: You can give leaderboards a solid background color or if you prefer you can leave the background transparent.

Once you’re done, click on CREATE LEADERBOARD and that’s it! Your leaderboard is ready.

There’s nothing more to do on the dashboard at the moment, so click on actiosncript code and write down the Leaderboard Id

Now it’s time to add some code to the script we’ve seen in the previous step:

package {
	import flash.display.Sprite;
	import mochi.as3.*;
	import flash.events.Event;
	import flash.events.MouseEvent;
	public class gameMc extends Sprite {
		private var showPlayerName:showPlayerNameMc;
		private var showTopScore:showTopScoreMc;
		public function gameMc() {
			mochi.as3.MochiScores.setBoardID("a87ab09ee29bc3bc");
			/* show leaderboard button */
			var showBoard:showBoardMc = new showBoardMc();
			addChild(showBoard);
			showBoard.x=20;
			showBoard.y=100;
			showBoard.buttonMode=true;
			showBoard.addEventListener(MouseEvent.CLICK,showBoardClick);
			/* show leaderboard and add score button */
			var showBoardWScore:showBoardWScoreMc = new showBoardWScoreMc();
			addChild(showBoardWScore);
			showBoardWScore.x=20;
			showBoardWScore.y=130;
			showBoardWScore.buttonMode=true;
			showBoardWScore.addEventListener(MouseEvent.CLICK,showBoardWScoreClick);
			/* show leaderboard and add score and name button */
			var showBoardWName:showBoardWNameMc = new showBoardWNameMc();
			addChild(showBoardWName);
			showBoardWName.x=20;
			showBoardWName.y=160;
			showBoardWName.buttonMode=true;
			showBoardWName.addEventListener(MouseEvent.CLICK,showBoardWNameClick);
			/* show big leaderboard button */
			var showBigBoard:showBigBoardMc = new  showBigBoardMc();
			addChild(showBigBoard);
			showBigBoard.x=20;
			showBigBoard.y=190;
			showBigBoard.buttonMode=true;
			showBigBoard.addEventListener(MouseEvent.CLICK,showBigBoardClick);
			/* show player name button */
			showPlayerName = new showPlayerNameMc();
			addChild(showPlayerName);
			showPlayerName.x=20;
			showPlayerName.y=220;
			showPlayerName.buttonMode=true;
			showPlayerName.nameText.mouseEnabled=false;
			showPlayerName.addEventListener(MouseEvent.CLICK,showPlayerNameClick);
			/* show top score button */
			showTopScore = new showTopScoreMc();
			addChild(showTopScore);
			showTopScore.x=20;
			showTopScore.y=250;
			showTopScore.buttonMode=true;
			showTopScore.scoreText.mouseEnabled=false;
			showTopScore.addEventListener(MouseEvent.CLICK,showTopScoreClick);
			//;
			addEventListener(Event.ADDED_TO_STAGE,onAddedToStage);
		}
		private function onAddedToStage(e:Event):void {
			var mochiContainer:Sprite=new Sprite();
			stage.addChild(mochiContainer);
			var visitBlog:visitBlogMc=new visitBlogMc();
			mochiContainer.addChild(visitBlog);
			MochiServices.addLinkEvent('http://x.mochiads.com/link/7bb0d7adfc9263d3', 'http://www.emanueleferonato.com/', mochiContainer);
		}
		/* simply showing leaderboard */
		private function showBoardClick(e:MouseEvent):void {
			// mochi.as3.MochiScores.showLeaderboard(); <-- NO!!!
			// mochi.as3.MochiScores.showLeaderboard({boardID:"a87ab09ee29bc3bc"}); <-- YES
			mochi.as3.MochiScores.showLeaderboard({});
		}
		/* showing leaderboard adding a random score */
		private function showBoardWScoreClick(e:MouseEvent):void {
			var myScore:int=Math.floor(Math.random()*100);
			mochi.as3.MochiScores.showLeaderboard({boardID:"a87ab09ee29bc3bc",score:myScore});
		}
		/* showing leaderboard adding a random score and a name */
		private function showBoardWNameClick(e:MouseEvent):void {
			var myScore:int=Math.floor(Math.random()*100);
			var myName:String="triqui_"+Math.floor(Math.random()*10000).toString();
			mochi.as3.MochiScores.showLeaderboard({boardID:"a87ab09ee29bc3bc",score:myScore,name:myName});
		}
		/* showing a big leaderboard */
		private function showBigBoardClick(e:MouseEvent):void {
			var myScore:int=Math.floor(Math.random()*100);
			mochi.as3.MochiScores.showLeaderboard({boardID:"a87ab09ee29bc3bc",score:myScore,width:640,height:400});
		}
		/* showing player name */
		private function showPlayerNameClick(e:MouseEvent):void {
			MochiScores.getPlayerInfo(this,gotPlayerInfo);
		}
		private function gotPlayerInfo(playerObj:Object):void {
			showPlayerName.nameText.text=playerObj.name;
			// trace(playerObj.score);
		}
		/* showing top score */
		private function showTopScoreClick(e:MouseEvent):void {
			mochi.as3.MochiScores.requestList(this,requestListReceived);
		}
		private function requestListReceived(scoreObj:Object):void {
			var theScores:Object=mochi.as3.MochiScores.scoresArrayToObjects(scoreObj.scores);
			showTopScore.scoreText.text=theScores.alltime[0].name+": "+theScores.alltime[0].score;
		}
	}
}

As you can see, most of the code is used to create some buttons and add a click listener, so let's jump straight to leaderboards code.

mochi.as3.MochiScores.setBoardID("a87ab09ee29bc3bc");

setBoardID method tells Mochi Scores API which board we are currently handling. Remember a game can have more than one leaderboard, so in this case we are saying from now on we are working on leaderboard a87ab09ee29bc3bc, which is the string I told you to write down once you created the leaderboard.

mochi.as3.MochiScores.showLeaderboard({});

showLeaderboard method will just show the leaderboard, without adding any score. It's the simplest thing to do, and just requires an empty object.

Remember the object is mandatory, so calling the leaderboard this way:

// mochi.as3.MochiScores.showLeaderboard(); <-- NO!!!

will not work, while you can specify the leaderboard id on the fly, overriding the one set with setBoardID method, this way:

// mochi.as3.MochiScores.showLeaderboard({boardID:"a87ab09ee29bc3bc"}); <-- YES

And as you can see, with a single line of code you can open a fully functional leaderboard.

Let's see how to add scores.

var myScore:int=Math.floor(Math.random()*100);
mochi.as3.MochiScores.showLeaderboard({boardID:"a87ab09ee29bc3bc",score:myScore});

Now a random number from 0 to 99 is created in a variable called myScore, then is passed in the argument object as score. This will make the leaderboard ask for player's name, then show the top scores, eventually with the one just submitted, if good enough.

What if you already ask for player's name, maybe in a role playing game when the player is asked to create his character?

var myScore:int=Math.floor(Math.random()*100);
var myName:String="triqui_"+Math.floor(Math.random()*10000).toString();
mochi.as3.MochiScores.showLeaderboard({boardID:"a87ab09ee29bc3bc",score:myScore,name:myName});

This time not only we create a random score, but a random name too, and we pass it in the argument object as name. This will make the leaderboard directly save name and score without player interaction.

Also note leaderboards use shared objects to manage multiple scores of the same player, and only the best score is saved, along with its name. So don't worry if you enter a lot of names with different scores, and see only the highest one. It's the way it works.

You can also define the leaderboard size this way:

mochi.as3.MochiScores.showLeaderboard({boardID:"a87ab09ee29bc3bc",score:myScore,width:640,height:400});

width and height are intended in pixels, and you have to specify both of them if you want it to work.

But the best has yet to come. You can retrieve leaderboard and player information without displaying any graphics. This way, you can create your custom leaderboard.

MochiScores.getPlayerInfo(this,gotPlayerInfo);

getPlayerInfo method gets player information and calls a function (like a callback) once it's done. In this case, gotPlayerInfo function (line 91) is called after player information has been stored into an object, available as argument.

showPlayerName.nameText.text=playerObj.name;

This is how I am writing the player name on a dynamic text field. If you change playerObj.name with playerObj.score, you will print player's best score.

As you can see, no leaderboard id is specified in getPlayerInfo method. That's because it gets the id from setBoardID, which in this case is mandatory to use the data APIs.

And you can even get up to the best 50 scores with requestList method this way:

mochi.as3.MochiScores.requestList(this,requestListReceived);

then call requestListReceived function once the scores are available into an object like this:

{ now: 1197420828414.14,
places: { daily: "100%", weekly: "100%", monthly: "100%" },
counts: { daily: 2, weekly: 4, monthly: 8 },
daily: { cols: ["name", "geo", "score", "timestamp"], rows: [["george", "us", 3333, 1197420828414.14], …]},
weekly: { cols: ["name", "geo", "score", "timestamp"], rows: [["george", "us", 3333, 1197420828414.14], …]},
monthly: { cols: ["name", "geo", "score", "timestamp"], rows: [["george", "us", 3333, 1197420828414.14], …]}
}

Then with scoresArrayToObjects method (line 100) you can convert the array of arrays returned by requestList into an array of objects whose keys are derived from cols and finally display them (line 101).

And the same setBoardID thing applies to this method.

Enough at the moment, there are a couple more of interesting features but I'll merge them in next tutorial, meanwhile look at this recap:

Every button has its own function as explained in this tutorial, play a bit and try to make a decent score.

Download the source code.

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