Mochi Support Center

Developer Support

Coins API Documentation

1.1 Overview

The Mochi Coins API provides an easy way to sell game upgrades like level unlocks, equipment, special weapons and cheats to players. It also provides secure login and server side persistence of player data to store game state and user data no matter where the game is played.

1.2 Prerequisites

MochiAPI is not compatible with versions prior to Flash Player 7, and is no longer compatible with ActionScript 1.0.

Installing the Coins API

  1. Download and unzip the latest MochiAPI.
  2. 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. Create your store and add items in your Mochi Developer account.

1.3 Connecting to MochiServices

connect

connect(id:String, clip:Object, onError:Function):void

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.

1.4 Showing the Login Widget.

The Login Widget allows the player to register or login and gives them access to their items and coins. If the player has previously logged in, the widget will show their profile picture, items, and coins. The Login Widget is 200x25 in size, and will automatically place itself on the lower right corner of your stage. We recommend this placement for consistency between all Coins enabled games, however you may pass in a custom position for your specific design.

import mochi.as3.*;

MochiCoins.showLoginWidget(); // You can also pass a x,y - MochiCoins.showLoginWidget({x:330, y:360})

You can hide the Login Widget with the code below. The widget will still be loaded to keep state but won't be visible.

MochiCoins.hideLoginWidget();

1.5 Listening to Events.

Once a player has logged in, you will get a LOGGED_IN event followed by ITEM_OWNED events for each item the player owns. If the player previously logged in and has a valid session, this may happen quickly after the MochiServices.connect() call, so listeners should be enabled for these events before your MochiServices.connect() call. When players purchase an item, the ITEM_NEW event will happen, allowing you to register the item for your game.

import mochi.as3.*; // import mochi.as2.* if using the AS2 API

    MochiCoins.addEventListener(MochiCoins.ERROR, handleError);
    MochiCoins.addEventListener(MochiCoins.LOGGED_IN, loggedIn);
    MochiCoins.addEventListener(MochiCoins.ITEM_OWNED, registerItem);
    MochiCoins.addEventListener(MochiCoins.ITEM_NEW, newItem);

    MochiServices.connect("xxx", root, onError);

    public function loggedIn(event:Object):void {
        // receive {name: name, uid: uid, profileImgURL: profileImgURL, hasCoins: True, userProperties: { hitPoints: 120 }}
        trace("Hello " + event.name);
    }

    public function registerItem(event:Object):void {
        // receive {id: id, count: count}
        trace("Player owns " + event.count + " of " + event.id);
    }

    public function newItem(event:Object):void {
        // receive {id: id, count: count}
        trace("Player just bought " + event.count + " of " + event.id);
    }
    

It should be noted that the parameter dispatched with an event is an Object, and not a decedent of the Event class. While Objects behave in a similar fashion as an Event object, they do not contain the same parameters and properties as a built-in AS3 Event. Likewise, you will not be able to use instanceof, is, as and typeof to determine what kind of event has been passed.

1.6 Showing the store.

Use MochiCoins.showStore() to show your store with two or more items. You may pass an optional tags array to show a subset of the items in your store that match the tags defined in your items in your Mochi Developer account. The tags array can also have specific itemIds specified as each item is already implicitly tagged with its itemId. The example below shows all items with the "weapons" tag as well as a specific itemId. No x,y coordinates are passed as the store should fill the stage.

MochiCoins.showStore({ tags: ["weapons", "c27d0672bf98ec05"] });

1.7 Showing a single item.

Use MochiCoins.showItem() to show a modal dialog offering a single item. Pass the item identifier listed for your item in your Mochi Developer account. The dialog will center itself on the stage but you may also pass x,y coordinates.

MochiCoins.showItem({item: "xxx"}); // You can also pass a x,y - MochiCoins.showItem({x:330, y:360, item: "xxx"})

1.8 Showing an item demonstration video.

Use MochiCoins.showVideo() to show a modal dialog displaying the demonstration video associated with an item. The call will be ignored if the item ID is invalid, or there is no video associated with the specified item.

