一个游戏操作会根据游戏者按下的按键调用keyPresed()、keyReleased()、keyRepeated()方法。可以调用getGameAction()方法探测发生了哪些游戏操作。getGameAction()方法需要一个参数,即游戏者选择的按键的按键编码,这个编码会作为参数传给keyPressed()、keyReleased()和keyRepeated()方法。
使用两种方法可以探测游戏者所选择的游戏操作按键。
第一种:调用getKeyCode()方法比较按键编码值。
if(getKeyCode(FIRE)==keycode){ //fire }
第二种:调用getKeyName()方法,获得和输入的按键编码相关联的按键的名称。if(getKeyName(getKeyCode(FIRE).equeals(getKeyName(keycode)))){ //fire }
package mtk; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Graphics; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class GameActionExample extends MIDlet { private Display display; private MyCan canvas; public GameActionExample() { display=Display.getDisplay(this); canvas=new MyCan(this); } protected void destroyApp(boolean arg0){ } protected void pauseApp() { } public void exitMidlet(){ destroyApp(true); notifyDestroyed(); } protected void startApp() throws MIDletStateChangeException { display.setCurrent(canvas); } } class MyCan extends Canvas implements CommandListener{ private Command CMD_EXIT=new Command("退出",Command.EXIT,1); private String message; private GameActionExample gameActionExample; private int x,y; public MyCan(GameActionExample gameActionExample){ x=5; y=5; message="使用游戏键"; this.gameActionExample=gameActionExample; addCommand(CMD_EXIT); setCommandListener(this); } protected void paint(Graphics graphics) { graphics.setColor(255,255,255); graphics.fillRect(0, 0, getWidth(), getHeight()); graphics.setColor(255,0,0); graphics.drawString(message, x, y, Graphics.TOP|Graphics.LEFT); } public void commandAction(Command c, Displayable d) { if(c==CMD_EXIT){ gameActionExample.exitMidlet(); } } protected void keyPressed(int key){ switch(getGameAction(key)){ case Canvas.UP: message="up"; y--; break; case Canvas.DOWN: message="down"; y++; break; case Canvas.LEFT: message="left"; x--; break; case Canvas.RIGHT: message="right"; x++; break; case Canvas.FIRE: message="fire"; break; } repaint(); } }