Click here to Skip to main content
15,880,469 members
Articles / Programming Languages / Java / Java SE / J2EE

Programming 2D Games in J2ME

Rate me:
Please Sign up or sign in to vote.
4.86/5 (17 votes)
23 Apr 2009CPOL6 min read 245.4K   17.1K   63   54
It is easy to run your own game on your own mobile

GameProgrammingInJ2ME/game_screen.jpg

Introduction

J2ME is an interesting environment for games. With basic knowledge of Java, preinstalled NetBeans and J2ME Wireless Toolkit, you can make simple, funny 2D games that are capable of running on your own mobile devices.

This article will make use of the 5-class Game API composed in the package javax.microedition.lcdui.game.

Background

This thread assumes that you have basic knowledge of Java, are familiar with NetBeans and have gone through the thread “Introduction to Java ME Programming”. Game making also requires certain knowledge of physics including Newton’s Law of motion, Motions, collisions, …etc.

Recently, I attended a project named Mobile Application Development Intensive Programs organized by my University and its alliances. The project is financed by Uramus, a program to encourage student exchange between European countries. We started with J2ME and it is the result of this thread. So, in this thread, I will use some of the material taken from the project.

By using the GameBuilder, the game making process is much easier. However, I’m not going to cover it in this thread. Details of game making by using GameBuilder can be found here.

As a student, I probably do not have enough experience to apply the best practice. That's why I warmly welcome any comments or suggestions to make it a better guide.

Using the Code

The MainMidlet

As a Midlet, the MainMidlet must extend the abstract class Midlet that can be found in the package javax.microedition.midlet. The Midlet requires override of three methods:

  • startApp() called to start the game
  • pauseApp() called to temporarily stop the application, i.e., receiving a call. Application should stop the animation and release resources that are not needed. Application can be resumed by calling resumeMIDlet()
  • destroyApp(boolean unconditional) called when exiting the application. In order to terminate, the MIDlet can call notifyDestroyed()

(These methods are automatically created by creating a Visual Midlet in NetBeans.)

We are, however, only needed to implement the startApp() methods by creating an instance of our GameCanvas and adding a CommandListener to exit the Midlet. It is, of course, not a good programming habit but until this step, we probably only want the application to run. Current display can be set to the GameCanvas at the end or inside the GameCanvas by the method setCurrent. This method accepts any Displayable objects as an argument.

Java
public class MainMidlet extends MIDlet implements CommandListener {
    private SSGameCanvas gameCanvas ;
    private Command exitCommand ;
    public void startApp() {
        try {
           //create new game thread
            gameCanvas = new SSGameCanvas();
            gameCanvas.start(); // start game thread
            exitCommand = new Command("Exit",Command.EXIT,1);
            gameCanvas.addCommand(exitCommand);
            gameCanvas.setCommandListener(this);
            Display.getDisplay(this).setCurrent(gameCanvas);
        }
        catch (java.io.IOException e) { e.printStackTrace();}
    }
Java
public void pauseApp() {} 
Java
public void destroyApp(boolean unconditional) {}
Java
public void commandAction(Command command, Displayable displayable) {
        if (command == exitCommand) { 
            destroyApp(true); 
            notifyDestroyed();
        } 
    } 
}

The GameCanvas

As an element of low level UI engine, when combined with Graphics, GameCanvas provides us flexible tools to set up our own game screen. With Graphics, you basically can draw things that you can normally do in Java 2D, including drawing shapes, strings or images. GameCanvas is an extension to the original Canvas with more control over the painting, and the rate at which keys are delivered into the game.

Using GameCanvas, you can notice its capabilities including the off-screen buffering. When you are drawing things, you probably are drawing into the off-screen and by calling the flushGraphics() method, the buffer is quickly written into the screen.

GameCanvas also simplifies the process of getting input by allowing us to query the key status using the getKeyState() method. Processing key status, however, is left to the GameManager for easier management.

The origin of the game coordinate system is located in the top left corner of the screen as shown.

GameProgrammingInJ2ME/gamescreen.jpg

In the render method, the off-screen is cleared and graphics are rendered by calling paint method of the GameManager.

Java
public void render(Graphics g) {

        ……..
       // Clear the Canvas.
        g.setColor(0, 0, 50);
        g.fillRect(0,0,WIDTH-1,HEIGHT-1);
        ….….
        gameManager.paint(g);
    }

In this example, the SSGameCanvas implements Runnable interface, which leads to the creation of the run() methods in which we create a game loop running until we reach certain ending condition.

GameProgrammingInJ2ME/game_states.jpg

Game Loops

Java
public void run() {


      while (running) {
          // draw graphics
          render(getGraphics());
          // advance to the next tick
          advance(tick++);
          // display
          flushGraphics();
          try { Thread.sleep(mDelay); }
          catch (InterruptedException ie) {}
      }
  }

Timing of the game is controlled by an integer named tick. tick simplifies timer problem in the game, such as firing rate of a ship, or how long a star will flash, how long a sprite will step into the next frame. If timing is done in the GameCanvas by implementing Runnable, a tick means mDelay + time to complete one game cycle (milliseconds). If we create a Thread which takes care of tick, we will probably have tick = mDelay. We will probably need only 24 -30 fps, so we limit the mDelay accordingly to have the desired animation effect with less power consumption. At every cycle of the game, we call the method advance of the GameManager, which extends LayerManager to check the user input, collisions and paint the graphics.

Java
public void advance(int ticks) {
       // advance to next game canvas
        gameManager.advance(ticks);
        this.paint(getGraphics());
    }
}

tick may have a limitation: it limits the game playing time by the limit of the integer, which is about over 590 hours in a 32-bit system.

Sprite

Sprite acts as the actors of the games. It could be our Mario characters, ducks, and bullets in the Mario games or space ships in a star war game. As a basic visual element, it can be rendered to display continuous action with several frames stored in an Image. The Image file must pack all the frames of the Sprite in order to be displayed. All frames must have the same and predefined width and height.

Java
public SpaceShip(Image image, int w, int h) throws java.io.IOException {
       super(image,w ,h);
        WIDTH = w;
        HEIGHT= h;
        setFrameSequence(SEQUENCE);
        defineReferencePixel(WIDTH/2,HEIGHT/2);
        setTransform(this.TRANS_MIRROR_ROT270);
    }

Image 4

To initiate the Ship sprite, I call the constructor from the superclass Sprite: super(image, w, h); where w and h is the width and height of each frame. The image consists of 8 frames, so I set the frame sequence {0,1,2,3,4,5,6,7} using setFrameSequence method.

Next, I call the defineReferencePixel method to set the reference point to the middle of the frame. This reference pixel will be used to position the ship on the screen. And finally, I rotate all the frames by the method setTransform.

Java
public void advance(int ticks) {
        if ((ticks%RATE==0))
            nextFrame();
    }

The method advance will change the frame of the ship to create animation accordingly to RATE. By continuously calling nextFrame(), the screen will display the frame sequence from 0 to 8 and then come back to 0: 0,1,2…7,0,1,2…. The following methods moveLeft(), moveRight(), moveUp(), moveDown() to change the position of the ship on the screen depends on its speedX and speedY.

Java
public void moveLeft () {
       if (this.getRefPixelX()>0)
            this.move(-speedX, 0);
    }
Java
public void moveRight (int m) {
        if (this.getRefPixelX() < m)
            this.move(speedX, 0);
    }
Java
public void moveUp () {
        if (this.getRefPixelY()>0)
            this.move(0, -speedY);
    } 
Java
public void moveDown (int m) {
        if (this.getRefPixelY()<m)
            this.move(0, speedY);
    }

When the ship is commanded to shoot a bullet, we check whether the cool down is gone or not by comparing current time with the previous shot time.

Java
public Bullet fire (int ticks) {
        if (ticks- fireTick > SHOOT_RATE) {
           fireTick = ticks;
           bullet.setSpeed(BULLET_SPEED);
           bullet.shot(this.getRefPixelX(), this.getRefPixelY()+HEIGHT/2);
            return bullet;
        }
        else
           return null;
   }

To check the collision between the spites, images or TitledLayer (will be mentioned later), we use the method collidesWith. I will make use of this method in the GameManager to check the collision between the ship and the asteroids to reduce HP of the ship and to check collision between the bullet and the asteroids to increase score and destroy both the bullet and the asteroid.

GameManager

As a subclass of LayerManager , the GameManager is capable of managing series of Layers, automatically renders each Layer in an appropriate order. Method append is called to add a specific Layer to the LayerManager.

Java
private Image shipImage;
    private static final String SHIP_IMAGE    = "/resource/blue_ship.png";
    private static final int    SHIP_WIDTH    = 40;
    private static final int    SHIP_HEIGHT   = 33;
Java
shipImage = Image.createImage( SHIP_IMAGE );
        // create space ship
        ship = new SpaceShip(shipImage, SHIP_WIDTH, SHIP_HEIGHT);
        // set it position
       ship.setRefPixelPosition(height/2, width/2);
        this.append(ship);

In order to respond to the user input, we query the key states with a referenced instance of our GameCanvas using the method getKeyStates(). For each key state, we react correspondingly by moving the ship to the desired direction.

Java
int keyState = gameCanvas.getKeyStates();
 
// move right
if ((keyState & GameCanvas.RIGHT_PRESSED)!= 0){
       ship.moveRight(width);
} 

// move left
if ((keyState & GameCanvas.LEFT_PRESSED)!= 0){
       ship.moveLeft();
}

// move up
if ((keyState & GameCanvas.UP_PRESSED) != 0){
        ship.moveUp();
} 

// move down
if ((keyState & GameCanvas.DOWN_PRESSED) != 0){
        ship.moveDown(height);
}

In the GameManager, we also check for collision between the ship, bullet and random created enemy (asteroids). If collision occurred, we change the game status accordingly to the collision.

Java
private Obstacle checkCollisionWithAsteroids(Sprite t) {

        for (int i =0; i < MAX_OBS;i++) {
            if (obs[i]!=null)
                 if (obs[i].collidesWith(t, true)) {
                 return obs[i];
            }
        }
        return null;
    }

In case we reach the game ending condition, we display high score and stop the GameCanvas Thread using the method stop:

Java
protected void endGame(Graphics g) {
        GameOver=true;
        gameCanvas.stop();
        Font f = g.getFont();
        int h = f.getHeight()+40;
        int w = f.stringWidth("High score")+40;       
        g.setColor(250,250,250);
        g.drawString("Score " + score,(width-w)/2,(height-h)/2,g.TOP | g.LEFT);
}

Points of Interest

With the given knowledge, I believe that you can create simple games like: go fishing, frog crossing the road. I will cover TitledLayer, sound in the next updated of the post. They will surely increase the look and the feeling of the game.

GameProgrammingInJ2ME/fishing.jpg

GameProgrammingInJ2ME/frog.jpg

History

  • 23rd April, 2009: Published

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Other
Finland Finland
Programming languages: Java, C/C++, Objective-C, Assembly, Action script , PHP, Visual basic.

Second year student

Comments and Discussions

 
QuestionError in theGameManager.java Pin
suman259212-Jul-14 1:49
suman259212-Jul-14 1:49 
Questiongames Pin
Member 107949094-May-14 20:33
Member 107949094-May-14 20:33 
Questionbullet passes through the asteroid Pin
Member 1004315210-May-13 23:57
Member 1004315210-May-13 23:57 
QuestionWhat kind of j2me game is yours? Pin
supernorb29-Sep-12 11:26
supernorb29-Sep-12 11:26 
QuestionNeed help to run it Pin
Mac_xxx4-Aug-12 2:01
Mac_xxx4-Aug-12 2:01 
AnswerRe: Need help to run it Pin
hoangtuanbs6-Aug-12 0:18
hoangtuanbs6-Aug-12 0:18 
QuestionBullet is not colliding with asteroid Pin
Ashz0077-Jul-12 10:19
Ashz0077-Jul-12 10:19 
Questioncollision and score is not increasing Pin
hoaanhdao31127-May-12 16:51
hoaanhdao31127-May-12 16:51 
SQL
while running the program, not a collision between bullets and asteroids, the score does not increase.
Can you explain this case?

AnswerRe: collision and score is not increasing Pin
hoangtuanbs27-May-12 18:37
hoangtuanbs27-May-12 18:37 
GeneralRe: collision and score is not increasing Pin
hoaanhdao31128-May-12 6:12
hoaanhdao31128-May-12 6:12 
QuestionRe: collision and score is not increasing Pin
hoaanhdao31128-May-12 16:54
hoaanhdao31128-May-12 16:54 
AnswerRe: collision and score is not increasing Pin
hoangtuanbs6-Aug-12 0:18
hoangtuanbs6-Aug-12 0:18 
QuestionHỏi Pin
hoaanhdao31126-May-12 17:15
hoaanhdao31126-May-12 17:15 
AnswerRe: Hỏi Pin
supernorb29-Sep-12 11:28
supernorb29-Sep-12 11:28 
QuestionRun in NetBean 7.01 :Platform home (platform.home property) is not set. Value of this property should be Sun Java(TM) Wireless Toolkit 2.5.2 for CLDC emulator home directory location Pin
qhai9-Sep-11 4:18
qhai9-Sep-11 4:18 
AnswerRe: Run in NetBean 7.01 :Platform home (platform.home property) is not set. Value of this property should be Sun Java(TM) Wireless Toolkit 2.5.2 for CLDC emulator home directory location Pin
hoangtuanbs6-Aug-12 0:20
hoangtuanbs6-Aug-12 0:20 
Questionplease... Pin
wawarock13-Apr-11 0:29
wawarock13-Apr-11 0:29 
AnswerRe: please... Pin
hoangtuanbs6-Aug-12 0:20
hoangtuanbs6-Aug-12 0:20 
Generalgive me suggestion Pin
abbie329020-Jan-11 1:23
abbie329020-Jan-11 1:23 
GeneralRe: give me suggestion Pin
hoangtuanbs20-Jan-11 5:32
hoangtuanbs20-Jan-11 5:32 
GeneralRe: give me suggestion Pin
abbie329020-Jan-11 7:26
abbie329020-Jan-11 7:26 
Generalcollision and score is not increasing Pin
vimalsudhan9-Nov-10 3:09
vimalsudhan9-Nov-10 3:09 
GeneralRe: collision and score is not increasing Pin
hoangtuanbs9-Nov-10 7:04
hoangtuanbs9-Nov-10 7:04 
Generalj2me game Pin
sinha9916-Oct-10 22:55
sinha9916-Oct-10 22:55 
GeneralException error. Pin
mport949116-Oct-10 1:37
mport949116-Oct-10 1:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.