MochiCoins.showVideo({item: "xxx"});

1.9 Saving persistent player properties.

The MochiCoins API will allow you to save persistent player properties. This can be used to save any custom player state that can be retrieved on subsequent gameplays. As an example, you may wish to save the state of health, experience, or the number of levels unlocked for the player which can provide a more continuous game play experience when the user returns to the game at a later time. The example below will save the key value pairs specified for the logged in player. Only values of types Number, String, Boolean, and Array can be saved. There is currently a 4KB limit (total serialized size) per user per game that can be saved.

MochiCoins.saveUserProperties({ hitPoints: 120, levelsFinished: [1, 2, 4, 6] });

The above call will overwrite the previous properties Object that may have existed for the player. On subsequent MochiCoins.LOGGED_IN events, this object will be passed back.
                        MochiCoins.addEventListener(MochiCoins.LOGGED_IN, loggedIn);

                        public function loggedIn(ev:Object):void {
                            // receive {name: name, uid: uid, profileImgURL: profileImgURL, hasCoins: True, userProperties: { hitPoints: 120 .. }}
                            var userProperties:Object = ev.userProperties
                        }
                                                

MochiCoins.PROPERTIES_SAVED event will occur when the properties Object save is successful. MochiCoins.ERROR of type MochiCoins.PROPERTIES_SIZE or of type MochiCoins.NO_USER will occur when the size of the properties Object is too large, or no user is logged in. See 2.0 Event definitions.

                        MochiCoins.addEventListener(MochiCoins.PROPERTIES_SAVED, properties_saved);
                        MochiCoins.addEventListener(MochiCoins.ERROR, handleError);

                        public function properties_saved(ev:Object):void {
                            trace("Properties Saved!");
                        }
                        public function handleError(ev:Object):void {
                            switch (ev.type) {
                                case MochiCoins.PROPERTIES_SIZE:
                                    trace("Properties too large.");
                                    break;
                                case MochiCoins.NO_USER:
                                    trace("No user logged in.");
                                    break;
                            }
                        }
                                                

1.10 API

showStore

showStore(options:Object):void

Description:

Shows the game store.

Parameters:

tags:Array (optional)
Array of string group names for filtering

Example:

    MochiCoins.showStore({ tags: ["weapons"] });
    

showItem

showItem(options:Object):void

Description:

Shows a single item for purchase. The UI will center itself on the stage be default if no custom coordinates are passed.

Parameters:

x:Number
x coordinate
y:Number
y coordinate
item:String
item id
bought:Boolean (optional)
set to true if you wish to show the single item dialog and force the ui to show the item as being bought by the user. This can be useful if you sell an item that represents a bundle of other items in your game and wish to prevent players who have already bought that bundle from purchasing this single item.

Example:

    MochiCoins.showItem({ x:150, y: 150, item: "xxx" });
    

showVideo

showVideo(options:Object):void

Description:

Shows the demonstration video associated with the specified item ID.

Parameters:

item:String
item id

Example:

    MochiCoins.showVideo({ item: "xxx" });
    

showLoginWidget

showLoginWidget(options:Object):void

Description:

Shows the login widget.

Parameters:

x:Number
x coordinate
y:Number
y coordinate

Example:

    MochiCoins.showLoginWidget({ x:150, y: 150 });
    

hideLoginWidget

hideLoginWidget():void

Description:

Hides the login widget.

requestLogin

requestLogin():void

Description:

Present the user with a modal login screen.

getStoreItems

getStoreItems():void

Description:

Get items metadata from the store. This will fire the MochiCoins.STORE_ITEMS event.

Events:

MochiCoins.STORE_ITEMS
Event with metadata. See 2.0 Event definitions

saveUserProperties

saveUserProperties(properties:Object):void

Description:

