JavaOne Hands-On Lab

Your First Mobile Game

Lab-5502

Copyright 2009 Sun Microsystems

 

Lab-5502: Your First Mobile Game

Expected Duration: 100 minutes

Last Updated: 10 March, 2009

This Hands-on Lab takes you through the process of developing a mobile game with the assistance of the Game Builder included in the NetBeans Java ME module. Participants will learn how to quickly create compelling SVG UIs using the new SVG Form components. The lab will also cover the basics of creating a MIDP application and connecting it to a web service.

In this lab we create a simple game where the heroes Duke and James collect bricks. At first Duke will be controlled by the player and James will be managed by the computer. In the last exercise will use web services to make it a true multiplayer game.

All menus in this application use an SVG UI and you will create them yourself during the lab.

Copyright
Copyright  2009 Sun Microsystems, Inc. All rights reserved. Sun, Sun Microsystems,
the Sun logo, Solaris, Java, the Java Coffee Cup logo, JavaOne, the JavaOne logo,
and all Solaris-based and Java-based marks and logos are trademarks or registered
trademarks of Sun Microsystems, Inc. in the United States and other countries.
                        

Prerequisites

 

This hands-on lab assumes you have some basic knowledge of, or programming experience in, the following technologies:

You will need to refer to the accompanying presentation 5502_mobilegame.pdf during the lab.


System Requirements

 

Software Needed For This Lab

 

Please install the following set of software. If you have any questions on installation, please feel free to send questions to the lab forum mentioned below.


Notations Used in This Documentation

 

Lab Exercises

 

Additional Resources

 

Where To Go For Help

 

Exercise 0: Install and Configure Lab Environment

 

In addition to the contents of this lab's zip file you should have the following installed on your computer:

Exercise 1: Create MIDP Application (15 minutes)

 

In this exercise we will create a new Mobile Information Device Profile (MIDP) application using NetBeans Java ME support. We will see how the IDE's Java ME Visual Designer simplifies the creation of mobile application workflows.


Background Information

 

NetBeans Mobility makes it easy for programmers to start developing for the Java ME platform quickly, even if you've only had Java SE programming experience. If you are programming mobile devices for the first time, you can just think of Java ME as having a more limited version of the Java SE API, and let NetBeans take care of Java ME specific issues. Though there are more differences to Java ME than just a smaller API, it's not necessary to know all of them before producing a working mobile application. To help you get started, here are some terms that are used throughout this document:


Steps to Follow

 

Step 1: Creating NetBeans Java ME Project

  1. If NetBeans is not already running, start it.
  2. Open the New Project wizard. To do it click the New Project... button on the toolbar or select  File > New Project... from the main menu.
  3. Select Java ME > Mobile Application as project type and click Next.

  4. Type MobileGame as the project name and uncheck the Create Hello MIDlet box and click Finish to create the project.

Step 2: Defining the application workflow with the Visual Designer

  1. Expand the Source Packages node in the Project tree and select <default package>
  2. Add a new java package named game to source packages.

    To do it select New > Java Package... in contextual menu of the <default package> node.

    In the New Java Package dialog enter the package name, game and click Finish.

  3. Add a new VisualMIDlet to the game package. You can use the default name.

    The new MIDlet will be opened in Visual Mobile Designer's Flow view by default.

    The Mobile Device element representing the MIDLet is always shown in the Flow view. The Visual Designer is a drag-n-drop interface that enables us to add new displayables and manage the application workflow.

  4. Add the SVG Form to the application by dragging it from the SVG Components category of the palette.

  5. To make SVG Form the first displayable that will be shown on the device screen after the MIDlet is started, Add a connection from the Started action of the Mobile Device to svgForm by dragging the mouse with the left button pressed from the Started action to the svgForm component

  6. The next element to add to the application workflow is the game, but until we import the game classes, we can't display them in the Visual Designer. For the moment we'll postpone this step until Exercise 3.

  7. After the game is finished, we will show the winner using another SVG form.

    Add the second SVG form to the flow view.


Summary

 

In this exercise, you saw how to rapidly create a mobile application from scratch using the Visual Movile Designer in NetBeans.

In the next Exercise we will create SVG images for displaying the SVG forms we created.

Exercise 2: Creating an SVG UI (25 minutes)

 

We will create compelling SVG menus and forms for our MIDP Application using the tools provided by NetBeans without any need for external editors. The SVG Composer allows us to compose an SVG Form from standard form components and the Visual Designer will embed it into the application workflow.


Background Information

 

Steps to Follow

 

Step 1: Creating the main menu SVG Image

  1. Create a new package called svg which will contain our SVG images.

  2. Create a new SVG image called main_form

    To do this open the New File dialog by selecting New > Other... in the contextual menu of the svg package node.

    Select Other > SVG File and click Next.

    Type main_form as the file name and click Finish. The main_form is created in the svg package and an empty image is opened in SVG Composer.

  3. In the Palette tab at the right find the Form Components group and expand it.

    Drag and drop the Label component and from the palette to the image view in the editor as shown in the following screenshot.

    In the Navigator window you can see that id = "label_0" was added to the main_form.svg xml image file.

  4. Add two Button SVG Components using the same method we used in the previous step and place them as they are shown in the screenshot.

  5. Save your changes by clicking the Save All button on toolbar or type Ctrl+Shift+S.

Step 2: Connect SVG Images to the SVG Form component in the Visual Designer

  1. Open the VisualMIDlet.java file created in the previous exercise.

  2. Drag and drop the main_form.svg SVG image from project tree to the svgForm component in the Flow view of the Visual Designer.

    You can see svgButton and svgButton1 elements shown in the SVG Buttons section of the svgForm component. When you Select svgForm you can also see the elements in the SVG Components node in the navigator.

  3. You can update the image connected to the svgForm component in the SVG Image Properties window.

    To open the SVG Image property editor select svgForm in the editor and the image properties will open.

    Click the ellipse button (button with three dots) next to SVG Image property value.

    If you switch to Recognized SVG Components in the SVG Image property editor, you can see all of the recognized SVG From Components. You can change their tab order here if needed.

Step 3: Customizing SVG Form Components

  1. Now switch to the Screen view of Visual Designer. and select svgForm from combo-box, as it is shown in the screenshot.

    When the svgForm preview is opened in the editor it allows you to see an approximate view of the component on the device screen.

  2. To change the Label text to something more descriptive select the label in the Screen view to open it's properties and change the Text property value to Collect Blocks.

    You can see the new value displayed in the Screen preview.

  3. Use the same steps to change the svgButton text (left button) to Play

    Hint: You can see the component's instance name in the Properties window or in the Navigator tree. The component selected on the Screen view will be selected in the navigator view.

    We also need to change the svgButton1 text (right button) to Exit

Step 4: Creating, connecting and customizing the second SVG Form Component

  1. Use the same steps we used previously to create a new SVG Image called game_result.

  2. Put two labels and one button on the image as shown in the screenshot and save your changes wen finished.

  3. Connect the game_result with the svgForm1 component in the VisualMIDlet Flow view by dragging and dropping game_result from the project tree to the svgForm1 component.

    Note: The svgButton2 should be shown in the svgForm1 component and the svgButton2 and two SVG labels should be shown in the Navigator window.

  4. Open svgForm1 in the Screen view
  5. Select the first label and change the text value in the Properties editor to "The Winner Is."

    Note: For this application we don't need to change the other two SVG elements.

Step 5: Assigning actions to SVG Buttons

Now we can assign actions to the SVG Buttons we have open.

  1. Open the Flow view of VisualMIDlet.
  2. If a user clicks the OK button in game_result form (svgForm1 component in the Visual Designer), we want the the main_form SVG to be opened (svgForm component in the Visual Designer). To enable this behavior, connect the svgButton2 action of the svgForm1 component to the svgForm.

  3. Connect the Exit button of the svgForm (svgButton1 action) to the Mobile Device. This will stop the MIDlet after the Exit button is clicked.
  4. Clicking the SVG button Play should start the game. In order to connect the svgButton action to the game we have to create a game to use in the Visual Designer. We'll do that in the next exercise.

The solution of this exercise is provided as a "ready to build and run" NetBeans project, <lab_root>/solutions/exercise2/MobileGame.


Summary

 

In this exercise you saw how to create SVG Forms using the NetBeans SVG Composer and how to use them in the VisualMIDlet workflow. Creating SVG images in the Composer is just a starting point because you can also open these images in your favourite SVG editor and design them as you like.

Exercise 3: Creating the game (30 minutes)

 

In this exercise we will create a mobile game based on the MIDP 2.0 Game API. NetBeans Java ME support provides the Game Builder module to help us create a the game framwork with the essential visual elements such as TiledLayers, Sprites, and Scenes so that we can concentrate our efforts on creating the game logic.


Background Information

 

Visual editing support for the MIDP 2.0 Game API (JSR 178) including the creation and editing of Sprites, TiledLayers and their arrangement into scenes. The main objective of the Game Builder module is to reduce the effort involved in creating common game components.


Steps to Follow

 

Step 1: Open the existing project

In this exercise you will need some additional files we have prepared. To use these files we are going to start by opening a project that contains them.

  1. Close the MobileGame we project created in Exercise 1.
  2. Open the existing lab project by choosing File > Open Project. A filechooser dialog appears.
  3. Select the MobileGame project in the /exercises/exercise3/ folder.
  4. The opened project appears in Projects tab of the IDE.

Step 2: Create a new Visual Game Design file

  1. Expand Project and Source Packages nodes.

  2. Right-click and choose New > Game Builder... on the game package node.

  3. In the New File dialog accept the default MIDP Class Name GameDesign and click Finish.
  4. The newly created Game Design file is opened in the Game Builder with the Game Design view opened by default.

Step 3: Create a new Sprite

Now we are going to create an animated sprite of Duke walking.

  1. Click on the Create Sprite... link and the New Sprite dialog is opened.

  2. Type dukeWhite in the Sprite Name textfield and select the images/duke.png from the Select Image list.

    The list contains all images of the supported type available in the current project. Move the sliders to adjust the tile height and width to 25px and click OK.

  3. The newly created sprite is opened in Sprite Editor of the Game Builder.

  4. You can drag image tiles from the list on the bottom to specific frames of a sequence. Drag images to the first four frames to get the sequence seen in the below screenshot.

  5. Four tiles in enough to create the appearance of Duke walking, so let's remove the final, 5th frame, from the sequence.

    Right-click on the 5th frame and choose Remove frame from the contextual menu.

Step 4: Create the second Sprite

  1. Use the Drop Down menu in the editor toolbar and switch to the Game Design view.
  2. Click Create Sprite... to create another sprite.

  3. Name the new Sprite JamesG and select the /images/james.png images.

    Adjust the tile size to the width and height of 25px.

  4. Change the sprite sequence as we did for the white Duke sequence by dragging the images into positions to look like the screenshot below. Again, we want to remove the unused 5th frame.

Step 5: Create a new Tiled Layer

  1. Switch back to Game Design view using the drop down menu in the toolbar and click Create tiled layer... to create add a new tiled layer to our game. The New tiled layer dialog opens.

  2. Type bricks as the tiled layer name and select the /images/brick.png image and verify that the tile size is 25x25 px.

    Click OK and the Tiled Layer editor opens.

  3. In the Tiled Layer editor select paint mode by clicking the far left button on the editor toolbar. .

    Select the brick.png image from the tiles list at the bottom.

    Add the image into the table cells by clicking or dragging the mouse with the left mouse button pressed and held down.

    Don't worry too much about which cells you put bricks in for now.

    Note: Leave the perimeter cells empty, we will create a border layer later on and need this area to be available.

    The Tiled Layer with bricks to collect is ready.

  4. Create one more Tiled Layer using the /images/bord.png image and name it border.

    In the opened Tiled Layer editor click once on the Enable layer auto-resizing toggle button. This switches off the rows and columns auto add feature when you drag the mouse out of an existing layer.

    Draw a evenly square border as shown in the screenshot.

