Home arrow Java arrow Page 6 - Storing and Retrieving Data
JAVA

Storing and Retrieving Data


Storing bytes of data locally on a device equipped for the Mobile Internet Device Profile (MIDP) is easy. MIDP allows you to store arrays of bytes. But what if the data you need to store isn't in the form of bytes? And how can you make the data small enough so that storing it on a device with a relatively small amount of memory is not a problem? That's where this article comes in. It is excerpted from the book J2ME Games with MIDP2, written by Carol Hamer (Apress, 2004; ISBN: 1590593820).

Author Info:
By: Apress Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 24
May 12, 2005
TABLE OF CONTENTS:
  1. · Storing and Retrieving Data
  2. · Serializing More Complex Data Using Streams
  3. · Using Data Types and Byte Arithmetic
  4. · Applying Data Storage to a Game
  5. · Converting an array of bytes into a dungeon
  6. · Creating the Complete Example Game
  7. · DungeonManager.java
  8. · Doors and keys

print this article
SEARCH DEVARTICLES

Storing and Retrieving Data - Creating the Complete Example Game
(Page 6 of 8 )

All the classes youíve seen to encode and store data arenít much use without a game to go with them. This section shows you the code for the fun part of the game. Iíve discussed all the programming ideas used in this game in previous chapters, so Iím leaving the explanation for the comments.

Listing 5-7 shows the code for the MIDlet subclass Dungeon.java.

Listing 5-7. Dungeon.java

  package net.frog_parrot.dungeon;
 
import javax.microedition.midlet.*;
  import javax.microedition.lcdui.*;
 
/**
   
* This is the main class of the dungeon game.
    *
   
* @author Carol Hamer
   
*/
  public class Dungeon extends MIDlet implements CommandListener {
  //----------------------------------------------------
  //
game object fields
 
/**
   
* The canvas that the dungeon is drawn on.
   
*/
  private DungeonCanvas myCanvas;
 
/**
   
* the thread that advances the game clock.
   
*/
  private GameThread myGameThread;
 
//----------------------------------------------------
  // command fields
  /**
   
* The button to exit the game.
    */
  private Command myExitCommand = new Command("Exit", Command.EXIT, 99);
  /**
   
* The command to save the game in progress.
   
*/
  private Command mySaveCommand
    = new Command("Save Game", Command.SCREEN, 2);
  /**
   
* The command to restore apreviously saved game.
    */
 
private Command myRestoreCommand
    = new Command("Restore Game", Command.SCREEN, 2);
  /**
   
* the command to start moving when the game is paused.
   
*/
  private Command myGoCommand = new Command("Go", Command.SCREEN, 1);
 
/**
   
* the command to pause the game.
   
*/
  private Command myPauseCommand = new Command("Pause", Command.SCREEN, 1);
 
/**
   
* the command to start a new game.
   
*/
  private Command myNewCommand = new Command("Next Board", Command.SCREEN, 1);
 
//----------------------------------------------------
  // initialization and game state changes
  /**
    * Initialize the canvas and the commands.
    */
  public Dungeon() {
   
try {
      // create the canvas and set up the commands: 
      myCanvas = new DungeonCanvas(this); 
      myCanvas.addCommand(myExitCommand); 
      myCanvas.addCommand(mySaveCommand);
      myCanvas.addCommand(myRestoreCommand);
      myCanvas.addCommand(myPauseCommand);
      myCanvas.setCommandListener(this);
   
} catch(Exception e) {
      // if there's an error during creation, display it as an alert.
      errorMsg(e);
    }
  }
  /**
   
* Switch the command to the play again command.
   
* (removing other commands that are no longer relevant)
    */
  void setNewCommand() {
    myCanvas.removeCommand(myPauseCommand); 
    myCanvas.removeCommand(myGoCommand);
    myCanvas.addCommand(myNewCommand);
  }
 
/**
   
* Switch the command to the go command.
      * (removing other commands that are no longer relevant)
    */
  void setGoCommand() {
    myCanvas.removeCommand(myPauseCommand); 
    myCanvas.removeCommand(myNewCommand);
    myCanvas.addCommand(myGoCommand);
 
}
 
/**
   
* Switch the command to the pause command.
   
* (removing other commands that are no longer relevant)
    */
 
void setPauseCommand() {
    myCanvas.removeCommand(myNewCommand);
    myCanvas.removeCommand(myGoCommand);
    myCanvas.addCommand(myPauseCommand);
 
}
 
//-------------------------------------------------------  // implementation of MIDlet
  // these methods may be called by the application management
  // software at any time, so you always check fields for null
  // before calling methods on them.
 
/**
    * Start the application.
    */
  public void startApp() throws MIDletStateChangeException {
    if(myCanvas != null) {
     
if(myGameThread == null) {
        // create the thread and start the game: 
        myGameThread = new GameThread(myCanvas);
        myCanvas.start();
        myGameThread.start();
     
} else {
        // in case this gets called again after
        // the application has been started once: 
        myCanvas.removeCommand(myGoCommand);
        myCanvas.addCommand(myPauseCommand);
        myCanvas.flushKeys();
        myGameThread.resumeGame();
      }
    }
  }
 
/**
   
* Stop the threads and throw out the garbage.
    */
  public void destroyApp(boolean unconditional)
     
throws MIDletStateChangeException {
    myCanvas = null;
    if(myGameThread != null) {
     
myGameThread.requestStop();
    }
    myGameThread = null;
    System.gc();
 
}
 
/**
   
* Pause the game.
    */
  public void pauseApp() {
    if(myCanvas != null) {
     
setGoCommand();
    }
    if(myGameThread != null) {
     
myGameThread.pause();
    }
  }
  //-------------------------------------------------------  // implementation of CommandListener
 
/*
    * Respond to a command issued on the Canvas.
    * (reset, exit, or change size prefs).
    */ 
  public void commandAction(Command c, Displayable s) {
    try {
      //myCanvas.setNeedsRepaint();
      if(c == myGoCommand) {
       
myCanvas.setNeedsRepaint();
        myCanvas.removeCommand(myGoCommand); 
        myCanvas.addCommand(myPauseCommand);
        myCanvas.flushKeys();
        myGameThread.resumeGame();
      } else if(c == myPauseCommand) { 
        {myCanvas.setNeedsRepaint();
        myCanvas.removeCommand(myPauseCommand);
        myCanvas.addCommand(myGoCommand);
        myGameThread.pause();
     
} else if(c == myNewCommand) {  
        myCanvas.setNeedsRepaint();
        // go to the next board and restart the game
        myCanvas.removeCommand(myNewCommand);
        myCanvas.addCommand(myPauseCommand);
        myCanvas.reset();
        myGameThread.resumeGame();
     
} else if(c == Alert.DISMISS_COMMAND) {
        // if there was a serious enough error to
        // cause an alert, then we end the game
        // when the user is done reading the alert:
        // (Alert.DISMISS_COMMAND is the default
        // command that is placed on an Alert
        // whose timeout is FOREVER)
        destroyApp(false);
        notifyDestroyed();
     
} else if(c == mySaveCommand) {  
        myCanvas.setNeedsRepaint();
        myCanvas.saveGame();
     
} else if(c == myRestoreCommand) {
        myCanvas.setNeedsRepaint();
        myCanvas.removeCommand(myNewCommand);
        myCanvas.removeCommand(myGoCommand);
        myCanvas.addCommand(myPauseCommand);
        myCanvas.revertToSaved();
     
} else if(c == myExitCommand) {
        destroyApp(false);
        notifyDestroyed();
     
}
      } catch(Exception e) {
        errorMsg(e);
      }
    }
 
//------------------------------------------------------
  // error methods
 
/**
   
* Converts an exception to amessage and displays
   
* the message.
    */
  void errorMsg(Exception e) {
    if(e.getMessage() == null) {
      errorMsg(e.getClass().getName());
  } else {
    errorMsg(e.getClass().getName() + ":" + e.getMessage());
 
}
}
  /**
    * Displays an error message alert if something goes wrong.
    */
  void errorMsg(String msg) {
    Alert errorAlert = new Alert("error",
                            
msg, null, AlertType.ERROR); 
    errorAlert.setCommandListener(this);
    errorAlert.setTimeout(Alert.FOREVER);
    Display.getDisplay(this).setCurrent(errorAlert);
 
}

}

Listing 5-8 shows the code for  the GameCanvas subclass DungeonCanvas.java.

Listing 5-8. DungeonCanvas.java

  package net.frog_parrot.dungeon;
  import javax.microedition.lcdui.*;
  import javax.microedition.lcdui.game.*;
  /**
    * This class is the display of the game.
    *
    * @author Carol Hamer
    */
  public class DungeonCanvas extends GameCanvas {
  //-------------------------------------------------------  // dimension fields
  // (constant after initialization)
  /**
    * the height of the black region below the play area.
    */
    static int TIMER_HEIGHT = 32;
  /**
    * the top-corner X coordinate according to this
    * object's coordinate system:
    */
  static final int CORNER_X = 0;
  /**
    * the top-corner Y coordinate according to this
    * object's coordinate system:
    */
  static final int CORNER_Y = 0;
  /**
    * the width of the portion of the screen that this
    * canvas can use.
    */
  static int DISP_WIDTH;
  /**
    * the height of the portion of the screen that this
    * canvas can use.
    */
  static int DISP_HEIGHT;
  /**
    * the height of the font used for this game.
    */
  static int FONT_HEIGHT;
  /**
    * the font used for this game.
    */
  static Font FONT;
  /**
    * color constant
    */
  public static final int BLACK = 0;
  /**
    * color constant
    */
  public static final int WHITE = 0xffffff;
  //-------------------------------------------------------  // game object fields
  /**
    * ahandle to the display.
    */
  private Display myDisplay;
  /**
    * a handle to the MIDlet object (to keep track of buttons).
    */
  private Dungeon myDungeon;
  /**
    * the LayerManager that handles the game graphics.
    */
  private DungeonManager myManager;
  /**
    * whether the game has ended.
    */
  private static boolean myGameOver;
  /**
    * The number of ticks on the clock the last time the
    * time display was updated.
    * This is saved to determine if the time string needs
    * to be recomputed.

   
*/
  private int myOldGameTicks = 0;
  /**
   
* the number of game ticks that have passed since the
   
* beginning of the game.
   
*/
  private int myGameTicks = myOldGameTicks;
 
/**
   
* you save the time string to avoid re-creating it
   
* unnecessarily.
   
*/
  private static String myInitialString = "0:00";
 
/**
   
* you save the time string to avoid re-creating it
   
* unnecessarily.
    */
  private String myTimeString = myInitialString;
 
//----------------------------------------------------
  // gets/sets
 
/**
   
* This is called when the game ends.
    */
  
void setGameOver() {
    myGameOver = true;
    myDungeon.pauseApp();
  }
 
/**
   
* Find out if the game has ended.
    */
  static boolean getGameOver() {
    return(myGameOver);
  }
 
/**
   
* Tell the layer manager that it needs to repaint.
    */
  public void setNeedsRepaint() {
   
myManager.setNeedsRepaint();
  }
  //----------------------------------------------------
  //   initialization and game state changes
 
/**
   
* Constructor sets the data, performs dimension calculations,
   
* and creates the graphical objects.
    */
 
public DungeonCanvas(Dungeon midlet) throws Exception {
    super(false);
    myDisplay = Display.getDisplay(midlet);
    myDungeon = midlet;
    // calculate the dimensions
    DISP_WIDTH = getWidth();
    DISP_HEIGHT = getHeight();
    if((!myDisplay.isColor()) || (myDisplay.numColors() < 256)) {
     
throw(new Exception("game requires full-color screen"));
    }
    if((DISP_WIDTH < 150) || (DISP_HEIGHT < 170)) {
     
throw(new Exception("Screen too small"));
    }
    if((DISP_WIDTH > 250) || (DISP_HEIGHT > 250)) {
     
throw(new Exception("Screen too large"));
    }
    // since the time is painted in white on black,
    // it shows up better if the font is bold:
    FONT = Font.getFont(Font.FACE_SYSTEM,
                    Font.STYLE_BOLD, Font.SIZE_MEDIUM);
    // calculate the height of the black region that the
    // timer is painted on:
    FONT_HEIGHT = FONT.getHeight();
    TIMER_HEIGHT = FONT_HEIGHT + 8;
    // create the LayerManager (where all the interesting
    // graphics go!) and give it the dimensions of the
    // region it is supposed to paint:
    if(myManager == null) {
     
myManager = new DungeonManager(CORNER_X, CORNER_Y,  
          DISP_WIDTH, DISP_HEIGHT - TIMER_HEIGHT, this);
    }
  }
  /**
   
* This is called as soon as the application begins.
    */
    void start() {
    myGameOver = false;
    myDisplay.setCurrent(this);
    setNeedsRepaint();
  }
 
/**
   
* sets all variables back to their initial positions.
    */
 
void reset() throws Exception {
    // most of the variables that need to be reset
    // are held by the LayerManager:
    myManager.reset();
    myGameOver = false;
    setNeedsRepaint();
  }
  /**
    * sets all variables back to the positions
    * from apreviously saved game.
    */ 
  void revertToSaved() throws Exception {
    // most of the variables that need to be reset
    // are held by the LayerManager, so we
    // prompt the LayerManager to get the
    // saved data:
    myGameTicks = myManager.revertToSaved();
    myGameOver = false;
    myOldGameTicks = myGameTicks;
    myTimeString = formatTime();
    setNeedsRepaint();
  }
  /**
    * save the current game in progress.
    */
    void saveGame() throws Exception {
      myManager.saveGame(myGameTicks);
  }
  /**
    * clears the key states.
    */
    void flushKeys() {
      getKeyStates();
  }
  /**
    * If the game is hidden by another app (or amenu)
    * ignore it since not much happens in this game
    * when the user is not actively interacting with it.
    * (you could pause the timer, but it's not important
      * enough to bother with when the user is just pulling
    * up amenu for a few seconds)
    */
  protected void hideNotify() {
  }
  /**
    * When it comes back into view, just make sure the
    * manager knows that it needs to repaint.
    */
  protected void showNotify() {
    setNeedsRepaint();
  }
  //------------------------------------------------------  // graphics methods
  /**
    * paint the game graphics on the screen.
    */
  public void paint(Graphics g) {
    // color the bottom segment of the screen black 
    g.setColor(BLACK);
    g.fillRect(CORNER_X, CORNER_Y + DISP_HEIGHT - TIMER_HEIGHT,
               DISP_WIDTH, TIMER_HEIGHT);
    // paint the LayerManager (which paints
    // all the interesting graphics):
    try {
      myManager.paint(g);
    } catch(Exception e) {
      myDungeon.errorMsg(e);
    }
    // draw the time
    g.setColor(WHITE);
    g.setFont(FONT);
    g.drawString("Time: " + formatTime(), DISP_WIDTH/2,
          CORNER_Y + DISP_HEIGHT - 4, g.BOTTOM|g.HCENTER);
    // write "Dungeon Completed" when the user finishes a board:
    if(myGameOver) {

      
myDungeon.setNewCommand();
      // clear the top region:
      g.setColor(WHITE);
      g.fillRect(CORNER_X, CORNER_Y, DISP_WIDTH, FONT_HEIGHT*2 + 1);
      int goWidth = FONT.stringWidth("Dungeon Completed");
      g.setColor(BLACK);
      g.setFont(FONT);
      g.drawString("Dungeon Completed", (DISP_WIDTH - goWidth)/2,
                    CORNER_Y + FONT_HEIGHT, g.TOP|g.LEFT);
    }
  }
 
/**
   
* asimple utility to make the number of ticks look like a time...
    */
  public String formatTime() {
   
if((myGameTicks / 16) != myOldGameTicks) {
    myTimeString = "";
    myOldGameTicks = (myGameTicks / 16) + 1;
    int smallPart = myOldGameTicks % 60;
    int bigPart = myOldGameTicks / 60;
    myTimeString += bigPart + ":";
    if(smallPart / 10 < 1) {
     
myTimeString += "0";
    }
    myTimeString += smallPart;
 
}
  return(myTimeString);
}
  //------------------------------------------------------  // game movements
 
/**
   
* update the display.
    */
 
void updateScreen() {
    myGameTicks++;
    // paint the display
   
try {
      paint(getGraphics());
      flushGraphics(CORNER_X, CORNER_Y, DISP_WIDTH, DISP_HEIGHT);
   
} catch(Exception e) {
      myDungeon.errorMsg(e);
    }
  }
  /**
    * Respond to keystrokes.
    *
   public void checkKeys() {
    if(! myGameOver) {
      int vertical = 0;
      int horizontal = 0;
      // determine which moves the user would like to make:
      int keyState = getKeyStates();
      if((keyState & LEFT_PRESSED) != 0) {
        horizontal = -1;
      }
      if((keyState & RIGHT_PRESSED) != 0) {
        horizontal = 1;
      }
      if((keyState & UP_PRESSED) != 0) {
        vertical = -1;
      }
      if((keyState & DOWN_PRESSED) != 0) {
        // if the user presses the down key,
        // we put down or pick up a key object
        // or pick up the crown:
        myManager.putDownPickUp();
      }
      // tell the manager to move the player
      // accordingly if possible:
      myManager.requestMove(horizontal, vertical);
    }
  }

}


blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials