Mochi Support Center
Developer Support
Table of Contents
-
Analytics API Documentation
-
Ads API
-
Live Updates
-
Scores API
Link Tracking API
Universal Data Storage
Analytics API Documentation
1.1 Overview
The Analytics API provides developers with a means of tracking user game information. This includes session durations, how long the average player spends in an average round of play, as well as tracking other events such as item pick-ups, reaching waypoints.
1.2 Prerequisites
MochiAPI is not compatible with versions prior to Flash Player 9, and is no longer compatible with ActionScript 1.0.
Installing the Mochi Analytics Tracking API
- Download and unzip the latest MochiAPI.
- Copy the “mochi” folder and paste it into the root classpath of your game. Most often this is the same as the location of your game’s FLA file.
1.3 Connecting to MochiServices
connect
Description:
Retrieves and initializes the MochiServices.swf from Mochi servers. Any API calls executed prior to the complete download and initialization of the MochiServices.swf are queued and will be executed once the API is available
Parameters:
- id:String
- Mochi game ID
- clip:Object
- the MovieClip or Sprite in which to load the API (optional for all but AS3, defaults to _root). In as3 the clip must be dynamic.
- onError:Function
-
This method will be invoked if MochiServices cannot connect to the server or any IO errors occur in any other API calls.
onError handlers will receive status codes that describe the error. The possible errors are:
- NotConnected — Services were unable to connect or attach to a clip in the current movie.
- IOError — Services has connected but cannot transfer data to and from the server.
AS3 Example:
mochi.as3.MochiServices.connect("xxx", root, onConnectError); // use mochi.as2.MochiServices.connect for AS2 API
public function onConnectError(status:String):void {
// handle error here...
}
… where ‘xxx’ is your Mochi game ID, in quotes. Test your movie, and you should see the following text in your output panel:
MochiServices Connecting…
Waiting for Mochi services to connect…
connected!
If you see the text above, then that means you have the "mochi" folder in the correct location, and have supplied MochiServices the correct Mochi game ID. Keep in mind that you want to connect to MochiServices as early as possible in your game, and before you make any other API calls. You only need to make this call once in the beginning of your game.
AS3 Requirement - The clip parameter
In ActionScript 3, the root of the Stage cannot be accessed globally. If a Sprite or MovieClip does not have access to the root or to another Display Container that has been added to the display list, then it can not be shown visually on the screen. For this reason, you must supply either the root of your stage or a reference to a Sprite or MovieClip that is a child of the stage to the clip parameter when you call MochiServices.connect. Please note the clip passed must also be dynamic.
Ads API Documentation
This is a simple step-by-step guide to getting Mochi Ads API working with your Flash game. The first two sections describe all that is required to get your ads running.
NOTE: The easiest way to implement MochiAds is by simply using our Live Updates system
1.1 Prerequisites:
MochiAPI is not compatible with versions prior to Flash Player 9, and is no longer compatible with ActionScript 1.0.
Before you get started, make sure you have done the following:
- Sign up for a Mochi Developer account on www.mochimedia.com
- Log in and add a new game to your account.
- Download the MochiAPI classes ZIP package.
- Choose your code options and copy the Mochi Ads API in-game code.
1.2 The Mochi API Ad Codes:
If you ever find yourself forgetting how to implement the ad code, you can find a customized code snippet by going to your Mochi developer dashboard, selecting your game, click on "Ads" on the left and then "Mochi Ads Code: Get the ad code and installation instructions" beneath the Default Ad Settings.
Also, there are different examples for ads in the "examples" directory.
Figure a: The MochiAPI ZIP package folder structure.
You need two things for Mochi Ads API to work properly in your game -- The mochi include folder, and the in-game code.
The include folder contains the ActionScript code that your game will reference to display your ad. You will never need to edit this code. You just need to make sure that it is in the proper location so that it is imported or included when you publish or compile your game. You only need to do this once for each game, no matter how many ads you show in the game.
The in-game code is the code you paste into your game to display the ad at a specific point in the game. This may be placed in a specific frame on the main timeline of your movie, or called when a specific event is called in your game code. Depending on how you created your game, where you place this code will differ. Just remember, when you make the call to the Mochi Ads API, that's when the ad will show.
Include Folder Installation:
Figure b: Copying the mochi folder to the directory of your .fla.
(Click image to restart animation)
The MochiAPI ZIP package contains the include code necessary for your game. UnZIP the package to a location on your hard drive. If you browse to that location, you will see a group of folders (fig.a).
Make sure to read the README.TXT file for information regarding the latest release of the MochiAPI file include.
Each folder in the package corresponds to a particular coding environment. It's up to you to choose which one is best for you:
- docs: MochiAPI usage documentation.
- examples: Examples using MochiAPI.
- mochi: MochiAPI include folder.
Simply copy the mochi folder and paste it into the
location where you are publishing your game. You do not need to create a
special folder for the include (fig.b).
These instructions also apply to the examples. Simply copy the
mochi folder into the example project direct that you wish to use,
and publish to test.
Adding the In-game Code:
The in-game code is a one-line code snippet that you copy from the
Mochi Developer web site. This code is a method call that tells MochiAPI to launch your ad. You will paste
this code into your game in the place where you want the ad to appear.
Your code looks something like this:
import mochi.as2.*;
MochiAd.showPreGameAd({id:"xxxxxxxxxxxxxxxx",
res:"360x240"});
import mochi.as3.*;
MochiAd.showPreGameAd({id:"xxxxxxxxxxxxxxxx",
res:"360x240"});
NOTE: In the 3.0 revision of the API, we changed namespaces for
our libraries to unify and organize our packages. Now you must explicitly call the
API corresponding to your ActionScript version: mochi.as2.* or
mochi.as3.* respectively. For the purposes of this
documentation we will show examples specifying the ActionScript 2.0 MochiAPI. Simply remove
mochi.as2. from the code samples, and add import mochi.as3.*;
to the beginning of your code block to use the ActionScript 3.0 MochiAPI.
There are five types of ads you can place in your game -- a pre-game ad, an inter-level ad, showcase ads, dock ads and a Click-away ad. Pre-game ads include a preloader bar that grows as your game file is loaded from the web to the player's computer. An inter-level ad is an ad that appears at some point during game-play. The most convenient and unobtrusive time to show ads is usually between game levels, hence the name inter-level ad. Click-away ads are 300x250 ads that can be placed anywhere you specify and will only disappear on a user-initiated action. Both the Showcase and the Dock type load a group of small, thumbnail ads into a frame. Each ad in the frame has its own tracking and clickthrough URLs, and a mouse-over caption bubble. Showcase and Dock types are essentially the same except for their visual appearance and behavior in the game window, and one additional API call available to the Dock type.
You can use the Mochi Developer web site to customize your code for the particular type of ad and version of ActionScript you need.
ACTIONSCRIPT 3 NOTE: ActionScript 3 developers will also notice that there is an additional parameter named clip which passes a reference to the DisplayObject container for your ad to appear. This is required, and by default this is set to root for pre-game and inter-level ads. See below for more info regarding customizing this parameter.
Pre-game Ad:
Figure c: Pasting the pre-game code into a game FLA.
(Click image to restart animation)
To add a pre-game ad with a preloader to your game, simply get the appropriate in-game code from the Mochi Developer web site, and paste it into the main timeline of your movie, in the place you've designated for a preloader (fig.c).
If your game is ready, you can test your movie, and you should see the pre-game ad appear as your movie loads. You may test your ads as much as you like while you develop your game. Keep in mind that your ads will not earn money until you complete your game profile which includes a URL to the completed game. You may also upload your SWF file from the Game Settings page for free hosting.
Inter-level Ad
Figure d: Pasting the inter-level code into a game FLA.
(Click image to restart animation)
To add an inter-level ad to your game, simply get the appropriate code from the Mochi Developer web site, and paste it into the main timeline of your movie, in the place you've designated for your inter-level screen (fig.d).
Just like the pre-game ad, you can test your game and see the inter-level ads in action.
Click-away ad
To add a Click-away ad to your game, simply get the appropriate code
from the Mochi Developer web site. Pass in the DisplayObject container / MovieClip which
will contain the Click-away ad in the clip parameter. The upper left corner
of the 300x250 Click-away ad will be placed at the upper left corner of the DisplayObject
container / MovieClip you specify. When you wish to stop displaying the Click-away ad
pass your clip to MochiAd.unload() depending on your respective ActionScript version
publish settings.
You must assign a MovieClip? to the clip parameter when using a Click Away ad. The reason you must do this is so our Ads API knows where to put the Click Away ad in your game. If you didn't do this, we wouldn't know where to put the ad. Should it appear in your main menu? On your game's stage? Inside an inventory window? On top of the avatar's head?
NOTE: The easiest thing to do is create an empty MovieClip?, name it appropriately like clickAwayAdMovieClip and place it somewhere on your stage. This is now the clip you assign to the Click Away ad clip parameter.
Showcase and Dock Ads (AS3 ONLY)
Two new ad methods were introduced with version 4.0 of the MochiAds API. These methods are
To add a showcase or dock type to your game, use the example code below. The Showcase or Dock will display a row or column of ads in a rectangle.
A game can contain one Showcase and one Dock ad which will remain available for the duration of the game, but can be hidden or revealed by calling the appropriate methods on the API. See specific methods below.
You must assign an empty MovieClip to the 'clip' property when using a Showcase or Dock ad.
This MovieClip instance must be above all other game assets in the display list and must be positioned
at the top left corner of the game area. (0,0)
Showcase Ads
The API call will load a Mochi Showcase Ad into the clip. The Showcase loads a number of small, static ads into a horizontal row of thumbnails, and by default centers it in the game area with an optional 'close' button.
To load a Showcase Ad make a call to the MochiAds API using the example code below:
import mochi.as3.*;
// This clip must be above all other game assets in the display list and must be positioned at screen coordinate (0,0)
var clip:MovieClip = new MovieClip();
var game_id:String = "REPLACE WITH YOUR GAME ID";
MochiAd.loadShowcase({
clip:clip,
id:game_id,
position:"0x0", // This represents an X, Y offset from the center.
ad_count:5, // The number of ads to display in the showcase. (Choose a lower number for small games)
ad_size:90, // Force dimensions for all Ads displayed.
user_close:true, // Allow the use to close the Showcase ad.
ad_loaded: function(w:int, h:int):void { }, // A callback that occurs when ad is first displayed.
ad_closed: function():void {} // A callback that occurs when user closes Showcase.
});
Additional control methods are available to hide the Showcase and redisplay it at appropriate times (for example: between levels). These methods are :
MochiAd.openAdGroup(clip)
MochiAd.closeAdGroup(clip)
In both cases 'clip' is the MovieClip reference assigned to the 'clip' property when calling loadShowcase().
Dock Ads
The API call will load a Dock into the clip. The Dock will load a number of small, static ads into an "auto-hide" dock on one edge of the game window. The Dock is initially visible and fully extended into the game area. After a short time the Dock will retract out of view, leaving only a small mouse-over tab visible in the game area. If the user rolls the mouse pointer over the tab the Dock will extend back into view for a short time.
To load a Dock ad make the following call to the MochiAds API :
import mochi.as3.*;
// This clip must be above all other game assets in the display list and must be positioned at screen coordinate (0,0)
var clip:MovieClip = new MovieClip();
var game_id:String = "REPLACE WITH YOUR GAME ID";
MochiAd.loadDock({
clip:clip,
id:game_id,
position:"bottom", // See below for explanation.
ad_count:5, // The number of ads to display in the showcase. (Choose a lower number for small games)
ad_size:90, // Force dimensions for all Ads displayed.
ad_loaded: function(w:int, h:int):void { }, // A callback that occurs when ad is first displayed.
ad_opened: function():void {}, // A callback that occurs when the user opens the Dock by mousing over the tab.
ad_closed: function():void {} // A callback that occurs when the Dock auto-hides.
});
The location and orientation of the Dock can be selected to keep the mouse-over tab away from the gameplay area where the mouse is most active. Location and orientation are parsed from a 'position' property on the 'options' object. The available options for the value of 'position' are:
- "top" :
- "bottom" :
- "left" :
- "right" :
- "top_left" :
- "top_right" :
- "bottom_left" :
- "bottom_right" :
- "left_top" :
- "left_bottom" :
- "right_top" :
- "right_bottom" :
- A horizontal dock will be centered on the top edge.
- A horizontal dock will be centered on the bottom edge.
- A vertical dock will be centered on the left edge.
- A vertical dock will be centered on the right edge.
- A horizontal dock will be located at the left end of the top edge.
- A horizontal dock will be located at the right end of the top edge.
- A horizontal dock will be located at the left end of the bottom edge.
- A horizontal dock will be located at the right end of the bottom edge.
- A vertical dock will be located at the top of the left edge.
- A vertical dock will be located at the bottom of the left edge.
- A vertical dock will be located at the top of the right edge.
- A vertical dock will be located at the bottom of the right edge.
The default 'position' is "bottom" if this property is not assigned.
Additional control methods are available :
MochiAd.closeAdGroup(clip); // Hide Dock completly, including mouse-over tab.
MochiAd.openAdGroup(clip); // Redisplay hidden Dock (without opening slider).
MochiAd.openDockSlider(clip); // Cause displayed Dock to slide open.
In all cases 'clip' is the MovieClip reference used when calling loadDock().
Fitting Showcase and Dock Ads Into Small Games
The default configuration of five 90 pixel ads in a row or column may not fit in smaller games. There are two approaches you can take to work around this problem:
You can set an 'ad_size' property on the object you pass into MochiAd:loadDock() or MochiAd:loadShowcase() This will force one dimension of the individual thumbnails (width, in the case of Showcase and horizontal Docks, height, in the case of vertically oriented Docks) the default ad_size is 90 pixels, if not supplied.
You can also change the number of ads displayed in a Dock or Showcase by setting the 'ad_count' property on the object you pass into the load method. The default is 5.
Flash Player Security Settings:
If you are testing locally outside of the Flash authoring environment and want to be able to see ads, you will need to change the default local playback security settings. In Flash, go to "File -> Publish Settings," then click on the "Flash" tab. At the bottom, under "Local Playback Security", choose "Access network only" and then publish again. Keep in mind that if you are loading any local data that it will no longer be accessible until you change your settings back to "Access local files only." These settings will not affect playback on the web.
Alternatively, you may wish to add the location of your development files to your global security settings in the Adobe Flash Player Settings Manager. This way, you can give all SWF files in this location local-trusted access, allowing access to both local and remote data.
You will not need to do this if you are only testing your games in the Flash authoring environment, although you will see Sandbox Violation warnings in the Output panel. Warnings pertaining to MochiAPI can be safely ignored.
Alternate In-game Code Placement
Since there are many different ways to architect Flash games, it is very likely that your game development setup is not the same as what you see above. You may have nested MovieClips, or perhaps you are not using the timeline at all. It is possible to place your in-game code in the timeline of a MovieClip as well, and it will execute when the frame where you placed the code is reached.
And You're Done!
That's all that is required to get MochiAPI Ads running in your game. When you've completed your game and released it to the world, be sure to complete your profile so that your game can be approved and you can start earning money right away!
1.3 Customizing Your Ad
NOTE: The easiest way to customize the ads shown in your game is to use the Ad Code code generator in the developer dashboard. You can find this code generator by going to your Mochi developer dashboard, selecting your game, clicking on "Ads" on the left and then "Mochi Ads Code: Get the ad code and installation instructions" beneath the Default Ad Settings." Inside you will be provided the option to customize the options.
It is possible to customize many of the visual elements and behaviors of your Mochi Ads. The Mochi Ads API in-game code allows you to simply tailor the display to suit your needs. Here's some of the things you can tweak:
- MovieClip container: You can place your ad into any MovieClip on the stage, or into MovieClips you create with Actionscript.
- Timing: You can customize fade time of your ads.
- Colors: Change the colors of the ad preloader bar, background and outline. You can also turn off the solid background.
- Event Handlers: You can assign custom functions to be called when ads start, load, and end.
The Mochi Ads API
Your ads can be customized by sending special parameters via your in-game code. Depending on whether you've chosen to display a pre-game or inter-level ad, your options will be slightly different.
The in-game code is passed an object with keys and values to pass to the server. The default code contains two keys -- id, the unique Mochi game ID, and res, the height x width of your game. These parameters are required.
import mochi.as2.*;
MochiAd.showPreGameAd({id:"xxxxxxxxxxxxxxxx",
res:"360x240"});
You may add more key: value pairs to the object by separating them with commas. You may add the following optional parameters to your object:
- clip:MovieClip - a MovieClip reference in which to place the ad. Required for click-away, showcase and dock ads or if you're using Actionscript 3.0. Otherwise the default is _root. (default: _root)
- no_bg:Boolean - setting to true allows you to disable the background entirely. (default: false)
The following additional options apply to pre-game ads only:
- color:Number - the color of the preloader bar as a number. (default: 0xFF8A00)
- background:Number - the inside color of the preloader bar as a number. (default: 0xFFFFC9)
- outline:Number - the outline color of the preloader bar as a number. (default: 0xD58B3C)
- no_progress_bar:Boolean - setting to true allows you to disable the preload progress bar. (default: false)
You can find out the width and height of your ad when it loads. You can use this information to create a custom frame around your ad that matches your game.
- ad_loaded:Function - ad_loaded is called just before an ad is displayed with the width and height of the ad. (default: function(width:Number, height:Number):Void { }).
You can also find out the progress of the preloader bar. You can use this information to create your own preloader bar when used with the no_progress_bar option.
- ad_progress:Function - ad_progress is called with the progress of the preloader bar. The progress is a percent (represented from 0 to 100). (default: function(percent:Number):Void { }).
Here is an example of how the code might look if you were to add more options:
import mochi.as2.*;
MochiAd.showPreGameAd({id:"xxxxxxxxxxxxxxxx", res:"360x240", clip: _root.myClip, no_bg: true, color: 0x006699, outline: 0xFFFFFF});
If you need to add many options, or define functions to handle ad events, you may consider creating an object first, and then referencing that object when you call the Mochi Ads API.
import mochi.as2.*;
var myOptions:Object = {
id: "xxxxxxxxxxxxxxxx",
res: "360x240",
clip: _root.myClip,
color: 0x006699,
background: 0x333333,
outline: 0xFFFFFF,
ad_loaded: function (width, height) { trace("ad loaded: " + width + "x" + height); }
ad_progress: function (percent) { trace("preloader percent: " + percent); }
}
MochiAd.showPreGameAd({myOptions});
There is also a tool on the Mochi Developer web site to customize the appearance of your ad when you set up your in-game code. Often, this is easier than editing the code by hand.
1.4 Changing Ad Behaviors
The Mochi Ads API described above also allows you to assign your own event handlers to be called by your ad. There are six events:
- ad_started:Function - a function to call when the ad has started playing. (default: function ():Void { this.clip.stop() })
- ad_loaded:Function - a function to call just before an ad is displayed with the width and height of the ad. If it is called, it is called after ad_started. (default: function(width:Number, height:Number):Void { }).
- ad_finished:Function - a function to call when the ad has finished playing. (default: function ():Void { this.clip.play() })
- ad_failed:Function - a function to call if an ad can not be displayed, this is usually due to the user having ad blocking software installed or issues with retrieving the ad over the network. If it is called, then it is called before ad_finished. (default: function ():Void { })
- ad_skipped:Function - a function to call if the ad was skipped, this is usually due to frequency capping, or developer initiated domain filtering. If it is called, then it is called before ad_finished. (default: function ():Void { })
- ad_progress:Function - a function to call when the progress of the preloader bar has changed. The progress is a percent (represented from 0 to 100). (default: function(percent:Number):Void { }).
When you assign custom functions to ad_started and ad_finished in your options object, your ad will no longer stop and play the timeline. Instead, your custom functions will be called.
import mochi.as2.*;
var myOptions:Object = { id: "xxxxxxxxxxxxxxxx", res: "360x240", clip: _root.myClip, ad_started: function ():Void { _global.game.pause(); }, ad_finished: function ():Void { _global.game.resume(); } }
MochiAd.showPreGameAd({myOptions});
It is best to explicitly pass a function literal in your options object instead of referencing a function in a separate class. That way, you do not need to worry about losing scope or relying on the Delegate class. If you are using ActionScript 3, though, you can pass a reference to your function without losing scope.
Keep in mind that, if you define custom ad_started or ad_finished event handlers, your timeline will no longer be stopped during the playback of your ad. So, if you still wish to stop your timeline, you will need to be sure your event handler does this.
1.5 MTASC and MXMLC
For those developers who are developing in environments that don't use the Flash IDE, the process for adding the Mochi Ads API will be slightly different. In order to get your ads functioning in your game, you will need to:
- Make sure that the
mochifolder is in your root project classpath. - You've added the in-game code in a method that is executed in an instantiated class in your game.
1.6 Adobe Flex
To use the Mochi Ads API as an Adobe Flex application's preloader, you will need to:
- Make sure that you use the
MochiPreloader.asfrom the examples/flex folder from the MochiAPI ZIP package. - Make sure that the
mochifolder andMochiPreloader.asare in your project classpath. - Tell your MXML application the preloader you want to use:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" preloader="MochiPreloader"> </mx:Application>
- NOTE: With inter-level ads, the Mochi API is unable to tell your game when it has finished via the
MovieClip.stop()andMovieClip.start()methods. You must use thead_startedandad_finishedcallback methods in your game's options object (described in Section 1.4) to be notified when to start and stop your game.
1.7 ActionScript 3.0 Preloader
The mxmlc folder includes a preloader class (Preloader.as) that provides an example of how to properly compile a preloader into an AS3 SWF compiled with Adobe Flex mxmlc compiler. For the preloader to function correctly, it must load first and execute before your base class and other SWF assets load. In order for this to happen, the Preloader class is included on the first frame of your SWF and all of the other assets are included on the next frame. The Preloader class contains a weak reference to your document class that it uses to instantiate your class after it completely loads your game.
// Change this class name to your main class public static var MAIN_CLASS:String = "Test";
For Flex Builder, there is a makefile included in the example which tells the mxmlc compiler to include your Document Class in the second "frame" of your SWF so that the preloader will load first:
mxmlc \
-default-frame-rate 31 \
-default-size 550 400 \
-use-network \
-optimize=true \
-output $@ \
-frame=Test,Test \
Preloader.as
Notice the compiler option '-frame=Test,Test'.
If you are using FlashDevelop, you need to make sure you're passing "-frame Test, Test" to the mxmlc compiler, which you can set under Compiler Options in Project Properties. Don't forget to change 'Test' to the actual name of your base class.
1.8 Flash Develop
Our example uses the AS3 Empty Project Template as it's basis. Using our API within this framework is no more difficult
than that of a standard Flash IDE project. Simply copy the mochi folder into the src folder created for your
project. After you have done this, it is simply a matter of using that standard API calls
1.9 More Resources
If you have questions about using the Mochi Ads API, you can view our FAQs or visit the support forums for help. Also, if you have suggestions regarding this help document, we encourage your feedback.
Live Updates
1.1 Overview
Our Live Updates service enables you to create a special version of your SWF which can be updated at any time and contains an extra layer of encryption to protect against decompiling.
Benefits of Mochi Live Updates
- Update anything about your game, at any time. The updated version will be instantly available to players around the world.
- The game does not require Mochi servers to be played – Your file is completely stand alone.
- Your game can be played offline as well as online – Offline players simply get the original packaged version
- Increased encryption and protection from decompiling.
- Downloading the new updates are quick and transparent, players only need the differences between versions.
Live Updates works great for
- Fixing those nasty bugs that crop up after your game is released.
- Recently changed your logo? No problem, upload a new version with a new splash screen.
- Made a hot new sequel to your game? Add in a link and screenshot pointing users to the sequel to generate awareness and traffic.
- Sell a timed sponsorship to someone for a fixed period of time. Simply upload the new version with their links and splash screen and revert to the old version when you're done.
How it works
Live Updates games play just like any other game to the user. However behind the scenes when the game is first loaded it checks with Mochi servers to see if there is a new version available. If so, the game will be patched while during the loading process (it only sends minimum differences, so it doesn’t have to download the whole game over again).
1.2 General Installation
Adding a new game
- Click on 'add game' like normal to add a game to the Mochi service.
- Check the box 'Use Live Updates' to enable the feature.
- Add a verification code to your game - this ensures you have access to the source code.
- Upload your game, a pre-loader is automatically added so you don't have to include any ad-code for a pre-loader. Other in-game ad formats are ok.
Updating your game
- Click on your game from your developer dashboard.
- Click on the 'game settings' link
- Under the 'game files' section, click on 'upload new version'.
- Select 'use Live Updates' for the new game version.
- Follow the on-screen instructions and upload your new version.
That's it!
Distribute your new version anywhere you like! If at any time you want to change your game, visit your game settings tab and upload the new version. Within minutes players will be enjoying your new awesomeness.
1.3 Test Your Game For Compatibility
The Live Updates service embeds games into an AS3 loader SWF. The Flash Player treats games differently when loaded this way than when loaded by either through an HTML page or directly into a browser.
To test for compatibility, loading your game using the LoaderTest utility to see if you can reproduce the problem. LoaderTest uses the same underlying Flash features that the Live Updates loader SWF uses. If the problems are still present when using LoaderTest, then you will need to make changes to your game. If the problems are not present, then notify us, and we will investigate the problem.
1.4 Preparing AS3 games
AS3 display list membership
Adobe’s Flash Player treats AS3 SWFs loaded into another AS3 SWF differently than when it’s loaded directly by the browser. In particular,
the main object is not added to the display list until after the constructor is called whereas when loaded directly the main object is already
attached to the display list. This results in the stage and parent properties being set to ‘null’ (and likely resulting in null object references).
This can usually be worked around by moving any code that needs to interact with the stage being moved to an event listener.
Event.ENTER_FRAME, Event.INIT, or Event.ADDED_TO_STAGE events are good candidates for this.
AS3 LoaderInfo, third party APIs
Since Live Updates loads your code with a flash.display.Loader, the FlashVars and URL
should be accessed somewhat differently than normal. Some third party APIs may need small changes to use this LoaderInfo instead of root.loaderInfo. This code will get the true LoaderInfo in a game using Live Updates (but also works if not using Live Updates):
public function getMainLoaderInfo():LoaderInfo {
var loaderInfo:LoaderInfo = root.loaderInfo;
if (loaderInfo.loader != null) {
loaderInfo = loaderInfo.loader.loaderInfo;
}
return loaderInfo;
}
1.5 Preparing AS2 games
AS2 Sound
Some sounds may not play properly in AS2 games within an AS3 loader when the sound is not attached to a movieclip. To get around this, you should ensure your sounds are always attached to a movieclip:
var s = new Sound(mc);
The following is an example of how you can handle sounds in your AS2 games so they are always compatible with AS3 loaders. At the top level of the .as files, the following code initially creates all of the different Sound objects on their own MovieClip:
var core = this;
var make_sound = function (mc_name, depth, volume, name) {
var mc = core.createEmptyMovieClip(mc_name, depth);
var snd = new Sound(mc);
snd.setVolume(volume);
snd.attachSound(name);
return snd;
};
var s_newline = make_sound('so_newline', 200, 30, 'newlineMP3');
var s_skull = make_sound('so_skull', 201, 100, 'skullMP3');
var s_doubleskull = make_sound('so_doubleskull', 202, 100, 'doubleskullMP3');
var s_success = make_sound('so_success', 203, 30, 'successMP3');
var s_timer = make_sound('so_timer', 204, 100, 'timerMP3');
Later, when a sound should be played, there's a line like:
core.s_skull.start(0, 1);
Using _root and _level0
It is not recommended to use _root as references in your game. If you are experiencing problems when testing your
game for compatibility, replace these references and test again.
Using _level0, _leveln or doing a loadMovie into a level is not
supported at all by AVM1Movie, so you must change code that depends on it.
Moving _root makes MovieClip.hitTest behave strangely
If you change _root._x or _root._y you may notice that MovieClip.hitTest no longer behaves
the same way. This is because MovieClip.hitTest is based off of global coordinates when inside the AS3 container but it's based on _root coordinates otherwise. The following code snippet that you can place in your initialization code will detect the container and swap out the MovieClip.hitTest implementation with one that does this translation for you.
/* detect AS3 container and patch MovieClip.hitTest */
if (_level0 === undefined && MovieClip.prototype.oldHitTest === undefined) {
var realRootForReal = this;
MovieClip.prototype.oldHitTest = MovieClip.prototype.hitTest;
MovieClip.prototype.hitTest = function (x, y, shapeflag) {
if (arguments.length === 1) return this.oldHitTest(x);
var obj = {x: x, y: y};
realRootForReal.localToGlobal(obj);
return this.oldHitTest(obj.x, obj.y, shapeflag);
}
}
Using FlashVars
In order for AS2 to properly pick up FlashVars, you will need to use the URL to the SWF instead. Here's an example of how you can pass variables from the HTML to your Flash:
<embed src="game.swf?variable=awesome"></embed>
Strings no longer work as MovieClip references
In some older versions of Flash it would let you use strings where MovieClip references were expected. When this content is loaded into an AS3 container Flash no longer allows this and you must change to references instead. For example:
// BROKEN: "mc2" is a String, not a MovieClip
mc.setMask("mc2");
// FIXED: mc2 is a variable that references a MovieClip
mc.setMask(mc2);
AS2 games encrypted with SWF Protect
Using SWF Protect mangles the AS2 byte code, making it impossible to find the verification token. A workaround is to instead place the verification token as an export identifier. Here are instructions on how to do this:
- Open the Library window in Flash.
- Right click on any asset that is not already exported (but preferably one that is used anyways).
- Select “Linkage…”
- Check “Export for ActionScript"
- In text box labeled “Identifier”, enter “XXXXXXXX”
- Click “OK”.
NOTE: Where 'XXXXXXXX' should be replaced with your game's Mochi game ID
1.6 Preparing AS1 games
Case-sensitivity: Users have reported that AS1 games loaded into AVM1Movie are suddenly case sensitive, whereas normally they are case-insensitive.
1.7 Third Party APIs written in AS2
Usually these APIs work by cross-scripting a SWF to inject new code into AS2 games. However, Flash does not support cross-scripting between AS2 and AS3, and the Live Updates loader SWF uses AS3, preventing the API from being injected correctly.
NOTE: LocalConnection APIs will still work, but sites may not provide these for AS2.
1.8 Flash 10 games using TLF Text (Text Layout Framework)
TLF Text causes your SWF file to be wrapped in an additional preloader, which is not compatible with Live Updates. The workaround is to follow "Solution 1" in this Tech Note: http://kb2.adobe.com/cps/838/cpsid_83812.html
Go to "File" -> "ActionScript Settings" and then change "Default linkage" to "Merged into code". This will allow SWFs with TLF text to be used with Live Updates.
1.9 Flash Player targeting options
You can select the version of Flash Player that you would like to target, starting from Flash Player 10 and continuing through to the latest version. There is a drop-down menu in the Live Updates settings page, which is accessible both when uploading a new game (and selecting Live Updates) and the Live Updates settings for an existing game. Simply select the Flash Player version you would like to target from this menu.
Scores API Documentation
1.1 Overview
MochiServices is all Mochi APIs except for the Mochi Ads API. The API is dynamically loaded from Mochi servers and must be initialized in either the first frame of your game or during Document Class initialization.
NOTE: The easiest way to start implementing Leaderboards is to do so through the developer dashboard. First go to the Mochi developer dashboard, select your game, click on Scores and then click on Create Leaderboard. After you fill in the appropriate information, you will see a list of all your leaderboards. Click "Actionscript Code" to find step by step instructions on how to use the leaderboards!
1.2 Prerequisites
MochiAPI is not compatible with versions prior to Flash Player 9, and is no longer compatible with ActionScript 1.0.
Installing the Mochi Scores API
- Download and unzip the latest MochiAPI.
- Copy the “mochi” folder and paste it into the root classpath of your game. Most often this is the same as the location of your game’s FLA file.
NOTE: In the 3.0 revision of the API, we changed namespaces for
our libraries to unify and organize our packages. Now you must explicitly call the
MochiAPI that is specific version: mochi.as2.* or
mochi.as3.* respectively. For the purposes of this
documentation we will show examples specifying the ActionScript 2.0 API. Simply change
mochi.as2. from the code samples, and add import mochi.as3.*;
to the beginning of your code block to use the ActionScript 3.0 API.
1.3 Connecting to MochiServices
connect
Description:
Retrieves and initializes the MochiServices.swf from Mochi Ads servers. Any API calls executed prior to the complete download and initialization of the MochiServices.swf are queued and will be executed once the API is available
Parameters:
- id:String
- Mochi game ID
- clip:Object
- the MovieClip or Sprite in which to load the API (optional for all but AS3, defaults to _root). In as3 the clip must be dynamic.
- onError:Function
-
This method will be invoked if MochiServices cannot connect to the server or any IO errors occur in any other API calls.
onError handlers will receive status codes that describe the error. The possible errors are:
- NotConnected — Services were unable to connect or attach to a clip in the current movie.
- IOError — Services has connected but cannot transfer data to and from the server.
AS2 Example:
mochi.as2.MochiServices.connect("xxx", root, onConnectError);
public function onConnectError(status:String):Void {
// handle error here...
}
… where ‘xxx’ is your Mochi game ID, in quotes. Test your movie, and you should see the following text in your output panel:
MochiServices Connecting…
Waiting for Mochi services to connect…
connected!
If you see the text above, then that means you have the "mochi" folder in the correct location, and have supplied MochiServices the correct Mochi game ID. Keep in mind that you want to connect to MochiServices as early as possible in your game, and before you make any other API calls. You only need to make this call once in the beginning of your game.
AS3 Requirement - The clip parameter
In ActionScript 3, the root of the Stage cannot be accessed globally. If a Sprite or MovieClip does not have access to the root or to another Display Container that has been added to the display list, then it can not be shown visually on the screen. For this reason, you must supply either the root of your stage or a reference to a Sprite or MovieClip that is a child of the stage to the clip parameter when you call MochiServices.connect. Please note the clip passed must also be dynamic.
Leaderboards
2.1 Overview
Mochi Scores gives developers a simple drop-in solution to in-game scores. Developers can create any number of leaderboards they want for their game to track player scores. Scores are ranked and tracked in daily, weekly and monthly intervals. Each game that you add to Mochi can have many leaderboards, but you must have at least one in order to use the Mochi Scores API.
Benefits of Mochi Scores:
- Use one line of code to show our complete in-game leaderboard.
- Create as many leaderboards as you want for each game.
- Track any kind of score – track by time or numbers and configure the sort order.
- Automatically remembers users name, and last score, and displays the users' country.
- Management tools let you delete player scores or ban them altogether.
- Encrypted communication from your game to Mochi Scores servers.
- Mochi Publisher integration.
2.2 Prerequisites
MochiAPI is not compatible with versions prior to Flash Player 9, and is no longer compatible with ActionScript 1.0.
Before you get started, make sure you have done the following:
- Sign up for a Mochi Developer account on www.mochimedia.com
- Log in and add a new game to your account.
- Create a leaderboard for your game.
- Download the latest version of MochiAPI and copy the include folder to your .fla directory.
- Call
connect()to initialize the Mochi Scores API.
2.3 Displaying the Leaderboard
If you merely want to display the top scores for your game, then simply add the following script to your game:
// stop the main timeline and display the leaderboard
mochi.as2.MochiScores.showLeaderboard({boardID: ”xxx”});
… where ‘xxx’ is your board ID, in quotes. If you’ve already connected to MochiServices and set your board ID, then the leaderboard widget will call stop(); to stop the timeline and then display itself. Players cannot submit a high score this way — they can only see the scores. This is handy if you want to allow players to see the high scores before they play the game.
By default, the showLeaderboard method will call stop(); on the main timeline of your game, and then play(); on the timeline once the leaderboard has been closed by the user. This only occurs if you do not provide a container MovieClip for the leaderboard or your clip is the root of your movie. If you wish to override this behavior, read about providing your own custom onDisplay and onClose handlers Section 2.8: Other Leaderboard Options.
You will also notice that there is a preloader graphic that appears before the leaderboard displays. This graphic will appear in the top left-hand corner of your game unless you provide a resolution in the leaderboard options. If you provide a resolution, then the preloader graphic will appear centered in the area where the leaderboard will display. You can also turn off the preloader graphic entirely by setting a variable in the leaderboard options. Further information on options is detailed below.
In order to allow a player to submit a score after they’ve played your game, then you would call the same method, but also supply an object containing their score, like so:
// stop the main timeline and submit a score to the leaderboard
mochi.as2.MochiScores.showLeaderboard({boardID: ”xxx”, score: 128472});
… where 128472 is the player’s actual score. If you are tracking scores as times, like in a racing game, send the player score in milliseconds. For instance, if the player completed the game in 12.5 seconds, send the integer 12500.
When the leaderboard widget appears, there will be an input box where they can type in their username. After they enter their name, they can then submit their score.
If you have your own registration system within your game, or wish to prevent the player from entering any name they wish, you can supply the username in code, like so:
// stop the main timeline and submit a score and username to the leaderboard
mochi.as2.MochiScores.showLeaderboard({boardID: ”xxx”, score: 128472, name: “janedoe”});
… where ‘janedoe’ is the username, in quotes. This will show the leaderboard widget with the player name already entered, and not editable.
That’s all you need to know to get started! If you’d like to do more advanced customization, read on.
2.4 Saving Your Board ID
If you do not wish to pass the board ID to the showLeaderboard call every time, you can save your board ID by adding the following code to your game:
// set the board ID for all subsequent leaderboard calls
mochi.as2.MochiScores.setBoardID(”xxx”);
… where ‘xxx’ is your board ID, in quotes. This API method sets the board ID for future API calls, so you no longer need to pass the boardID parameter in your API calls. You can always change this by calling this method with a different board ID.
2.5 Other Leaderboard Options
The {} in the showScores API call is an ActionScript object that is referred to as the options object. These options change the way the leaderboard widget behaves. You can enter as many supported optional parameters into this object as you wish. Below is a list of all possible options.
Basic Options:
score — the player's score to submit (integer, or time in milliseconds)
name — the player's name
boardID — board ID (overrides setBoardID)
Callback Options:
onDisplay - the function to call when the GUI has displayed. default: function () { clip.stop(); }
onClose - the function to call when the GUI is finished or could not load. default: function () { clip.play(); }
onError - the function to call if the leaderboard cannot load. default: onClose();
Display Options:
res — the dimensions of the background behind your leaderboard. (i.e. "500x400")
width — exact width for the leaderboard (optional). The height must also be set.
height — exact height for the leaderboard (optional). The width must also be set.
preloaderDisplay — show a preloader graphic while the leaderboard loads. The default is true.
numScores — maximum number of scores to display. You can specify any number from 1 to 25, and the default is 10. Changing this alters the height of the leaderboard.
hideDoneButton — set to true if you wish to hide the 'done' button and instead close the leaderboard in code by calling closeLeaderboard.
showTableRank — set to true if you wish to show the player's rank at the bottom of the table.
previewScores — set to true if you wish to display the top scores before the user submits their name and score. scoreMessage — allows the developer to change the messages used for the leaderboard. This should be passed as an object in this format: { highscore: "Beat my highscore of ${highscore} in ${game}!", latestscore: "I just scored ${score} in ${game}!", gameinvite: "Come play ${game}!" }
Replacement tokens used for customizing social link sharing
${game} — Name of the game containing the leaderboard
${board} — Name of the leaderboard
${score} — Score user just submitted
${highscore} — Highest score user has submitted
Controlling Leaderboard Size:
When you use the "res" option, your leaderboard will display centered in a background rectangle that matches those dimensions. If you would like to specify the exact pixel dimensions of your leaderboard, you can supply two separate parameters, width and height. If you use width and height but omit res, the background will disappear, and the leaderboard will move to 0,0 in _root or in the (optional) clip you specified in MochiServices.connect(). See the diagram below to see how the options work together:
2.6 API Reference
This is the complete list of Mochi Scores API calls. Most developers will only need to use connect, setBoardID, and showLeaderboard. The other calls offer additional functionality to allow advanced developers to create their own custom leaderboards using the MochiServices back-end.
- mochi.as2.MochiScores.setBoardID(boardID:String):Void
- Sets the name of the mode to use for categorizing submitted and displayed scores.
@param boardID — The unique string name of the mode - mochi.as2.MochiScores.showLeaderboard(options:Object):Void
- Displays the leaderboard GUI showing the current top scores.
@param options — optional parameters <see: Leaderboard Options> - mochi.as2.MochiScores.closeLeaderboard():Void
- Closes the leaderboard GUI (Same as if the player clicked 'Done' on the leaderboard)
- mochi.as2.MochiScores.submit (score:Number, username:String, callbackObj:Object, callbackMethod:Object):Void
- Submits a score to the server. Will send a scores object to the callback <see: Scores data format>
@param name — the string name of the user.
@param score — the number representing a score. If the score is time, send it in milliseconds.
@param callbackObj — the object or class instance containing the callback method
@param callbackMethod — the string name of the method to call when the score has been sent - mochi.as2.MochiScores.requestList (callbackObj:Object, callbackMethod:Object):Void
- Returns an array of at most 50 score objects. Will send a scores object to the callback <see: Scores data format>
@param callbackObj — the object or class instance containing the callback method
@param callbackMethod — the string name of the method to call when the score has been sent. default: "onLoad" - mochi.as2.MochiScores.scoresArrayToObjects (scores:Object):Void
- Converts the array of arrays returned by requestList into an array of objects whose keys are derived from cols.
@param scores — the scores object returned to the requestList callback method - mochi.as2.MochiScores.getPlayerInfo (callbackObj:Object, callbackMethod:Object):Void
- Retrieves all persistent player data that has been saved in a SharedObject.
2.7 Error Handling
All web services such as this require an internet connection in order to function properly. Since it is possible that a player's internet connection becomes unavailable during gameplay, it's possible that these services may not become available. In order to handle this possibility, there are additional error handlers you can pass to the services.
The mochi.as2.MochiServices.connect method also includes the ability to pass an onError method. You can also pass an optional onError handler showLeaderboard in the options object. This will be invoked if the leaderboard
cannot load for some reason. By default, the onClose method is called if an error occurs.
Other methods, such as requestList and submit, do not have onError handlers. However, you can check the results that are returned to see if an error occurred. Upon error, the result object will return a variable named 'error' whose value will be true. Also, a variable named 'errorCode' will return one of the above status codes.
2.8 Custom Leaderboards and Scores Data
If you would like to create your own custom Leaderboard, you can use the Mochi Scores API to submit scores and retrieve up to 50 scores from your leaderboard. To retrieve scores data, you must first set your board ID using the setBoardID method, and then call requestList, providing a callback method to receive the scores data object.
mochi.as2.MochiScores.setBoardID("xxxxxxxxxxxxxxxx"); // set the board ID to the leaderboard you wish to work with
mochi.as2.MochiScores.requestList(this, "onScoresReceived"); // request the scores and send them to the onScoresReceived method in this object or class
Your callback method should accept a single parameter of type Object. This object will contain the scores object. If there is an error, the object will contain a variable named error whose value is true, as well as a variable named errorCode which explains the error.
//
//
public function onScoresReceived (args:Object):Void {
if (args.scores != null) {
trace("Scores received!");
var newScores:Object = mochi.as2.MochiScores.scoresArrayToObjects(args.scores);
} else {
if (args.error) {
trace("Error: " + args.errorCode);
}
}
}
If you are using the submit and requestList API calls to create your own custom Leaderboard, you will receive your scores data in the following format:
{ 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], …]}
}
This is an ActionScript object that contains four variables:
now — the current server timestamp in milliseconds since the epoch
places — the percentile that the player's score achieved in each table
counts — the number of scores in each table
daily — scores for the daily table
weekly — scores for the weekly table
monthly — scores for the monthly table
The daily, weekly and monthly variables are objects that contain the following variables:
cols — an array containing the column keys
rows — an array of row arrays. each row array contains the values that correspond to each column key
You may also convert your scores from rows and columns to a list of objects by sending the scores data to MochiScores.scoresArrayToObjects. This will return a new object where each row is an object with key-value pairs. Shown below is an example of how the daily scores would be converted:
daily { [{name: "george", geo: "us", score: 3333, timestamp, 11974208328414.14}, {name: "george", geo: "us", score: 3333, timestamp, 11974208328414.14}, …] }
2.9 Closing the Leaderboard
When you click on Close for a leaderboard, it will automatically call Play() and start playing your SWF file. This sometimes causes your game to reset since it was on the last frame of your game. If you don't want this to occur, add the following parameter into the showLeaderBoard code:
MochiScores.showLeaderboard({boardID: boardID, score: playerscore, onClose: function() {} });
The onClose: function() {} piece is very important. It tells the leaderboard that
when it closes to run that function. In this specific example, the function listed does nothing.
Because it does nothing, closing the leaderboard will not call Play() and your game will stay on
the frame where the leaderboard was called. This is also useful if you want your game to call
another function when it closes.
MochiEvents Achievements API
3.1 Overview
The achievements API allows developers to track and score users progress though gameplay by using badges with various values. These achievements are tracked by IDs, and are stored locally as well as globally using a handful of simple calls and events.
3.2 Prerequisites
Installing the Mochi Scores API
- Download and unzip the latest MochiAPI.
- Copy the “mochi” folder and paste it into the root classpath of your game. Most often this is the same as the location of your game’s FLA file.
3.3 Usage
The achievements system really only requires one call to use, and that is unlock achievements. The majority of the system is tailored around asynchronous events which should be tracks when you start your game. For ease of use, you may use MochiSocial.showProfile to display a user's achievements (under the medals tab), even when the user is in their logged out state. If the user is not logged in, they will not be asked to join Mochi Games. Below is a basic example of how to use the achievements API.
import mochi.as2.MochiEvents;
var _gameAchievements:Object;
// These should be added before, or shortly after MochiServices.connect
MochiEvents.addEventListener( MochiEvents.GAME_ACHIEVEMENTS, this, onGameAchievements );
MochiEvents.addEventListener( MochiEvents.ACHIEVEMENTS_OWNED, this, onUserAchievements );
MochiEvents.addEventListener( MochiEvents.ACHIEVEMENT_NEW, this, onNewAchievement );
MochiServices.connect( 'xxx' );
function onGameAchievements( ach:Array ):Void
{
for( var i = 0; i < ach.length; i++ )
{
_gameAchievements[ ach[i].id ] = ach[i];
_gameAchievements[ ach[i].id ].unlocked = false;
}
}
function onUserAchievements( ach:Array ):Void
{
for( var i = 0; i < ach.length; i++ )
{
_gameAchievements[ ach[i].id ] = ach[i];
_gameAchievements[ ach[i].id ].unlocked = true;
}
}
function onNewAchievement( ach:Object ):Void
{
_gameAchievements[ ach.id ] = ach;
_gameAchievements[ ach.id ].unlocked = true;
}
MochiEvents.unlockAchievement( { id: 'xxx' } );
Obviously, you can create a much more robust example. Please note that these events will be dispatched any time the user login state changes, so it would be to your best interest to handle these events globally.
3.4 API Reference
Description:
Set the display style for the achievements 'toaster'. These are the notifications that will be displayed when an achievement is awarded.
Parameters:
- parameters:Object
-
This is a property bundle which controls
- format:String — The display style used for achievements
- FORMAT_NONE — Hide all achievement toasters
- FORMAT_SHORT — Small form achievement, only displays icon and name
- FORMAT_LONG — Long form, displays icon, description and name
- align:String — Relative on screen position for the achievement.
- ALIGN_TOP_LEFT
- ALIGN_TOP
- ALIGN_TOP_RIGHT
- ALIGN_LEFT
- ALIGN_CENTER
- ALIGN_RIGHT
- ALIGN_BOTTOM_LEFT
- ALIGN_BOTTOM
- ALIGN_BOTTOM_RIGHT
- format:String — The display style used for achievements
Example:
import mochi.as2.MochiEvents;
MochiEvents.setNotifications( {
format: MochiEvents.FORMAT_SHORT,
align: MochiEvents.ALIGN_BOTTOM_RIGHT
} );
Description:
Award user a registered game achievement (based on id
Parameters:
- parameters:Object
-
This is a property bundle which controls
- id:String — Achievement ID, supplied on the developer dash board
Example:
import mochi.as2.MochiEvents;
MochiEvents.unlockAchievement( { id: 'xxx' } );
Description:
Display a modal dialog containing the current user's medals and achievements.
Parameters:
- parameters:Object
- Unused, added for future upgrades.
Example:
import mochi.as2.MochiEvents;
MochiEvents.showAwards();
Description:
Request the game's achievements (Normally sent automatically
Parameters:
- parameters:Object
- Unused, for future expansion.
Example:
import mochi.as2.MochiEvents;
MochiEvents.addEventListener( MochiEvents.GAME_ACHIEVEMENTS, this, processGameAchievements );
MochiEvents.getAchievements();
3.5 Event definitions
Events as well as any arguments your event handler will receive are listed below
- MochiEvents.GAME_ACHIEVEMENTS [ { "name": "Bouncy", "id": "xxx", "score": 100, "imgURL": "http://...", "type": "leaderboards", "hidden": false, "description": "Score 20 or higher to get a Bronze Medal!" }, { "name": "Dead-Eye", "id": "xxx", "score": 120, "imgURL": "http://...", "type": "ingame", "hidden": false, "description": "Shoot 10 monsters with only a single shot." }]
- List of all the achievements available in the game, and information about their unlocked state
- MochiEvents.ACHIEVEMENTS_OWNED [ { "name": "Bronze Medal", "timestamp": 1300214011842, "description": "Pretty Good! Bronze Medal Score! Score 1,000 or higher to get a Silver Medal!", "score": 25, "imgURL": "http://...", "hidden": false, "id": "xxx" }, { "name": "Dead-Eye", "timestamp": 1299707446000, "description": "Shoot 10 monsters with only a single shot.", "score": 120, "imgURL": "http://...", "hidden": false, "id": "xxx" }]
- A List of all the user's currently unlocked achievements
- MochiEvents.ACHIEVEMENT_NEW { "name": "Dead-Eye", "timestamp": 1299707446000, "description": "Shoot 10 monsters with only a single shot.", "score": 120, "imgURL": "http://...", "hidden": false, "id": "xxx" }
- Event dispatched when a user is awarded a new achievement
- MochiEvents.ERROR { type: MochiCoins.IO_ERROR }
- An error occurred. Values for type are listed below:
- MochiCoins.IO_ERROR: There was a network error.
- MochiCoins.IO_PENDING: The game has not finished starting up (achievement list has not been received).
MochiDigits
4.1 Overview
MochiDigits provides a quick, and easy way for developers to encode their sensitive numbers in memory. While there is no foolproof solution to the problem of hacking, this at least provides another layer of security for developers hoping to keep their scores from being modified with memory editing tools.
4.2 Prerequisites
Installing the Mochi Scores API
- Download and unzip the latest MochiAPI.
- Copy the “mochi” folder and paste it into the root classpath of your game. Most often this is the same as the location of your game’s FLA file.
4.3 Usage
Getting started using MochiDigits is simple. MochiDigits operates like any other object, and can be modified using a set of easy to use functions or simply by directly altering a single property.
import mochi.as2.MochiDigits;
var score:MochiDigits;
score = new MochiDigits(0);
This creates a score object with the value "0". Now you can alter the score simply by calling two easy to use functions
- public function setValue(digit:Number):void
- Sets the value of a MochiDigits object to a specified number
@param digit — The value to apply to the object - public function addValue(inc:Number):void
- Increments the value of a MochiDigits object by a specified number
@param digit — The value to increment the object by - public function get value():Number
public function set value(v:Number):void - Property allowing direct access to the unencoded score
To use a real-world example, if you wished to say, give the player 100 points for grabbing an acorn, you would simply call addValue
score.addValue(100);
It is just that easy. Now, lets say the player has started a new level. While you could create a new score object, it may be cleaner to simply set the value to zero.
score.setValue(0);
Finally, you might be wondering how you can retrieve your score? Simply using the .value property
mochi.as2.MochiScores.showLeaderboard({boardID: ”xxx”, score: score.value});
You can use this property to do advanced tricks, like applying multipliers, or whatever else you can think of. Just remember that so long as you are working on an unencrypted score, your data is vulnerable to attack.
Link Tracking API Documentation
1.1 Overview
Mochi Link Tracking allows game developers can track all the traffic coming from their games. By using the Mochi Link Tracking method call you can get important stats for any link in your game. You can track as many in-game links as you want, and you can dynamically change the URL players are sent even after your game is spread across the internet.
Benefits of Link Tracking:
- Track as many links in your game as you want.
- Dynamically change the URL the link points to at any time.
- Includes enhanced pop-up blocking protection so your link works in as many situations as possible.
- Get valuable reporting telling you how much traffic your getting from each link.
Link Tracking works great for:
- Find out which link placements draw the most visitors.
- Learn about which hosts work best for driving traffic.
- Help determine the value of your game for sponsors with real traffic numbers.
- Sell timed sponsorship by dynamically changing the links to different sponsors on the fly.
1.2 Prerequisites
MochiAPI is not compatible with versions prior to Flash Player 9, and is no longer compatible with ActionScript 1.0.
Installing the Mochi Ads API
- Download and unzip the latest MochiAPI.
- Copy the “mochi” folder and paste it into the root classpath of your game. Most often this is the same as the location of your game’s FLA file.
NOTE: In the 3.0 revision of the API, we changed namespaces for
our libraries to unify and organize our packages. Now you must explicitly call the
MochiAPI that is specific version: mochi.as2.* or
mochi.as3.* respectively. For the purposes of this
documentation we will show examples specifying the ActionScript 2.0 API. Simply change
mochi.as2. from the code samples, and add import mochi.as3.*;
to the beginning of your code block to use the ActionScript 3.0 API.
1.3 Link Tracking API
addLinkEvent()
function addLinkEvent(url:String, backupUrl:String, container:DisplayObjectContainer, [callback:Function]):Void
Description
Adds click event listening to a DisplayObjectContainer that directs the user to an external website.
Parameters
- url:String
- Redirect URL provided to you by Mochi when you create a new link.
- backupUrl:String
- URL to fall back on if Mochi servers do not respond.
- container:DisplayObjectContainer
- Reference to a valid DisplayObjectContainer (or MovieClip in AS2) to attach the click event to.
- callback:Function
- Function to call when the click event occurs. No parameters are passed.
AS3 Example:
var container:Sprite = new Sprite(); //If your using SimpleButton, you'll need a display container container.addChild(mySimpleButton); //reference to your button mochi.as2.MochiServices.addLinkEvent( 'http://link.mochiads.com/link/XXXXXXXXXXX', //Mochi provided URL 'http://mygamesite.com', //Backup URL in case Mochi servers are unavailable container, //Sprite/Movie Clip to connect the click event to onMenuClick //Callback function ); //... public function onMenuClick():Void { // insert and callback code here }
addLinkEvent needs a reference to any DisplayObjectContainer. For example if you use a Sprite
with buttonMode = true you can pass a reference to the Sprite itself. If you use a TextField of SimpleButton you'll
need to add it to a containing Sprite.
Universal Data Storage (AS3-only persistence)
1.1 Overview
Mochi UserData allows game developers to persist data for games. With this API you can store multiple keys and users. The data is persisted in AMF3 format with compression, so you can efficiently store and transmit anything that could be persisted by SharedObject.
1.2 Prerequisites
MochiAPI is not compatible with versions prior to Flash Player 9, and is no longer compatible with ActionScript 1.0.
Installing the Mochi Ads API
- Download and unzip the latest MochiAPI.
- Copy the “mochi” folder and paste it into the root classpath of your game. Most often this is the same as the location of your game’s FLA file.
1.3 Universal Data Storage (AS3-only persistence)
getData()
Description:
Get the data stored at key for the userid, will call callback(userData) with the result. If there is no value stored at key, userData.data will be null.
Parameters:
- userid:String
- The user identity for your game
- key:String
- The name of the key to retrieve for this user
- callback(userData:MochiUserData):void:Function
- The function to be called on success or error. On success, userData.isError is false and userData.data is set to the value of this key for the logged-in user. If the key has not been previously set, userData.data will be null. If an error has occurred, userData.isError will be true and userData.errorCode is the description of the error.
Example:
private function loginEvent(event:Object):void {
MochiUserData.getData("user_12345", "login_count", gotLoginCount);
}
private function gotLoginCount(userData:MochiUserData):void {
if (userData.isError) {
trace("[ERROR] could not fetch login_count: " + userData.errorCode);
return;
}
var login_count:Number = 0;
if (userData.data !== null) {
login_count = login_count.data;
}
trace("This user has logged in " + login_count + " times");
MochiUserData.putData("user_12345", "login_count", login_count + 1, putLoginCount);
}
private function putLoginCount(userData:MochiUserData):void {
if (userData.isError) {
trace("[ERROR] could not put login_count: " + userData.errorCode);
return;
}
trace("Successfully updated login_count for user");
}
putData()
Description:
Store value at key for the userid, will call callback(userData) to report success or error. If the put succeeded, userData.isError will be false.
Parameters:
- userid:String
- The user identity for your game. Max digits: 36
- key:String
- The name of the key to retrieve for this user. Max digits: 20
- value:*
- The value to store at key for this user. Can be anything serializable by AMF3 (in other words, anything that you could put in a SharedObject).
- callback(userData:MochiUserData):void:Function
- The function to be called on success or error. On success, userData.isError is false. If an error has occurred, userData.isError will be true and userData.errorCode is the description of the error.
Example:
private function loginEvent(event:Object):void {
MochiUserData.getData("user_12345", "login_count", gotLoginCount);
}
private function gotLoginCount(userData:MochiUserData):void {
if (userData.isError) {
trace("[ERROR] could not fetch login_count: " + userData.errorCode);
return;
}
var login_count:Number = 0;
if (userData.data !== null) {
login_count = login_count.data;
}
trace("This user has logged in " + login_count + " times");
MochiUserData.putData("user_12345", "login_count", login_count + 1, putLoginCount);
}
private function putLoginCount(userData:MochiUserData):void {
if (userData.isError) {
trace("[ERROR] could not put login_count: " + userData.errorCode);
return;
}
trace("Successfully updated login_count for user");
}