Step 6: Create Game Scene

  1. Switch back to the Game Design view and click Create scene... and the New Scene dialog is opened.

    Name the scene level1.

  2. Add the tiled layer with bricks to the scene by right-clicking and choosing Add tiled layer > bricks from the contextual menu. When the tiled layer is added move it to the top-left corner of the design canvas.

  3. Add the tiled layer, border, to scene by repeating the step above and choosing border from the contextual menu.
  4. Add the Duke sprite to the scene by right-clicking the canvas and choosing Add sprite > dukeWhite from the contextual menu. When the sprite is added, move it to the top-left corner of the canvas.

  5. Add the James sprite to the scene using the same steps above and choosing JamesG from the contextual menu. Move the JamesG sprite to the bottom-left corner of the canvas as shown in the below screenshot.

The solution of this exercise is provided as a "ready to build and run" NetBeans project, <lab_root>/solutions/exercise3/MobileGame.

Exercise 4: Adding the game logic (30 minutes)

 

In this exercise we will describe how to add gaming logic to manage the behavior of the tiled layers and sprites.


Steps to Follow

 

At the end of this exercise you will have Turn-Based Strategy Game where Duke and James collect bricks.

Each player will have five moves per turn. When the bricks are gone, the player with the most bricks collected wins.

Step 1: Open the existing project

In this exercise you will need some additional files that we have prepared for this Hands on Lab. To use these files we will first open the project which contains them.

  1. Choose File > Open Project and the filechooser dialog appears.
  2. Select the MobileGame project in the <lab_root>/exercises/exercise4/. The opened project appears in Projects tab of the IDE.
  3. Note: two new packages are inside the opened project:

    logic - Contains classes that manage the game workflow

    logic.players - Classes for the player interface and it's implementations.

Step 2: Add the GameCanvas to the Visual Designer

The BricksGameCanvas which extends the GameCanvas, is the main displayable class of the game. Let's add it into the application workflow using the Visual Designer.

To use the BricksGameCanvas in the Visual Designer, we will add it to the palette as a custom component.

  1. Open the game.VisulMIDlet.java file in the editor by double clicking on it in the Project window.

    Right-click the mouse on any point of the palette area and select Palette Manager... from the centextual menu.

  2. Click Add to Palette... button in the Palette Content dialog.

    The Add to Palette Wizard opens and the MobileGame project is selected by default so we can click Next.

    Select logic.BricksGameCanvas from the Select Classes window and click Finish.

    Verify that the BricksGameCanvas component is added to the Custom palette group in the Palette Manager and then click Close.

  3. You can also verify that the component has been added by scrolling down to the bottom of the Palette and seeing that the BrickGameCanvas component is there.

Step 3: Add the GameCanvas to the application workflow

  1. Drag-n-drop BrickGameCanvas from the Palette to the flow view of the VisualMIDlet.

  2. The BricksGameCanvas has only a constructor with the parameter VisualMIDlet:

        public BricksGameCanvas(VisualMIDlet midlet)
    			    

    To use this constructor in the source code generated by Visual Designer we need to update the midlet(1.contructor-1.parameter defined property of the BricksGameCanvas

    Open the custom editor for midlet(1.contructor-1.parameter defined property by clicking the (...) button.

    Type this and press OK.

  3. The GameCanvas should be opened when the user presses the Play button on the svgForm.

    To enable this behavior, add a connection from the svgButton action on the svgForm to the BricksGameCanvas displayable item.

  4. Note the new Alert element we added to the visual designer canvas of this project. It is used to display critical error messages to the user.

Step 4: Start the Game Thread after switching to GameCanvas

  1. Open game.VisualMIDlet.java in the editor if it is not opened yet.

    Switch to the Visual Designer's Source view

  2. Add a new attribute named GameThread to the VisualMIDlet class:

        private GameThread myGameThread; //[ex4]
                                    

    The source code in the editor should now look similar to the following:

  3. Go back to Flow view and right-click the svgButton in the svgform and choose Go To Source from the contextual menu.

  4. In the expanded getSvgButton() method source we need to add the code below to enable the following:
    • Create a new GameThread object the implements Runnable
    • Create a new Thread object with GameThread as a parameter
    • Starts the created thread

                        myGameThread = new GameThread(getBricksGameCanvas(), VisualMIDlet.this);// [ex4]
                        Thread gameThread = new Thread(myGameThread);// [ex4]
                        gameThread.start();// [ex4]
                                    

    Paste the code snippet and replace the following comment: //Some action after switch after switchDisplayable method invocation.

    The result looks like the following:

  5. Now add the following stopGame() method to the end of the class methods declarations. It will stop the Game Thread when requested.

        private void stopGame(){
            if (myGameThread != null) {
                myGameThread.requestStop();
            }
        }
                                    
  6. Find the gameOver method and add the following:

            getSvgLabel2().setText(winnerName);
            stopGame();
                                    

    The method should now be like the following:

        /**
         * set all the things up when the game is over
         * @param score
         */
        public void gameOver(String winnerName) {
            getSvgLabel2().setText(winnerName);
            stopGame();
        }
                                    
  7. Now add the stopGame() invocation to the destroyApp method body.

    The updated destroyApp looks like the following:

        /**
         * Called to signal the MIDlet to terminate.
         * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
         */
        public void destroyApp(boolean unconditional) {
            stopGame();// [ex4] 
        }
                                    
  8. Fix Imports to correct any errors.

    For example:

    Use Fix Imports from the right-click contextual menu to make these types of corrections.

  9. We've made a lot of changes in the source code during this step. Let's save what we've done so far by using the Save All button on main toolbar or by choosing File > Save All.

Step 5: Initialize the game UI

Here we will initialize the game UI parts, created in the GameDesigner so that we can use them in BricksLayerManager.

  1. Open the logic.BricksLayerManager.java file in the source editor.

    Find the public void init() method. It should be located after the constructor.

    Copy the following code:

            gameDesign = new GameDesign();
            
            dukeSprite = gameDesign.getDukeWhite();
            jamesSprite = gameDesign.getJamesG();
            dukeSprite.defineReferencePixel(dukeSprite.getWidth() / 2, 0);
            jamesSprite.defineReferencePixel(jamesSprite.getWidth() / 2, 0);
            
            dukeSpriteAnimator = new SpriteAnimationTask(dukeSprite, false);
            jamesSpriteAnimator = new SpriteAnimationTask(jamesSprite, false);
    
            bricksLayer = gameDesign.getBricks();
            wallsLayer = gameDesign.getBorder();
            
            gameDesign.updateLayerManagerForLevel1(this);
    
            timer = new Timer();
            timer.scheduleAtFixedRate(dukeSpriteAnimator, 0, gameDesign.dukeWhiteseq001Delay);
            timer.scheduleAtFixedRate(jamesSpriteAnimator, 0, gameDesign.JamesGseq001Delay);
    
                                    

    Paste the code to the beginngng of the method body and replace the // [ex4 - add here] comment line.

    The Method should now be like the following:

    The inserted code performs the fololowing actions:

    • Creates a new instance of the GameDesign with the graphical data we created in Exercise 3.

    • Stores the Duke and James sprites using the gameDesign.getDukeWhite() and gameDesign.getJamesG().

    • Defines the reference pixels for the sprites used in the methods for setting and retrieving the sprite location.
      Examples include: setPosition(x,y), getX() and getY().
      By default the reference pixel is the top-left corner coordinates.

    • Creates the SpriteAnimationTask instances for James and Duke.

    • Stores the Wall and Brick tiled layers

    • Stores the first scene of level1 that we created by combining the Sprites and Tiled Layers in the Game Designer in Exercise 3 that's returned by gameDesign.updateLayerManagerForLevel1

Step 6: Assign Sprites to players

In this step we assign the Duke and James sprites to players. For this lab we will do a static assignment, But you are free to make it random or use any other rules you would like.

  1. If you closed BricksLayerManager already, we need to open it again.

  2. Find the initPlayers() method and copy the following code which enables the project to:

    • Create the OwnerPlayer instance connecting it to the Duke sprite
    • Create the PhonePlayer instance connecting it to the James sprite
             // init player 1
             myPlayer1 = new OwnerPlayer(dukeSprite, dukeSpriteAnimator, myGameInfo);
             // init player 2
             myPlayer2 = new PhonePlayer(jamesSprite, jamesSpriteAnimator, myGameInfo);
                                    

    Paste the the initPlayers() code over the // paste players initialization here comment.

    The result looks like the following:

  3. Now Fix Imports and Save the changes.

Step 7: Play the Game

It's time to test your game.

  1. Right-click the project node and choose Run from the contextual menu. The project builds and the phone emulator will launch.

    Note: this emulator is not touch-enabled, so you must use the buttons in the phone's UI rather than the screen to launch and play the game.

  2. Click the Launch button to run the VisualMIDlet selected on the screen.

  3. In the main application menu you use the Up and Down arrow keys to select Play or Exit.

    Select Play and click the button in the middle of the phone emulator to begin playing.

  4. The game canvas and game thread start and the device screen displays the following game information:
    • Current player - either You or the Opponent
    • Bricks - the total number on the canvas and the number collected by the active player
    • Steps left - Steps remaining in the current turn
  5. Enjoy The Game!

    Use the arrow keys to move your player and collect bricks.

The solution to this exercise is provided as a "ready to build and run" NetBeans project and can be found here: <lab_root>/solutions/exercise4/MobileGame_solution4.

Exercise 5: Play with friends (20 minutes)

 

The game we have created allows you to compete against the default player mode that runs on your mobile phone. In this exercise we will extend the game to allow multiple players using a web service that will let you exchange moves with an opponent on another mobile device. The Java ME Web Service API (JSR 172) support in NetBeans will help us to add this extended functionality to our application.


Steps to Follow

 

Step 1: Start Web Service

In this step we will deploy and start a Web Service to enable multi-player gaming. For testing purposes you will use your own Web Service, running locally.

  1. We will start by opening a WebApplication project which contains the web service used to enable multiplayer gaming on the web.

    Open the project by choosing File > Open Project. A filechooser dialog appears.

    Select the BrickGameWebApplication project in the <lab_root>/solutions/exercise5/.

    The opened project appears in the Projects window of the IDE.

  2. Right-click the Project node and choose Deploy from the contextual menu.

    The Application Server should be started automatically and the Web Application project should be deployed.

    An error message dialog and error message in the Glassfish output window are displayed if there is a problem.

Step 2: Open an existing project

In this exercise you need some additional files we prepared for this lab.

To use these files, we are going to open the project that contains them.

  1. Open the project by choosing File > Open Project. A filechooser dialog appears.

    Select the MobileGame project in the <lab_root>/exercises/exercise5/.

    The opened project appears in Projects window of the IDE.

  2. Note that a New Player implementation appeared in logic.players package:

    • WebPlayer - Player implementation that will use the Web service client to send your moves to the web service and load the opponent's moves.

      Note that the code is not yet compilable because it stilll needs the web service we are going to create.

Step 3: Create a new configuration

In this step you create a new project configuration that allows you to have two versions of the same project:

  1. Right click the MobileGame project node and cheoose Properties from the contextual menu.

  2. In the Project Properties dialog, select Add Configuration... from Project Configuration drop down menu.

    The Add Configuration dialog opens.

  3. Name the new configuration OnlineGame and Click OK.

  4. The new project configuration is created and currently the active configuration.

  5. In the Mobile Game configuration dialog select Abilities from the Category menu.

    Deselect the Use Values from DefaultConfiguration option.

  6. Click the Add button.

    In the Add Ability dialog type ONLINE as the name and true as the value and Click OK.

  7. Click OK to close project properties.

Step 5: Generating a Web Service Client

We will generate a Web Service Client using the wizard provided by NetBeans Mobility.

  1. Right-click th eproject node and choose New > Java ME Web Service Client... from the contextual menu.

  2. In the WSDL URL field type http://localhost:8080/BrickGameWebApplication/BricksWebServiceService?wsdl and click the Retrieve WSDL button.

    After loading and validating the WSDL file some of the the Java ME Web Service Client Information fields are filled and the Local filename is displayed.

  3. In the Client Name field type BricksWebService and name the Package wsclient.

  4. Press Finish and Web Service client stub is generated. Note that the logic.player.WebPlayer.java is no longer broken. If it's still broken, there may be a typo in the Web Service Client name or package.

Step 5: Use the Web Service Client to start multiplayer game

We will use WebPlayer in this lab. It generates a Web Service Client that displays player moves with the opponent playing on the other device.

First we have to initialize the game.

  1. Open the logic.BricksLayerManager.java file in the editor.

  2. Add the following attribute and method code to the BricksLayerManager class

        private BricksWebServiceService client = null;
        public BricksWebServiceService getMobileClient() {
            if (client == null) {
                client = new BricksWebServiceService_Stub();
            }
            return client;
        }
                                    
  3. Find the initPlayers() method.

    Update the method so that it uses a different behaviour depending on the selected project configuration by replacing the four lines where the players are initialized.

    Replace the existing code with the following:

    //#if ONLINE == "true"
            try {
                String id = getMobileClient().initPlayer("");
    
                int order = 0;
                while ((order = getMobileClient().startGame(id)) == 0){
                    myWaitingForOpponent = true;
                    Thread.sleep(500);
                }
                myWaitingForOpponent = false;
    
                if (order == 1) {
                    myPlayer1 = new OwnerPlayer(dukeSprite, dukeSpriteAnimator, myGameInfo);
                    myPlayer2 = new WebPlayer(jamesSprite, jamesSpriteAnimator, myGameInfo,
                            getMobileClient(), id);
                } else {
                    myPlayer1 = new WebPlayer(dukeSprite, dukeSpriteAnimator, myGameInfo,
                            getMobileClient(), id);
                    myPlayer2 = new OwnerPlayer(jamesSprite, jamesSpriteAnimator, myGameInfo);
                }
            } catch (RemoteException ex) {
                myCanvas.errorMsg(ex);
            } catch (InterruptedException ex) {
                myCanvas.errorMsg(ex);
            }
    //#else
    //#         // init player 1
    //#         myPlayer1 = new OwnerPlayer(dukeSprite, dukeSpriteAnimator, myGameInfo);
    //#         // init player 2
    //#         myPlayer2 = new PhonePlayer(jamesSprite, jamesSpriteAnimator, myGameInfo);
    //#endif
                                    

    The initPlayers method should now look as follows:

    Please note the following conditional attributes in the pasted code:

    • If the

      ONLINE ability exists and it's value equals true, the first part will be used.
      In this part the Player is registered in the service using the getMobileClient().initPlayer("") method.
      The game is then started with the getMobileClient().startGame(id) invoked in case there is no opponent.

      Typically it is better to initialize the game in a separate thread to avoid conflict with the game UI. But in order to simplify this exercise and reduce the amount of code in the lab this proceedure has been skipped.

      After the opponent appears and the game is initialized the Players are connected to Sprites depending on the playing order chosen.

    • Notice that that code in the else clause is the same as it was before.
      If the game application is not online this part of the code will be compiled and used. This means that you must Fix Imports using the contextual menu for this use case.

Step 6: Run The Game

  1. You can now run the project with two "remote" players.

    Right-click the MobileGame project and choose Run from the contextual menu. Repeat this action to launch a second instance of the game. Two emulators should have started.

    You can play for both players by switching between the emulators

The solution for this exercise is provided as a "ready to build and run" NetBeans project, <lab_root>/solutions/exercise5/MobileGame_solution5.

Troubleshoting tips

The project with the webservice already configured is in the <lab_root>/solutions/exercise5/ directory. The name of the pre-configured project is BrickGameWebApplication.

Congratulations! You have successfully completed LAB-5502: Your First Mobile Game Hands-on lab.

Where to send questions or feedbacks on this lab and public discussion forums: