27
BRIEF INTRODUCTION TO MIDP GRAPHICS Version 1.0 18 Nov 02

Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

  • Upload
    others

  • View
    7

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

BRIEF INTRODUCTION TO MIDP GRAPHICS

Version 1.0 18 Nov 02

Page 2: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

Table of Contents

1. INTRODUCTION ....................................................................................................................................................................4 1.1 PURPOSE .......................................................................................................................................................................................................4 1.2 REFERENCES ..................................................................................................................................................................................................4

2. MIDLET GRAPHICS...............................................................................................................................................................5 2.1 MIDLET GRAPHICS OVERVIEW......................................................................................................................................................................5 2.2 MIDLET SCREEN ...........................................................................................................................................................................................6 2.3 MIDP USER INTERFACE API ........................................................................................................................................................................8

3. AN EXAMPLE: TICTACTOEMIDLET.....................................................................................................................................9 3.1 DESIGN..........................................................................................................................................................................................................9

3.1.1 Overview ...............................................................................................................................................................................................9 3.1.2 TicTacToeMIDlet............................................................................................................................................................................... 10

3.2 TICTACTOEMIDLET.JAVA............................................................................................................................................................................ 12 3.3 CHOOSEPIECESCREEN.JAVA ....................................................................................................................................................................... 13 3.4 GAMESCREEN.JAVA.................................................................................................................................................................................... 15 3.5 GAME.JAVA ................................................................................................................................................................................................ 23 3.6 TICTACTOE.JAD........................................................................................................................................................................................... 27

Change history

13 Mar 02 Version 0.9.3 Document published in Forum Nokia.

18 Nov 02 Version 1.0 Document updated.

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

2

Page 3: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

Disclaimer:

The information in this document is provided ”as is,” with no warranties whatsoever, including any warranty of merchantability, fitness for any particular purpose, or any warranty otherwise arising out of any proposal, specification, or sample. This document is provided for informational purposes only.

Nokia Corporation disclaims all liability, including liability for infringement of any proprietary rights, relating to implementation of information presented in this document. Nokia Corporation does not warrant or represent that such use will not infringe such rights.

Nokia Corporation retains the right to make changes to this specification at any time, without notice.

The phone UI images shown in this document are for illustrative purposes and do not represent any real device.

Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.

Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc.

Other product and company names mentioned herein may be trademarks or trade names of their respective owners.

License:

A license is hereby granted to download and print a copy of this specification for personal use only. No other license to any other intellectual property rights is granted herein.

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

3

Page 4: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

1. INTRODUCTION

1.1 Purpose

The J2METM Mobile Information Device Profile (MIDP) and Connected Limited Device Configuration (CLDC) are defined in [MIDPSPEC] and [CLDCSPEC]. These specs define the foundation for writing MIDP applications, which are called MIDlets.

The following document briefly introduces MIDlet graphics programming through a simple example MIDlet application. It assumes that you are familiar with Java programming, as well as the basics of MIDP programming, for instance by having read the Forum Nokia paper Brief Introduction to MIDP Programming [MIDPPROG].

After reading this paper, you will have a better understanding of how to make graphical user interfaces for MIDP applications, including:

• how to use the high-level and low-level MIDP user interface APIs (see Section 2.2)

• how to adapt user interfaces to different device characteristics (see Section 2.2)

1.2 References

MIDPSPEC Mobile Information Device (JSR-37), JSR Specification, Java 2 Platform, Micro Edition, 1.0a, 15 Dec 2000, http://java.sun.com/products/midp/

CLDCSPEC Connected, Limited Device Configuration (JSR-30), JSR Specification, Java 2 Platform, Micro Edition, Version 1.0, 19 May 2000, http://java.sun.com/products/cldc/

MIDPPROG Brief Introduction to MIDP Programming Forum Nokia, 2001 http://www.forum.nokia.com

TICTACTOE1 Scott Violet, TicTacToe revisited, March 2001, http://java.sun.com/products/jfc/tsc/articles/tictactoe/index.html

TICTACTOE2 TicTacToe JDK1.0 demo applet, 1995, http://java.sun.com/applets/jdk/1.0/demo/TicTacToe/TicTacToe.java

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

4

Page 5: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

2. MIDLET GRAPHICS

2.1 MIDlet Graphics Overview

The Mobile Information Device Specification (MIDP) [MIDPSPEC] defines an API for applications called MIDlets, that run in suitable MIDP containers. This API is itself built on top of the CLDC API [CLDCSPEC]. The design of the MIDP user interface API classes is not based on those of the Java Abstract Window Toolkit (AWT). Instead they are specifically designed for use on small mobile information devices such as cell phones and pagers, which have limited screen and keyboard capabilities. A programmer may only use the MIDP or CLDC APIs when writing graphical applications with MIDP.

The basic abstraction of the MIDP user interface is a screen. The Screen class encapsulates device-specific graphics and user interactions. Only one screen is displayed at a time, and only items on that screen can be viewed or used. Figure 2.1 shows a few examples of screen-based MIDP Graphical Users Interfaces (GUIs).

Figure 2.1: Screen-based MIDP GUI

The MIDP API has both high-level and low-level UI classes. The high-level user interface classes (e.g., Form, List, TextBox, TextField, Alert, and Ticker) are adapted to the device: supporting images, text, text entry fields, radio buttons, etc. The low-level user interface (class Canvas) allows one to draw whatever one likes. MIDlets may run in mobile phones with color, greyscale, or black-and-white screens of varying sizes. The high-level classes are abstractions of common UI elements whose use is intended to improve the portability of MIDlets across different device implementations, and that may utilize the native device’s look and feel. The low-level API enables more direct control of what is displayed, but the MIDlet designer should ensure portability across a wide range of devices (display size, keyboard, color, etc.). This example presents use of both high-level and low-level APIs.

All MIDP GUI classes are part of the javax.microedition.lcdui package.

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

5

Page 6: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

2.2 MIDlet Screen

MIDP has two main types of screens:

• High-level screens

o This includes simple high-level screens such as classes List and TextBox. The user cannot add additional GUI components to this type of screen. The TicTacToe MIDlet example uses a screen derived from class List called ChoosePieceScreen for selection of the player’s game piece when the game begins.

o A generic Form screen is similar to a List, but allows additional graphical elements to be used, e.g., images, read-only text fields, editable text fields, editable date fields, gauges, and choice groups. Form items can be added or deleted on the fly. Class Form is not used in the TicTacToe example.

• Low-level screen

o The Canvas screen (and Graphics plus Image classes) may be used to write UIs based on the low-level API. These classes give the MIDlet programmer the most drawing flexibility. The programmer may draw a variety of graphics elements, e.g., lines, arcs, rectangles, rounded rectangles, circles, text (of various colors, fonts, and sizes), clip bitmap images, etc. Most game MIDlets will be written using canvas-based screens as the main GUI elements.

A MIDlet user interface usually contains one or more screens. Since only one screen can be seen at a time, it is essential for the MIDlet to have a well-defined architecture so that context switches between screens can be handled easily.

The following code snippets illustrate one approach to switching screens in a MIDlet, based on screen classes and appropriate MIDlet callbacks.

Class MyMIDlet extends MIDlet { private FirstScreen firstScreen; private SecondScreen secondScreen; public MyMIDlet() { … } public void startApp() { Displayable current = Display.getDisplay(this).getCurrent(); if (current == null) { firstScreen = new FirstScreen(this, …); Display.getDisplay(this).setCurrent(firstScreen); // Display the application’s first UI screen } else

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

6

Page 7: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

{ Display.getDisplay(this).setCurrent(current); } } // FirstScreen callback switches to next screen public void firstScreenDone() { … secondScreen = new SecondScreen(this, …); display.getDisplay(this).setCurrent(secondScreen); } // This SecondScreen callback ends the application public void secondScreenQuit() { … destroyApp(false); notifyDestroyed(); } … }

Figure 2.2: Example of a main MIDlet class

The MIDlet uses two screens (FirstScreen and SecondScreen) for the user interface. When MIDlet execution begins, it sets the currently displayed screen to be the FirstScreen. When it needs to switch to SecondScreen from FirstScreen, FirstScreen calls the parent MIDlet’s method firstScreenDone (Figure 2.3). The method firstScreenDone creates and sets SecondScreen to be the current display screen.

Class FirstScreen extends Form implements CommandListener { private MyMIDlet midlet; public FirstScreen(MyMIDlet midlet) { this.midlet = midlet; … } public void commandAction(Command c) { if (c == cmdQuit) { parent.firstScreenDone(); } …

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

7

}

Page 8: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

… }

Figure 2.3: Example of FirstScreen including its MIDlet call-back

2.3 MIDP User Interface API

It is the responsibility of the MIDP device to ensure portability and adaptation of UI objects based on high-level API classes.

On the other hand, low-level classes like Canvas and Graphics provide more freedom for programmers to control the UI’s visual appearance, and to listen for low-level keyboard events. The programmer is also responsible for guaranteeing the portability across MID devices with different characteristics (e.g., display sizes, color vs. black and white, and different keyboard types). For instance, it may be necessary to use the getWidth() and getHeight() methods to adapt the UI’s appearance to the available Canvas dimensions of one or more devices.

The TicTacToe MIDlet example in the next chapter will demonstrate:

• Simple usage of high-level API;

• Use of the low-level API to draw graphics elements such as line, arc, string, and image;

• Some aspects of MIDlet portability across MID devices with different display size;

• Mapping of key codes to game actions.

This section presented a brief overview of MIDP GUI design. For more detailed information, please see [MIDPSPEC].

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

8

Page 9: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

3. AN EXAMPLE: TICTACTOEMIDLET

3.1 Design

3.1.1 Overview

The example application is a simple MIDlet that allows a human player to play the game called Tic Tac Toe against the MIDlet. The example illustrates:

• Use of high-level and low-level user interface components

• Switching between multiple display screens

• Simple command handling

• Dynamic adaptation to display size

• Keyboard event handling

The user first selects which piece (circle or cross) to use. Then the game play begins. A random selection is made as to whether the MIDlet or human player makes the first move of the game. After each move, the game status is checked to see if the game has ended. Possible game outcomes are as follows: the human player wins, the MIDlet player wins, or a stalemate (neither wins). The tally of both sides during the current application session is shown. The user may play a new game or quit at any time.

The screen shots in Figure 3.1 show the MIDlet’s UI during game play.

Figure 3.1: Sequence of game screens

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

9

Page 10: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

3.1.2 TicTacToeMIDlet

Here is a class diagram for the TicTacToeMIDlet:

ChoosePieceScreen GameScreen

Game

creates callsback creates callsback

uses

TicTacToeMIDlet

Figure 3.2: TicTacToeMIDlet class diagram

When the MIDlet starts in method startApp(), the splash screen and first game screen (ChoosePieceScreen) are created. The splash screen is displayed for four seconds and then the first game screen is displayed. The ChoosePieceScreen allows the human player to choose which piece (circle or cross) they will play with. When the player has made his/her piece selection, he/she uses the OK command. This causes a callback from the ChoosePieceScreen to the main MIDlet’s choicePieceScreenDone() method.

The ChoosePieceScreen is implemented using the high-level API List class.

Figure 3.3: The ChoosePieceScreen is a high-level UI List subclass

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

10

Page 11: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

The choosePieceScreenDone() callback creates and displays the next screen, which is the main screen (GameScreen) for game play in this application.

Each time it is the player’s turn, the player uses the arrow keys of the GameScreen and the Select button to choose the empty square the player wishes to occupy. After each turn, the game status is checked for any end-of-game conditions, which are displayed. The user terminates the game by pushing the Quit command of the GameScreen, or plays again using the New command. The Quit command causes a callback to the quit() method of TicTacToeMIDlet. The MIDlet then calls lifecycle method destroyApp() to terminate the entire MIDlet.

The game logic is encapsulated in a separate class Game. This document is only concerned with MIDlet Graphics design, so the game logic is not explained further. For comparisons with existing applet Java™ programming, the game logic is based on a game presented in [TICTACTOE1] [TICTACTOE2].

The GameScreen is implemented using the low-level Canvas and Graphics classes. It illustrates drawing using Canvas, Image, and Graphics objects.

The GameScreen first initializes the displayed board based on the available canvas dimensions. This allows the MIDlet to run on MIDs with different display. An Image object was used to represent the board in this example application. The GameScreen next assigns circle and cross pieces to the human player and the MIDlet, based on the player’s preference specified from ChoosePieceScreen. The game is then initialized (which includes randomly deciding which player starts), and the game begins.

In order for GameScreen to be portable, MIDlet key codes must also be mapped to game actions such as: Up, Down, Left, Right, and Fire for use on MIDs with different keyboards. Whenever a key is pressed, the keyPressed() method will judge if it is a direction key or a Fire/Select key. If the depressed key is a direction key, a focus cursor will be moved accordingly to aid the player in visually selecting a square to occupy with his/her piece. The Select key is used to select a square to be occupied. When an end-of-game condition is detected, an appropriate message describing the game’s winner and the total score of the games played so far is displayed to the human player.

Figure 3.4: GameScreen is a low-level Canvas subclass

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

11

Page 12: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

3.2 TicTacToeMIDlet.java

The TicTacToeMIDlet is very simple: it handles MIDlet lifecycle events. It creates the screen objects as needed and handles callbacks from screens. The choosePieceScreenDone callback is used to create the GameScreen. The quit method is used by GameScreen to end the game.

package example.tictactoe; import java.io.IOException; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; public class TicTacToeMIDlet extends MIDlet { private ChoosePieceScreen choosePieceScreen; private GameScreen gameScreen; public TicTacToeMIDlet() { } public void startApp() { Displayable current = Display.getDisplay(this).getCurrent(); if (current == null) { // first time we've been called // Get the logo image Image logo = null; try { logo = Image.createImage("/tictactoe.png"); } catch (IOException e) { // just use null image }

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

12

Alert splashScreen = new Alert(null, "Tic-Tac-Toe\nForum Nokia", logo, AlertType.INFO);

Page 13: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

splashScreen.setTimeout(4000); // 4 seconds choosePieceScreen = new ChoosePieceScreen(this); Display.getDisplay(this).setCurrent(splashScreen, choosePieceScreen); } else { Display.getDisplay(this).setCurrent(current); } } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void quit() { destroyApp(false); notifyDestroyed(); } public void choosePieceScreenDone(boolean isPlayerCircle) { gameScreen = new GameScreen(this, isPlayerCircle); Display.getDisplay(this).setCurrent(gameScreen); } }

3.3 ChoosePieceScreen.java

ChoosePieceScreen is a high-level API Form-based screen that allows the user to select a circle or cross playing piece. It uses the MIDlet callback method choosePieceScreenDone to indicate the user’s selection when he or she pushes the OK button.

package example.tictactoe; import javax.microedition.midlet.*; import javax.microedition.lcdui.*;

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

13

Page 14: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

import javax.microedition.io.*; public class ChoosePieceScreen extends List implements CommandListener { private static final String CIRCLE_TEXT = "Circle"; private static final String CROSS_TEXT = "Cross"; private final TicTacToeMIDlet midlet; private final Command quitCommand; public ChoosePieceScreen(TicTacToeMIDlet midlet) { super("Choose your piece", List.IMPLICIT); this.midlet = midlet; append(CIRCLE_TEXT, loadImage("/circle.png")); append(CROSS_TEXT, loadImage("/cross.png")); quitCommand = new Command("Quit", Command.EXIT, 2); addCommand(quitCommand); setCommandListener(this); } public void commandAction(Command c, Displayable d) { boolean isPlayerCircle = getString(getSelectedIndex()).equals(CIRCLE_TEXT); if (c == List.SELECT_COMMAND) { midlet.choosePieceScreenDone(isPlayerCircle); } else // quitCommand { midlet.quit(); } } private Image loadImage(String imageFile) { Image image = null; try

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

14

Page 15: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

{ image = Image.createImage(imageFile); } catch (Exception e) { // Use a 'null' image in the choice list (i.e. text only choices). } return image; } }

3.4 GameScreen.java

GameScreen uses a low-level API Canvas screen, and the Image and Graphics classes to draw the game board, pieces, and final status message of the game. For more details, see the paint methods and methods drawCircle, drawCross, drawPiece, drawPlayerCursor, and drawBoard. The screen uses the MIDlet callback quit to indicate that the game is over.

The screen adapts to the available display capabilities (height, width, color, etc.). Also note that the cursor movement can be done using four-way or two-way navigation keys.

It uses the class Game, which encapsulates the main game logic.

package example.tictactoe; import java.util.Random; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; class GameScreen extends Canvas implements CommandListener { private static final int BLACK = 0x00000000; private static final int WHITE = 0x00FFFFFF; private static final int RED = 0x00FF0000; private static final int BLUE = 0x000000FF; private static final int NO_MOVE = -1; private final TicTacToeMIDlet midlet; private final Game game; private final Command exitCommand; private final Command newGameCommand; private final Random random = new Random(); private int screenWidth, screenHeight;

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

15

Page 16: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

private int boardCellSize, boardSize, boardTop, boardLeft; private boolean playerIsCircle; private boolean computerIsCircle; private int preCursorPosition, cursorPosition; private int computerMove = NO_MOVE; private int playerMove = NO_MOVE; private int computerGamesWonTally = 0; private int playerGamesWonTally = 0; private boolean isRestart; public GameScreen(TicTacToeMIDlet midlet, boolean playerIsCircle) { this.midlet = midlet; this.playerIsCircle = playerIsCircle; computerIsCircle = !playerIsCircle; game = new Game(random); initializeBoard(); // configure Screen commands exitCommand = new Command("Exit", Command.EXIT, 1); newGameCommand = new Command("New", Command.SCREEN, 2); addCommand(exitCommand); addCommand(newGameCommand); setCommandListener(this); // begin the game play initialize(); } // Initialize the Game and Game screen. Also used for game restarts. private void initialize() { game.initialize(); preCursorPosition = cursorPosition = 0; playerMove = NO_MOVE; boolean computerFirst = ((random.nextInt() & 1) == 0); if (computerFirst) { computerMove = game.makeComputerMove(); } else

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

16

Page 17: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

{ computerMove = NO_MOVE; } isRestart = true; repaint(); } public void paint(Graphics g) { if (game.isGameOver()) { paintGameOver(g); } else { paintGame(g); } } private void paintGame(Graphics g) { if (isRestart) { // clean the canvas g.setColor(WHITE); g.fillRect(0, 0, screenWidth, screenHeight); drawBoard(g); isRestart = false; } drawCursor(g); if (playerMove != NO_MOVE) { drawPiece(g, playerIsCircle, playerMove); } if (computerMove != NO_MOVE) { drawPiece(g, computerIsCircle, computerMove); } } private void paintGameOver(Graphics g)

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

17

Page 18: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

{ String statusMsg = null; if(game.isComputerWinner()) { statusMsg = "I win !"; computerGamesWonTally++; } else if (game.isPlayerWinner()) { statusMsg = "You win"; playerGamesWonTally++; } else { statusMsg = "Stalemate"; } String tallyMsg = "You:" + playerGamesWonTally + " Me:" + computerGamesWonTally; Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM); int strHeight = font.getHeight(); int statusMsgWidth = font.stringWidth(statusMsg); int tallyMsgWidth = font.stringWidth(tallyMsg); int strWidth = tallyMsgWidth; if (statusMsgWidth > tallyMsgWidth) { strWidth = statusMsgWidth; } // Get the {x, y} position for painting the strings. int x = (screenWidth - strWidth) / 2; x = x < 0 ? 0 : x; int y = (screenHeight - 2 * strHeight) / 2; y = y < 0 ? 0 : y; // clean the canvas g.setColor(WHITE); g.fillRect(0, 0, screenWidth, screenHeight); // paint the strings' text g.setColor(BLACK); g.drawString(statusMsg, x, y, (Graphics.TOP | Graphics.LEFT)); g.drawString(tallyMsg, x, (y + 1 + strHeight), (Graphics.TOP | Graphics.LEFT)); }

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

18

Page 19: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

public void commandAction(Command c, Displayable d) { if (c == exitCommand) { midlet.quit(); } else if (c == newGameCommand) { initialize(); } } private void initializeBoard() { screenWidth = getWidth(); screenHeight = getHeight(); if (screenWidth > screenHeight) { boardCellSize = (screenHeight - 2) / 3; boardLeft = (screenWidth - (boardCellSize * 3)) / 2; boardTop = 1; } else { boardCellSize = (screenWidth - 2) / 3; boardLeft = 1; boardTop = (screenHeight - boardCellSize * 3) / 2; } } protected void keyPressed(int keyCode) { // can't continue playing until the player restarts if (game.isGameOver()) { return; } int gameAction = getGameAction(keyCode); switch (gameAction) { case FIRE: doPlayerMove();

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

19

Page 20: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

break; case RIGHT: doMoveCursor(1, 0); break; case DOWN: doMoveCursor(0, 1); break; case LEFT: doMoveCursor(-1, 0); break; case UP: doMoveCursor(0, -1); break; default: break; } } private void doPlayerMove() { if (game.isFree(cursorPosition)) { // player move game.makePlayerMove(cursorPosition); playerMove = cursorPosition; // computer move if (!game.isGameOver()) { computerMove = game.makeComputerMove(); } repaint(); } } private void doMoveCursor(int dx, int dy) { int newCursorPosition = cursorPosition + dx + 3 * dy; if ((newCursorPosition >= 0) && (newCursorPosition < 9))

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

20

Page 21: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

{ preCursorPosition = cursorPosition; cursorPosition = newCursorPosition; repaint(); } } // Draw a CIRCLE or CROSS piece on the board private void drawPiece(Graphics g, boolean isCircle, int pos) { int x = ((pos % 3) * boardCellSize) + 3; int y = ((pos / 3) * boardCellSize) + 3; if (isCircle) { drawCircle(g, x, y); } else { drawCross(g, x, y); } } // Draw blue CIRCLE onto the board image private void drawCircle(Graphics g, int x, int y) { g.setColor(BLUE); g.fillArc(x + boardLeft, y + boardTop, boardCellSize - 4, boardCellSize - 4, 0, 360); g.setColor(WHITE); g.fillArc(x + 4 + boardLeft, y + 4 + boardTop, boardCellSize - 4 - 8, boardCellSize - 4 - 8, 0, 360); } // Draw red CROSS onto the board image private void drawCross(Graphics g, int x, int y) { g.setColor(RED); for (int i = 0; i < 4; i++) { g.drawLine(x + 1 + i + boardLeft, y + boardTop, x + boardCellSize - 4 - 4 + i + boardLeft, y + boardCellSize - 5 + boardTop);

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

21

Page 22: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

g.drawLine(x + 1 + i + boardLeft, y + boardCellSize - 5 + boardTop, x + boardCellSize - 4 - 4 + i + boardLeft, y + boardTop); } } // Visually indicates a Player selected square on the board image private void drawCursor(Graphics g) { // draw cursor at selected Player square. g.setColor(WHITE); g.drawRect(((preCursorPosition % 3) * boardCellSize) + 2 + boardLeft, ((preCursorPosition/3) * boardCellSize) + 2 + boardTop, boardCellSize - 3, boardCellSize - 3); // draw cursor at selected Player square. g.setColor(BLACK); g.drawRect(((cursorPosition % 3) * boardCellSize) + 2 + boardLeft, ((cursorPosition/3) * boardCellSize) + 2 + boardTop, boardCellSize - 3, boardCellSize - 3); } private void drawBoard(Graphics g) { // clean the board g.setColor(WHITE); g.fillRect(0, 0, screenWidth, screenHeight); // draw the board g.setColor(BLACK); for (int i = 0; i < 4; i++) { g.fillRect(boardLeft, boardCellSize * i + boardTop, (boardCellSize * 3) + 2, 2); g.fillRect(boardCellSize * i + boardLeft, boardTop, 2, boardCellSize * 3); } } }

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

22

Page 23: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

3.5 Game.java

This class encapsulates the main game logic for the game of Tic Tac Toe. The game’s logic itself is not a significant aspect of this example, as it instead concentrates on presenting the basics of MIDP graphics programming. The game logic’s WINS array is partially derived by modifying a well-known example available from [TICTACTOE2].

Note that the game logic is independent from the game’s UI presentation (see class GameScreen) and could be replaced with an alternative implementation.

package example.tictactoe; import java.util.Random; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; // The game logic for TicTacToe class Game { private static final int[] WINS = { // horizontals bit(0) | bit(1) | bit(2), bit(3) | bit(4) | bit(5), bit(6) | bit(7) | bit(8), // verticals bit(0) | bit(3) | bit(6), bit(1) | bit(4) | bit(7), bit(2) | bit(5) | bit(8), // diagonals bit(0) | bit(4) | bit(8), bit(2) | bit(4) | bit(6) }; private static final int DRAWN_GAME = bit(0) | bit(1) | bit(2) | bit(3) | bit(4) | bit(5) | bit(6) | bit(7) | bit(8); private int playerState; private int computerState; private Random random; Game(Random random) { this.random = random;

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

23

initialize();

Page 24: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

} void initialize() { playerState = 0; computerState = 0; } boolean isFree(int position) { int bit = bit(position); return (((playerState & bit) == 0) && ((computerState & bit) == 0)); } // The 'Contract' is that caller will always make valid moves. // We don't check that it's the player's turn. void makePlayerMove(int position) { playerState |= bit(position); } // The 'Contract' is that we will be called only when there is still // at least one free square. int makeComputerMove() { int move = getWinningComputerMove(); if (move == -1) { // can't win move = getRequiredBlockingComputerMove(); if (move == -1) { // don't need to block move = getRandomComputerMove(); } } computerState |= bit(move); return move; }

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

24

Page 25: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

boolean isGameOver() { return isPlayerWinner() | isComputerWinner() | isGameDrawn(); } boolean isPlayerWinner() { return isWin(playerState); } boolean isComputerWinner() { return isWin(computerState); } boolean isGameDrawn() { return (playerState | computerState) == DRAWN_GAME; }

// Return a winning move if there is at least one, otherwise return -1

private int getWinningComputerMove() { int move = -1; for (int i = 0; i < 9; ++i) { if (isFree(i) && isWin(computerState | bit(i))) { move = i; break; } } return move; } // Return a required blocking move if there is at least one (more // than one and we've inevitably lost), otherwise return -1 private int getRequiredBlockingComputerMove() { int move = -1; for (int i = 0; i < 9; ++i) {

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

25

Page 26: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

if (isFree(i) && isWin(playerState | bit(i))) { move = i; break; } } return move; } // Return a random move in a free square, // or return -1 if none are available private int getRandomComputerMove() { int move = -1; // determine how many possible moves there are int numFreeSquares = 0; for (int i = 0; i < 9; ++i) { if (isFree(i)) { numFreeSquares++; } } // if there is at least one possible move, pick randomly if (numFreeSquares > 0) { // shift twice to get rid of sign bit, then modulo numFreeSquares int pick = ((random.nextInt()<<1)>>>1) % numFreeSquares; // now find the chosen free square by counting pick down to zero for (int i = 0; i < 9; ++i) { if (isFree(i)) { if (pick == 0) { move = i; break; } pick--; } } }

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

26

Page 27: Brief Introduction to MIDP Graphics v1 - Prince of Songkla ...fivedots.coe.psu.ac.th/Software.coe/J2ME/Nokia... · Brief Introduction to MIDP Graphics Version 1.0 Disclaimer: The

Brief Introduction to MIDP Graphics

Version 1.0

return move; } private static boolean isWin(int state) { boolean isWinner = false; for (int i = 0; i < WINS.length; ++i) { if ((state & WINS[i]) == WINS[i]) { isWinner = true; break; } } return isWinner; } private static int bit(int i) { return 1 << i; } }

3.6 TicTacToe.jad

The following is the application descriptor for the TicTacToeMIDlet.

MIDlet-Name: TicTacToe MIDlet-Vendor: Forum Nokia MIDlet-Version: 1.1.1 MIDlet-Jar-Size: 11409 MIDlet-Jar-URL: TicTacToe.jar MIDlet-1: TicTacToe, /tictactoe.png, example.tictactoe.TicTacToeMIDlet

Copyright © 2002. Nokia Mobile Phones. All rights reserved.

27