Swarm Documentation API Reference

Lunar Lander - A Basic Example

Estimated Integration Time: 45 minutes

This guide shows you how to integrate social features into Android's Lunar Lander game sample. The Lunar Lander game is a very simple game that is bundled with the Android SDK that is often used as an introduction to game development. In this basic example, no knowledge of callbacks is needed.

We'll show you how to complete a very quick integration of Swarm that demonstrates just how easy it is to add Leaderboards, Achievements, a Virtual Store, Cloud Data, and even a Dashboard button to a game. Please keep in mind that this example is intended to be quick and easy, and once you understand the basics you'll be able to create much more elegant implementations.

To get a sneak peak of the completed basic example, you can download an apk here.



Prerequisites



Import Lunar Lander

  1. Launch Eclipse
  2. Setup the LunarLander project by opening Eclipse's File menu > New > Android Project.
  3. On The New Android Project pop-up window, choose "Create project from existing source".
  4. Click on the "Browse..." button and find the LunarLander project directory in android-sdk/samples/android-*/LunarLander as shown in the screenshot below. Note that the value for * can be any number 9 or higher.
  5. Finally, click on the "OK" button and then on "Finish".
  6. You should now see the LunarLander project in Eclipse's Package Explorer as shown in the screenshot below.
  7. Stop! Build the LunarLander project and run it in an emulator so you can get a feel for the game.


Import and Link SwarmLibrary

  • In Eclipse, import "Existing Projects into Workspace" and choose SwarmConnect/library as the root directory.
  • Right click on LunarLander in the Package Explorer and choose "Properties".
  • On the left side, left click on "Android".
  • Under Library, click on "Add..." and choose SwarmConnect.
  • Click on "Apply" and then on "OK".
  • Do a "Build Project" and "Clean Build Project" on ONLY SwarmConnect.
  • Do a "Clean Build Project" on ONLY LunarLander.


Set Manifest Merger Flag

Add this line to the bottom of LunarLander's project.properties file:
manifestmerger.enabled=true


Extend SwarmActivity

For Swarm to properly respond to requests, open up LunarLander.java and configure the LunarLander class to extend SwarmActivity instead of Activity (SwarmActivity extends Activity). Note that the SwarmActivity class behaves the same as the Activity class, but it also does some work for you behind the scenes to manage interactions with Swarm.
public class LunarLander extends Activity {
public class LunarLander extends SwarmActivity {
Do an auto-import (Ctrl + Shift + O) to add the following line to LunarLander.java.
import com.swarmconnect.SwarmActivity;


Create Lunar Lander app in Swarm's Admin Panel

  1. Go to Swarm's Admin Panel (click here).
  2. Click on "Create a New App".
  3. Name the app Lunar Lander and click on Submit.
  4. Click on the Lunar Lander app in the app list.
  5. Click on the App Details button at the top of the Admin Panel.
  6. Write down the App ID and App Key, because you'll need them very soon.


Initialize Swarm

To initialize Swarm, in the LunarLander class's onCreate(Bundle savedInstanceState) method, add a call to Swarm.init(...) just below the call to super.onCreate(savedInstanceState). The result should look like this:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Swarm.init(this, SWARM_APP_ID, "SWARM_APP_KEY");
  1. Replace the int SWARM_APP_ID with the Lunar Lander App ID from your Swarm Admin Panel.
  2. Replace the String SWARM_APP_KEY with the Lunar Lander App Key from your Swarm Admin Panel.
You should now be able to build and run Lunar Lander. When the game starts, you'll be prompted to login to swarm. Congrats! That's the first step.


Add Swarm Dashboard Access

It can be very convenient to give users access to the Swarm Dashboard.

  1. Add the following line of code to the LunarLander class just below "private static final int MENU_STOP = 7;"
    private static final int MENU_SWARM = 8;
  2. Add the following line of code inside the LunarLander class's onCreateOptionsMenu(Menu menu) method, immediately above "return true;"
    menu.add(0, MENU_SWARM, 0, "Swarm");
  3. Add a call to Swarm.showDashboard() in the onOptionsItemSelected(MenuItem item) method, just below the MENU_HARD case. The result should look like this:
    case MENU_HARD:
        mLunarThread.setDifficulty(LunarThread.DIFFICULTY_HARD);
        return true;
    case MENU_SWARM:
        Swarm.showDashboard();
    
        // The call to finish() isn't normally necessary.
        // It fixes a bug in the LunarLander code.
        // Do not add it to your own games or apps.
        finish();
        return true;
  4. Build and run Lunar Lander. When the game launches, login to Swarm.
  5. After logging in, press the Menu button to bring up the in-game menu.
  6. Tap on the More button and then tap on Swarm to launch the Swarm Dashboard. There isn't much to see yet, but it will fill up when you add Leaderboards, Achievements, and the Virtual Store. Nice!


Add an Achievement

Step 1: Setup Achievement in the Swarm Admin Panel
Adding achievements is a great way to increase replayability, and they're easy to add too! First, a new achievement for Lunar Lander in the Swarm Admin Panel.

  1. Go to Swarm's Admin Panel (click here).
  2. Click on Lunar Lander.
  3. Click on Achievements and then click on "Create new Achievement."
  4. Set the title of the Achievement to "Landed Once!"
  5. Set the description of the Achievement to "You landed once in Lunar Lander!"
  6. Set the Hidden radio button to "No" and do not change the Order Id.
  7. Set the Points to 10 and click on Submit.
  8. Write down the Achievement ID number for the Landed Once! Achievement, because you'll need it very soon.

Step 2: Setup Achievement in the Lunar Lander Code
Now that an achievement has been setup in the Swarm Admin Panel, update the Lunar Lander code so that players can start earning it.

How about making the Lunar Lander game a bit easier? It'll make playing and testing it more fun too! Make the following changes in LunarView.java:
public static final int TARGET_SPEED = 28; // > this speed means crash
public static final double TARGET_WIDTH = 1.6; // width of target
public static final int TARGET_SPEED = 2000; // > this speed means crash
public static final double TARGET_WIDTH = 5.0; // width of target

Ok, now let's setup that achievement!

Then, add code to give the achievement to the user when the user successfully lands the space ship. In the LunarView class, check to see if the user has won, and add a call to unlock the achievement inside of the setState(...) method. The result should look like this:
public void setState(int mode, CharSequence message) {

    // Did we win?
    if (mode == STATE_WIN) {

        // Give the achievement for successfully landing!
        SwarmAchievement.unlock(ACHIEVEMENT_ID_LANDED);
    }

    /*
     * This method optionally can cause a text messa...

Replace the ACHIEVEMENT_ID_LANDED with the Achievement ID number from the Swarm Admin Panel.

Now Lunar Lander will give an achievement to the user the user successfully lands the space ship. It's okay to give the same achievement to a user multiple times. Swarm will ensure that the user actually only earns it once.


Add a Leaderboard

Step 1: Setup Leaderboard on Swarm's Admin Panel
Adding Leaderboards is a great way to increase user retention and improve session length. Users typically enjoy competition, so let's setup a Leaderboard!

  1. Go to Swarm's Admin Panel (click here).
  2. Click on Lunar Lander.
  3. Click on Leaderboards and then click on "Create new Leaderboard."
  4. Name the Leaderboard "Fastest Landers", set the Default Sorting to "Ascending", the Format to "Time", and click Submit.
  5. Write down the Leaderboard ID number for the Fastest Landers Leaderboard, because you'll need it very soon.

Step 2: Setup Leaderboard in Lunar Lander Code
Now that a leaderboard has been setup in the Swarm Admin Panel, update the Lunar Lander code so that users can start competing for the top score.

Next, setup a scoring mechanism so that users can earn a score based performance. In this case, the faster a user lands the space ship, the higher the score. In LunarView's LunarThread class, add
public long startTimer = 0;

To complete the leaderboard code, in the LunarView class add the following code block inside of the public void setState(...) method, just after the if (mode == STATE_WIN) check and just before the synchronized (mSurfaceHolder) line. The result should look like this:
    public void setState(int mode, CharSequence message) {

        // Did we win?
        if (mode == STATE_WIN) {

            // Give the achievement for successfully landing!
            SwarmAchievement.unlock(ACHIEVEMENT_ID_LANDED);

            // Leaderboards come in 3 types, INTEGER, FLOAT, and TIME
    	    // TIME Leaderboards are submitted in seconds.
    	    float time = (float)(System.currentTimeMillis() - startTimer) / 1000f;

            // Submit the score to the leaderboard where LEADERBOARD_ID
            // is the Leaderboard ID number shown in the Admin Panel
            SwarmLeaderboard.submitScore(LEADERBOARD_ID, time);

    	    // We could also take the user to the leaderboard after submitting.
    	    // SwarmLeaderboard.submitScoreAndShowLeaderboard(LEADERBOARD_ID, time);
        }

        // We start a timer when the game starts to see 
        // how long it takes for the user to win.
        // Note: This is not a great example of high-scoring as 
        // pausing/unpausing is not taken into consideration.
        if (mode == STATE_RUNNING) {
            startTimer = System.currentTimeMillis();
        }
			     
        /*
         * This method optionally can cause a text mess...
Congrats! Now every time the user successfully lands the space ship, their score will be sent to the leaderboard and the user's leaderboard rank will be updated if necessary.


Add Cloud Data

Cloud Data is a conveient way to store data on Swarm's secure servers. Cloud Data uses key value pairs, similar to Android's Shared Preferences. In this example, Lunar Lander uses Cloud Data to track the number of times a user has successfully landed the space ship.

Setup Cloud Data in Lunar Lander Code

Add the following block of code inside LunarView's public void setState(...) method, just below the if (LunarLander.leaderboard != null) { } code block and just above the last closing curly brace "}" of the if (mode == STATE_WIN) statement.
// Cloud Data
// Track the number of times the user has successfully landed (total)
Swarm.user.getCloudData("numWins", new GotCloudDataCB() {
    public void gotData(String data) {

        // Set a default...
        if (data.length() == 0) data = "0";

        // Parse the existing number of wins.
        int numWins = Integer.parseInt(data);
        numWins++;
    
        // Save the new value back to the cloud.
        Swarm.user.saveCloudData("numWins", ""+numWins, null);

        // Optional: Tell the user how many times they've won!
        Message msg = mHandler.obtainMessage();
        Bundle b = new Bundle();
        b.putString("text", "You've won "+numWins+" times total!");
        b.putInt("viz", View.VISIBLE);
        msg.setData(b);
        mHandler.sendMessage(msg);
    }
});
Congrats! You're now using Cloud Data to track each user's total number of wins. Pretty handy, huh?


Add a Virtual Store

Adding a virtual store is a great way to improve monetization. In this example, Lunar Lander uses Swarm's virtual store to sell different backgrounds that the user can buy.

Step 1: Setup Virtual Store in Swarm's Admin Panel
Create a Category
  1. Go to Swarm's Admin Panel (click here).
  2. Click on Lunar Lander.
  3. Click on Store and then click on "Create a Category."
  4. Name the category "Backgrounds" and click Submit.

Create an Item
  1. Click on Store again (at the top of the Admin Panel) and then on "Add Items."
  2. Name the Item "Many Moons", set Consumable to "No", leave Payload blank, and click Submit.
  3. Write down the Store Item Id for the Many Moons Item, as you'll need it very soon.

Create an Item Listing
  1. Click on Store again and then on "Add Item Listings."
  2. Title the Item Listing "Many Moons Background", choose an Icon, set the Price to "10", the Quantity to "1", and the Status to "Active." Make sure to choose an icon that's 80px wide by 80px tall. If you need an icon, use this one.
  3. Write down the Store Item Listing Id for the Many Moons Background Store Item Listing, as you'll need it very soon.

Step 2: Setup Virtual Store in Lunar Lander Code
Add class variables to LunarLander

In the LunarLander class, add the following variables. Replace itemIdFromAdmin with the Store Item Id number (from above) and replace itemListingIdFromAdmin with the Store Item Listing Id number (from above).
public static final int BACKGROUND_ITEM_ID = itemIdFromAdmin;
public static final int BACKGROUND_ITEM_LISTING_ID = itemListingIdFromAdmin;
public static SwarmStoreListing backgroundListing;
public Button purchaseButton;

Next, load the store by adding the following code inside of the userLoggedIn method within the LunarLander class's SwarmLoginListener. This code block should be added just below the closing "});" of SwarmLeaderboard.getLeaderboardById.
// Load the store (just 1 item in this example)
SwarmStore.getStore(new GotSwarmStoreCB() {
    public void gotStore(SwarmStore store) {
        
        if (store != null) {
	
            // We only care about the one item (background)
	    for (SwarmStoreCategory category : store.categories) {
                for (SwarmStoreListing listing : category.listings) {

                    if (listing.id == BACKGROUND_ITEM_LISTING_ID) {
                        backgroundListing = listing;
                    }
                }
            }
        }
    }
});

Then, add a purchase button to the lunar_layout.xml file by adding the following code snippit inside of the RelativeLayout, just below the TextView.
<Button
    android:id="@+id/purchase"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Buy Background"
    android:layout_alignParentRight="true"
    />

It's time to create a method in the LunarView class's LunarThread that can handle the background change.
public void changeBackground() {
    mBackgroundImage = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.manymoons);
    mBackgroundImage = mBackgroundImage.createScaledBitmap(mBackgroundImage, mCanvasWidth, 
                                                           mCanvasHeight, true);
}

You'll notice that this method requires a drawable called manymoons. Download the manymoons landscape and manymoons portrait background images and add them to the Lunar Lander project's res/drawable-land and res/drawable-port directories respectively. After downloading the background images and putting them into their respective folders, rename the images so that they are both exactly named manymoons.png.

Now add some functionality to the purchase button so that the user has a way to purchase the new Many Moons Background. In the LunarLander class, setup the purchaseButton by adding the following code just below the call to setContentView(R.layout.lunar_layout).
// Attach a purchase popup to the purchase button.
purchaseButton = (Button)findViewById(R.id.purchase);
purchaseButton.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        if (backgroundListing != null) {
            backgroundListing.purchase(LunarLander.this, new ItemPurchaseCB() {

                // We don't care about this case.
                public void purchaseFailed(int arg0) {
                }

                // If the user successfully purchases the Many Moons Background
                public void purchaseSuccess() {
                
                    // Change the background to the Many Moons Background
                    mLunarThread.changeBackground();

                    // Hide the purchase Button
                    purchaseButton.setVisibility(View.GONE);
                }
            });
        }
    }
});

Finally, add one last block of code inside of the userLoggedIn method (in LunarLander's SwarmLoginListener) just below the last closing curly brace of the SwarmStore.getStore(...) call. This block of code will load the user's inventory upon successful login.
// Load the user's inventory to see if they have purchased the new background...
Swarm.user.getInventory(new GotInventoryCB() {
    public void gotInventory(SwarmUserInventory inventory) {

        if (inventory != null && inventory.containsItem(LunarLander.BACKGROUND_ITEM_ID)) {

            // They own the background, swap the background image.
            mLunarThread.changeBackground();

            // Hide our purchase button
            purchaseButton.setVisibility(View.GONE);
        }
    }
});

Improve Instructions

The LunarLander example code that ships with Android needs a few improvements to make it accessible on devices without a physical keyboard. Make changes in res/values/strings.xml to match the lines of code shown below.
<string name="mode_ready">Lunar Lander\nTo Play: press\nMenu button then\nchoose Start</string>
<string name="mode_pause">Paused\nTo Play: press\nMenu button then\nchoose Start</string>
<string name="mode_lose">Game Over\nTo Play: press\nMenu button then\nchoose Start</string>
<string name="mode_win_suffix">in a row\nTo Play: press\nMenu button then\nchoose Start</string>

Congratulations!

You're all done! Now it's time to compile and run the Lunar Lander example to see all of Swarm's features in action. Not too tough, right? If something isn't working quite right in your own Lunar Lander code, download the completed Lunar Lander example source code and then fill in your App ID, App Key, and other applicable numbers. By downloading the source code you are agreeing to the Terms and Conditions.

You can also just download the completed, precompiled apk file from here.

The Lunar Lander open sourced example demonstrated very simple implementations of great social features that you can add to your own games and apps. Now you should have a good, basic understanding of the Setup, Dashboard, Achievements, Leaderboards, Cloud Data, and Virtual Store. We highly recommend getting creative with your own Swarm implementation to find a solution that provides an optimal experience for your users. For a little inspiration, check out the Pro Tips as well as the complete API Reference.

Thanks for following the Swarm Lunar Lander Basic Open Sourced Example! If you have any questions or comments, we'd love to hear your thoughts. Please send all feedback through the Swarm Support Center.