MobileJava MEDeveloping Java-Based Mobile Games

Developing Java-Based Mobile Games

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Editor’s Note: To understand this article, some Java programming experience is necessary. GUI development experience with AWT and SWING will be helpful though not mandatory.

In recent times, mobile games have gained popularity for providing personal entertainment on the go. This popularity has mobile gaming playing a pivotal role in revenue generation for the cellular carriers, game publishers, and handset makers, while generating numerous opportunities for game developers and associated professionals. With the number of mobile gamers around the world expected to reach 220 million by 2009, the mobile gaming business is projected to expand to higher levels and constitute a bigger portion of the profit pie for the cellular carriers and handset makers.

Mobile games can be classified into three broad categories:

  • Embedded games: Games that are hardcoded into the mobile handset’s system and shipped with it. Soon to be outdated/obsolete. Example: Snake, shipped with all Nokia phones.
  • SMS games: Games played by sending text messages—for example, SMS to game server—that process them and sends back the result through SMS. Often in the form of live contests and polls. Not very popular because the cost of gaming increases with each SMS sent to the game server.
  • Browser games: These games are played using mobile phone’s built-in microbrowser (net browser for mobile devices), either in online or offline mode. Players can play such games online through their cellular carrier’s or a third-party game provider’s game Web site, or download them for offline gaming. This category includes a wide range of games, such as solo or multiplayer games, network games, offline games, arcade games, and so forth

Among these three categories, browser games are today’s most popular type of mobile games for their innovative and multimedia-rich content, appealing presentation, and lower cost of gaming compared to SMS games. This article discusses the development of browsing games and henceforth, the term “mobile games” will refer to “browser games” in this article.

Note: This article concentrates on 2D games. Because a large number of mobile phones in circulation today have very limited resources (small screen, limited memory and graphics support, cumbersome key input), the most suitable as well as commercially feasible games for these devices are 2D games. But, as capabilities of mobile phones are bound to increase over time, 3D games will become commonplace in the near future.

Mobile games can be developed using C++, Java (Java 2 Micro Edition, to be precise), and the Binary Runtime Environment for Wireless (BREW) platform from Qualcomm.

Why Choose Java for Mobile Game Development?

Although C++ has the advantage of being compiled into native code with direct access to system resources, and with BREW the platform provides end-to-end solutions to mobile game developers while allowing them to work with any desired language (including C++, Java, XML, and Flash), Java is the most popular choice for game development. Java, or the Java 2 Micro Edition (J2ME) platform to be precise, is identified as the most convenient for developing mobile games. (For more specifics on J2ME, see “What is Java 2 Micro Edition?“) The driving forces behind J2ME’s popularity are:

  • J2ME enjoys the status of an industry standard backed by all major handset makers, with most of the present day mobile phones being Java-enabled.
  • J2ME is a free and open platform. This helps keep the development costs low and provides the necessary flexibility with ample support freely available for developers using it.
  • Its highly portable nature (“Write once run anywhere”) ensures that a game application written for one brand/type of handset will work with all other brands/types of Java-enabled handsets.
  • It is especially optimized for small devices, is lightweight, and is highly secure because applications written on it cannot access or affect other applications running on the phone/device.
  • J2ME consists of the Mobile Information Device Profile (MIDP) API that is designed specifically for developing applications for mobile devices including mobile phones, keeping in mind their limitations and constraints. Furthermore, the latest MIDP version 2.0 itself dedicates a whole API to game development, making game development simpler and quicker.

Now, you will explore MIDP 2.0 the in context of mobile gaming.

The Role of MIDP 2.0 in Game Development

MIDP 2.0 API is a set of feature-loaded APIs used for developing secure, rich-content multimedia applications, including games, for mobile devices. MIDP 2.0 builds upon its predecessor MIDP 1.0 to provide a better development platform for building efficient and fast mobile applications. For more information on MIDP 2.0, see the Resources section at the end of this article.

MIDP 2.0 further refines the features and functionalities provided by MIDP 1.0. For information on the new features, see What’s New in MIDP 2.0. One of the important additions made to MIDP is the Game API, or the javax.microedition.lcdui.game API package to be precise. Through the Game API, MIDP 2.0 provides game developers with the readymade building blocks that were to be developed from scratch in the case of MIDP 1.0. These building blocks are classes for creating and controlling various game elements such as game canvas, sprites, layers, and so forth (these are explained in the next section). Thus, MIDP 2.0 significantly reduces the time involved in game development.

The other two MIDP 2.0 API packages essential for game development, also explored by this article, are javax.microedition.midlet and javax.microedition.lcdui.

The javax.microedition.midlet API package provides a base for developing all mobile applications. It contains the javax.microedition.midlet.MIDlet class, which is the base class of all J2ME-based mobile applications (also known as midlets) and must be extended by the main classes of all mobile applications. Quite similar to the java.applet.Applet class, the MIDlet class provides resources necessary to create midlets.

The javax.microedition.lcdui API package is necessary to develop a user interface (UI) for all types of mobile applications. This API provides classes to create and control UI components (such as screen, form, text box, radio buttons, and so on) and processing input for mobile applications, including games. Developers who have GUI development experience with AWT and SWING will find that the elements of the javax.microedition.lcdui package are similar to elements from these APIs.

I’ll discuss the elements of these APIs relevant to game development as upi encounter them during the development of the example game app.

Building the Example Game

To understand the APIs and their respective classes better, you’ll start developing a simple mobile game. This will be a solo player offline game, a car moving through an obstacle course. The player uses the left and right handset keys to “steer” the running car to the left or right to keep it from colliding into an obstacle. The game is over when a collision happens and the score is displayed. I’ll call it HardDrive.

Note: The example game is developed using the J2ME Wireless Toolkit 2.1_01 and J2SE 1.4.2_07 SDK on a Windows 2000 platform. Other versions of both the Wireless Toolkit and J2SE SDK that are compatible with various platforms are also available.

Begin building the game app by putting together the source code; call it HardDrive. From what you’ve explored in the previous section, the first thing you need develop is the HardDriveMIDlet (HardDriveMIDlet.java) that extends the javax.microedition.midlet.MIDlet class.

HardDriveMIDlet.java (Download)

Listing 1.1: Code snippet from HardDriveMIDlet.java

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;

public class HardDriveMIDlet extends MIDlet implements CommandListener {
... ... ... ... ... ... ... ...

HardDriveMIDlet also implements the javax.microedition.lcdui.CommandListener Interface to receive command events generated during application execution and process them. The command events occur when commands such as EXIT, CANCEL, BACK, OK, STOP, and the like are issued by using soft buttons (special buttons near the mobile phone’s screen, other than arrow keys) and are handled by the commandAction( ) method of the HardDriveMIDlet. To be effective, a command should be added to a canvas.

HardDriveMIDlet serves as a container for all canvases, which are objects representing surface available for drawing on mobile device screen. Here, the midlet contains HardDriveCanvas, which extends the javax.microedition.lcdui.game.GameCanvas class. The GameCanvas is a special canvas meant for drawing efficient animated graphics for the game app, and is also capable of querying key status off-screen graphics buffering for smooth animation.

Another canvas that HardDriveMIDlet contains is GameOverCanvas, which extends the javax.microedition.lcdui.Canvas class. Canvas is a simple canvas meant for drawing text, lines, and simple shapes. The canvas is extended when simple drawing on the screen is required, instead of heavy graphics; for example, to display splash screens, game over screens, and game instructions. A game app’s midlet may contain any number of canvases, but only one canvas is displayed at a time by using the setCurrent() method of the javax.microedition.lcdui.Display class.

HardDriveMIDlet also contains three other important methods, also called lifecycle methods. They are startApp(), pauseApp(), and destroyApp( ), corresponding to the Active, Paused, and Destroyed states of the midlet. In the startApp( ) method of HardDriveMIDlet, HardDriveCanvas is instantiated and the EXIT command is added to it by using the addCommand( ) method of HardDriveCanvas.

HardDriveCanvas.java (Download)

HardDriveCanvas implements a java.lang.Runnable interface to enable itself to run in its own thread, which is necessary to independently execute the game loop. The game loop is executed continuously to run the game until conditions necessary to stop the game become true (in this example, when the car collides with an obstacle or when the player exits the game anytime by using the Exit button).

Listing 1.2: Game loop of HardDriveCanvas.java

public void start()
   {
      gameRunning = true;
      Thread gameThread = new Thread(this);
      gameThread.start();
   }
... ... ... ...
... ... ... ...
public void run() 
   {
      Graphics g = getGraphics();
      //... ... ...some code
      while (gameRunning)    //The game loop
      {
         tick();
         input();
         render(g);

         //... ... ...some code

         try
         {
            Thread.sleep(timeStep );
            //... ... ... ...some code 
         }
            catch (InterruptedException ie) { stop(); }

      }

Listing 1.2 shows the game loop of HardDriveCanvas.java. This is a typical game loop that consists of calls to the following methods in a given order: tick( ), input( ), and render( ). The tick( ) method checks whether conditions necessary to stop the game have become true and changes the game state accordingly if so. Method input( ) handles game key (keys assigned for game playing) inputs and performs necessary actions for each key press, such as a game element’s movement. The rendering of the game according to its state is handled by the render( ) method.

HardDriveCanvas also uses an instance of javax.microedition.lcdui.game.LayerManager that adds and manages multiple layers of the HardDriveCanvas, each layer representing a sprite. A sprite is a basic visual element of a game, a character that moves around on a game canvas and interacts with other sprites (here, the car or obstacles are sprites that may collide with each other). Each sprite forms a virtual layer, which may be fully or partially transparent, laid on the game canvas; these layers are stacked upon one another. A sprite is an object of the javax.microedition.lcdui.game.Sprite class, which provides the functionality of displaying, transforming, and rotating the sprite along with collision detection for the sprite. The tick( ) method internally uses the collidesWith( ) method of the sprite class to check the collision.

HardDriveCanvas instantiates an object of the ObstacleManager class that renders and moves obstacle sprites on the game canvas and checks whether they’ve collided with the car sprite.

ObstacleManager.java (Download)

An ObstacleManager creates and manages obstacles that appear randomly in the car’s path. For the sake of simplicity and convenience, ObstacleManager.java has hardcoded values of a maximum number of obstacles appearing at a time in car’s path. This value may be modified as desired.

Listing 1.3: Code snippet from ObstacleManager.java

private static final int MAX_OBS = 10;
//... ...some code

To create and display obstacles at random positions, ObstacleManager employs a simple strategy. It creates the initial batch of 10 obstacle sprites and uses LayerManager to add these sprites to the game canvas. Then, it sets their position by using randomly generated values of x and y coordinates and starts moving them towards the bottom of game canvas. As soon as each of these obstacles reaches the bottom of the canvas without colliding with the car, its position is again reset by using the same technique while the game score is increased by one. Thus, ObstacleManager re-uses the same obstacle sprites and displays them randomly.

GameOverCanvas.java (Download)

GameOverCanvas is a simple canvas that receives the game duration and game score information from HardDriveMIDlet and displays it.

Readying the Example Game for Distribution

J2ME Wireless Toolkit provides KToolbar, a useful tool for compiling, preverifying, packaging, and testing a mobile application. KToolbar simplifies and automates most of these tasks.

Now that the game code is ready, it needs to be organized in the following directory structure, provided by KToolbar (see KToolbar’s User Guide for “Operating with KToolbar”). To achieve this, start KToolbar and create a new project, HardDriveGame, that will contain the HardDrive game app under the apps folder inside J2ME Wireless Toolkit’s installation folder.

HardDriveGame   (game project name, user-defined)
|___src
|
|___bin
|
|___classes
|
|___res
|
|___lib
|
|___tmpclasses
|
|___tmplib

Now, simply copy all four source files of the game app into the src folder and the car.png and obstacle.png icon files in the res folder. KToolbar takes care of everything else.

Now, the following actions will open the corresponding HardDriveGame game project, build it to compile (by using the JDK compiler), and preverify the game application.

Open project button -> choose HardDriveGame -> Build button

If some errors occur during the build process, they are displayed in the KToolbar window. Modify the game source code in the src folder to correct them; debugging has to be done manually because KToolbar does not provide a debugging facility. Otherwise, if no errors occur, a “Build complete” message is displayed in the KToolbar window.

Once the game project is built successfully, it could be run in the Emulator (a KToolbar component that virtually simulates the execution of the application on mobile phones) to test the application.

The game app is now complete and ready to be distributed. To package the game app into a .jar file for distribution using KToolbar, the following actions are to be performed.

Open project button -> choose HardDriveGame -> Project menu -> Package -> Create package / Create obfuscated package

The Create Package menu option will create a standard .jar file, whereas Create Obfuscated Package creates a .jar file of a smaller size than a standard .jar file. Once packaging is complete, the location of the .jar file is displayed in the KToolbar window, along with a .jad (Java Application Descriptor) file created automatically during packaging and used by Emulator while running the game app.

Emulator running example game app

Figure 1.1: Emulator running the example game app

Optionally, the game app’s midlet is signed after packaging by using following actions:

Project menu -> Sign

This creates a digital signature for the .jar file, and adds it to the .jad file.

Now, the game app’s .jar and .jad files, along with the MANIFEST.MF manifest file, created by KToolbar and grouped together as a midlet suite, are ready to be distributed.

This is how 2D mobile games are developed using Java. You can model your own games on the example given in this article.

Conclusion

Mobile game development has become a lucrative industry with a manifold increase in mobile subscriptions and the number of avid mobile gamers around the world. J2ME and MIDP 2.0 help game developers tap the potential of this industry by providing a platform for developing mobile game conveniently, quickly, and efficiently. MIDP 2.0 dedicates a whole API package for game development that provides readymade building blocks to simplify and quicken mobile game development.

Resources

Download the complete source code of the example game app.

Related Articles

BREW

The home page of the BREW platform at Qualcomm’s Web site.

Toolkits and SDKs

Although J2ME base games can run on all types of handsets, one also can use tools and SDKs (that are again built upon J2ME) provided by handset makers such as Nokia, Siemens, Sony Ericsson, Motorola, and so forth to tap the handset-specific resources and capabilities, and develop games optimized for specific handsets.

3D mobile games

About the Author

Mugdha Chauhan is a senior IT consultant and author. Major tech portals including developer.com, IBM developerWorks, CNET Networks, Slashdot, and many eZines regularly publish her work. Her expertise and interests include Java, Linux, XML, and Open Source, along with Wireless application development.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories