Home E-Books J2ME Game Development: Issues and Troubleshooting Methods used in the Canvas class

J2ME Game Development: Issues and Troubleshooting.(TM) - Methods used in the Canvas class

by Massimo Perrone (Hanami Solutions)

3.5 Methods used in the Canvas class

This too is simple from the logical point of view, it results being the implementation of the Canvas class.

Indeed at his heart logical will be similar to what we will plot on screen.

Usually in an arcade game structure to be implemented turns out to be more or less always the same, that is:

  • resources loading;
  • logo appears on screen;
  • main menu appears on screen;
  • main game loop (start, pause, characters interaction, animations, etc.);
  • end game;
  • All we've listed above can be quietly inserted in the aforementioned run() method and be sketched at code level in the following way:

    public void run() 
    if(logo==null) loadResources();
    else if(displayLogo) displayLogo();
    else if (pause) MyMIDlet.pauseApp();
    else if game();
    catch(Exception e)
    System.out.println("\n\nerror running MIDlet!!!\n");

    As you can see, the logic of our flow chart matches that of the code.

    Some further details: usage of Thread.sleep(20) method is useful to show, on our device, 50 frames per second but this is often not necessary, to the opposite, most times it ends up being counterproductive and one will need to take longer or shorter pauses between a frame and another to better sync animations in the game.

    You may notice that some checks are performed on some flags and according to the positive or negative results of these tests a method or another is executed. While for the first, concerning resource loading, we use a picture to perform the test and more in detail if "logo" is equal to "null" or not (so we check if the logo picture, last of the row, has been loaded) in all other cases we check a boolean variable to know whether to perform or not its related procedure. It will be then our task to set, each time, the correct variable to either "true" or "false" to execute a method rather than another one.

    Please notice that a link exists between main MIDlet and Canvas and thus how it is possible to launch a method belonging to the main class of Canvas by mean of, e.g.: MyMIDlet.pauseApp().

    This way, despite the code part handling the pause function stays whithin the main MIDlet, i can handle its logic from Canvas with no problem. But how can we phisically link MIDlet to Canvas? Very easily.

    It will be enough to insert an object GameMIDlet in the main class:

          GameMIDlet MyMIDlet;
    	and then link it by mean of the Canvas constructor:
    public GameCanvas(GameMIDlet mainClass)

    and the link is done.

    Please bear in mind that by mean of the repaint() and serviceRepaints() methods every 20 milliseconds there is a screen update so remember to keep the image to be plot on screen ready in the paint() method.

    Next Page >>