Java手机游戏编程之MIDP图形设计篇(4) 3、TicTacToeMIDlet.java TicTacToeMIDlet非常简单:它处理MIDlet的生命周期事件。它根据需要创建屏幕对象并且处理来自屏幕的回调。ChoosePieceScreenDone回调被用来创建GameScreen。quit方法则被GameScreen用来结束游戏。
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 } Alert splashScreen = new Alert(null, "Tic-Tac-Toe\nForum Nokia", logo, AlertType.INFO); 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); } } | 4、ChoosePieceScreen.java
ChoosePieceScreen是一个基于高级应用编程接口窗体的屏幕,允许游戏者选择圆或叉作为棋子。当游戏者按下OK键时,它使用MIDlet的回调方法choosePieceScreenDone来处理游戏者的选择。
package example.tictactoe; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; 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 // quit Command { midlet.quit(); } } private Image loadImage(String imageFile) { Image image = null; try { image = Image.createImage(imageFile); } catch (Exception e) { // Use a 'null' image in the choice list (i.e. text only choices). } return image; } } | (未完待续)
|