# Lab-5502: Your First Mobile Game

Expected Duration: 100 minutes
Contacts: Andrey Korostelev and Ivan Sidorkin

Introduction | Exercise 0 | Exercise 1 | Exercise 2 | Exercise 3 | Exercise 4 | Exercise 5 | Summary
2. Introduction Steps to Follow Summary ## 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. Choose `File > Open Project` and the filechooser dialog appears. Select the `MobileGame` project in the `<lab_root>/exercises/exercise4/`. The opened project appears in Projects tab of the IDE. Note: two new packages are inside the opened project: `logic` - Contains classes that manage the game workflow `BricksGameCanvas` - GameCanvas extension that will be displayed on the device screen. `BricksLayerManager` - Manages the interaction between the sprites and tiled layers. `GameInfo` - Current Game session information available for players. `GameThread` - Main game thread runs in a separate thread to avoid interfering with the game's UI. `logic.players` - Classes for the player interface and it's implementations. `Player` - Basic player interface. `OwnPlayer` - Human Player implementation. `PhonePlayer` - Player implementation managed by Phone's processing power. 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. 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. 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. 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 Drag-n-drop `BrickGameCanvas` from the Palette to the flow view of the VisualMIDlet. The `BricksGameCanvas` has only a constructor with the parameter `VisualMIDlet`:
           public BricksGameCanvas(VisualMIDlet midlet)
2. 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. 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. 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 Open `game.VisualMIDlet.java` in the editor if it is not opened yet. Switch to the Visual Designer's Source view Add a new attribute named `GameThread` to the `VisualMIDlet` class:
           private GameThread myGameThread; //[ex4]
4. The source code in the editor should now look similar to the following: Go back to `Flow` view and right-click the `svgButton` in the `svgform` and choose Go To Source from the contextual menu. 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]
5. Paste the code snippet and replace the following comment: `//Some action after switch` after `switchDisplayable` method invocation. The result looks like the following: 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]
           }
1. Fix Imports to correct any errors. For example: Use Fix Imports from the right-click contextual menu to make these types of corrections. 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`. 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);
2. 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. If you closed `BricksLayerManager` already, we need to open it again. 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: Now Fix Imports and Save the changes. Step 7: Play the Game It's time to test your game. 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. Click the Launch button to run the `VisualMIDlet` selected on the screen. 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. 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 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`. Back to top Next exercise