This method allows you to save custom user state that can be retrieved on subsequent gameplays. This is done by passing an Object with key value pairs to this method. On subsequent MochiCoins.LOGGED_IN events, this object will be passed back (See MochiCoins.LOGGED_IN in 2.0 Event definitions).

Parameters:

properties:Object
An Object of user defined key value pairs. Only values of types Number, String, Boolean, Array, and Object will be saved. There is currently a 4KB limit (total serialized size) per user per game that can be saved.

Events:

MochiCoins.PROPERTIES_SAVED
User properties successfully saved. See 2.0 Event definitions

Example:

    MochiCoins.saveUserProperties({ hitPoints: 120 });
    

2.0 Event definitions

Events as well as any arguments your event handler will receive are listed below

MochiCoins.LOGGED_IN {name: "name", uid: unique_identifier, profileImgURL: url_of_player_image, hasCoins: True, userProperties: {hitPoints: 120}, api_token: "***"}
Player logged in. This events passes an object with the above keys to your event listener. The userProperties key is a per user per game property bag that you save with the saveUserProperties call. This event will also be sent after calling MochiServices.connect() if the player is already logged in.
MochiCoins.LOGGED_OUT
Player logged out. This event will also be sent after calling MochiServices.connect() if the player is not logged in.
MochiCoins.LOGIN_SHOW
Login widget showing.
MochiCoins.LOGIN_HIDE
Login widget hidden.
MochiCoins.STORE_SHOW
Store (single or multiple items) showing.
MochiCoins.STORE_HIDE
Store hidden.
MochiCoins.PROFILE_SHOW
Profile/inventory screen showing. Player viewing profile/inventory.
MochiCoins.PROFILE_HIDE
Profile/inventory screen hidden.
MochiCoins.ITEM_OWNED {id: item id, count: number owned, tags: [ "powerup", "enhancement" ], properties: { power: 20 }}
Player owns item. The values of the tags and properties keys are what you have set your Item Store under your developer account.
MochiCoins.ITEM_NEW {id: item id, count: number bought, tags: [ "powerup", "enhancement" ], properties: { power: 20 }}
Player bought item. The values of the tags and properties keys are what you have set your Item Store under your developer account.
MochiCoins.STORE_ITEMS [ { id: "ab473e7f87129ecb", name: "Super Cannon", desc: "A Super Cannon", imgURL: "http://..", cost: 150, maxNum: 1, tags: [ level-1, powerup] ], properties: { power: 20 } } ]
Calling MochiCoins.getStoreItems() will trigger this event, passes an array of item meta objects.
MochiCoins.PROPERTIES_SAVED
User properties successfully saved. This happens after a call to MochiCoins.saveUserProperties().
MochiCoins.WIDGET_LOADED
Login / Store SWF loaded. Use this event to know when the Login widget has been loaded. For example you may wish to display a splash screen until then to prevent a visual delay in the Login widget appearing. Calling MochiServices.connect() in the Preloader area of your game can also help load the widget prior to when it's needed.
MochiCoins.ERROR { type: MochiCoins.IO_ERROR }
An error occurred. Values for type are listed below:
  • MochiCoins.IO_ERROR: There was a network error.
  • MochiCoins.PROPERTIES_SIZE: MochiCoins.saveUserProperties() call failed. The property size is too large. There is currently a 4KB limit (total serialized size).
  • MochiCoins.NO_USER: MochiCoins.saveUserProperties() call failed. No user is logged in.

2.1 Sandbox Mode.

Sandbox Mode allows you to test the viewing and purchasing of items in your store without publishing the changes to all players. All changes to your store and items are only visible in Sandbox Mode to Sandbox users until the changes are published.

To test your store, items and purchasing in Sandbox Mode:

  1. Create or modify your store in your game's Coins tab. Your changes will only be available to Sandbox users until they are published via the Publish Changes button.
  2. In the Sandbox Settings menu on the right enter a list of Mochi Developer accounts to allow sandbox access.
  3. Login to the Coins Login Widget as a Sandbox user by using your Mochi Developer username prepended with an '@'. Your password is the same as your Mochi Developer password.
  4. In Sandbox Mode you have a large amount (1,000,000) of coins for testing.
  5. Clear all purchased items for Sandbox users with the Clear Sandbox Inventory button in the Sandbox Settings menu.

Ads API Documentation

This is a simple step-by-step guide to getting Mochi Ads API working with your Flash game. Click the links below to skip to any part of this document. The first two sections describe all that is required to get your ads running.

1.1 Prerequisites:

MochiAPI is not compatible with versions prior to Flash Player 7, and is no longer compatible with ActionScript 1.0.

Before you get started, make sure you have done the following:

  1. Sign up for a Mochi Developer account on www.mochimedia.com
  2. Log in and add a new game to your account.
  3. Download the MochiAPI include ZIP package.
  4. Choose your code options and copy the Mochi Ads API in-game code.

1.2 The Mochi API Ad Codes:

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:

mochi.as2.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 three types of ads you can place in your game -- a pre-game ad, an inter-level ad 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.

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.

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

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.

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 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:

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.

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); }
}
mochi.as2.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.

var myOptions:Object = {
    id: "xxxxxxxxxxxxxxxx",
    res: "360x240",
    clip: _root.myClip,
    ad_started: function ():Void { _global.game.pause(); },
    ad_finished: function ():Void { _global.game.resume(); }
}
mochi.as2.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:

  1. Make sure that the mochi folder is in your root project classpath.
  2. 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:

  1. Make sure that you use the MochiPreloader.as from the examples/flex folder from the MochiAPI ZIP package.
  2. Make sure that the mochi folder and MochiPreloader.as are in your project classpath.
  3. Tell your MXML application the preloader you want to use:
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" preloader="MochiPreloader">
    </mx:Application>
  4. NOTE: With inter-level ads, the Mochi API is unable to tell your game when it has finished via the MovieClip.stop() and MovieClip.start() methods. You must use the ad_started and ad_finished callback 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.

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.

1.2 Prerequisites

MochiAPI is not compatible with versions prior to Flash Player 7, and is no longer compatible with ActionScript 1.0.

Installing the Mochi Scores API

  1. Download and unzip the latest MochiAPI.
  2. 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

connect(id:String, clip:Object, onError:Function):Void

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.
  • Social network, Mochi Publisher and MochiGames integration.

2.2 Prerequisites

MochiAPI is not compatible with versions prior to Flash Player 7, and is no longer compatible with ActionScript 1.0.

Before you get started, make sure you have done the following:

  1. Sign up for a Mochi Developer account on www.mochimedia.com
  2. Log in and add a new game to your account.
  3. Create a leaderboard for your game.
  4. Download the latest version of MochiAPI and copy the include folder to your .fla directory.
  5. 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.

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: 1, weekly: 2, monthly: 3 },
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 rank 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}, …] }

MochiDigits

3.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.

3.2 Prerequisites

Installing the Mochi Scores API

  1. Download and unzip the latest MochiAPI.
  2. 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

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 7, and is no longer compatible with ActionScript 1.0.

Installing the Mochi Ads API

  1. Download and unzip the latest MochiAPI.
  2. 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.

Live Updates

1.1 Overview

Our version control and encryption technology 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

  1. Click on 'add game' like normal to add a game to the Mochi service.
  2. Check the box 'Use Live Updates' to enable the feature.
  3. Add a verification code to your game - this ensures you have access to the source code.
  4. 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

  1. Click on your game from your developer dashboard.
  2. Click on the 'game settings' link
  3. Under the 'game files' section, click on 'upload new version'.
  4. Select 'use Live Updates' for the new game version.
  5. 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 encryption and version control tool's 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:

  1. Open the Library window in Flash.
  2. Right click on any asset that is not already exported (but preferably one that is used anyways).
  3. Select “Linkage…”
  4. Check “Export for ActionScript"
  5. In text box labeled “Identifier”, enter “XXXXXXXX”
  6. 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 version control and encryption 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.