您现在的位置: J2ME开发网 >> 参考源码 >> J2ME源码 >> 游戏源码 >> 例子正文
GameAction的使用范例
作者:佚名    例子来源:本站原创    点击数:    更新时间:2005-12-2

GameActionExample描述了如何使用Canvas开发游戏,重点突出了如何将keyCode转换为GameAction处理用户的输入。适合初学者了解游戏开发的基本按键转换

/*
 * GameActionExample.java
 *
 * Created on 2005年12月2日, 下午12:53
 */

package com.j2medev.game;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class GameActionExample extends MIDlet {
   
    private Display  display;
    private MyCanvas canvas;
    public GameActionExample() {
        display = Display.getDisplay(this);
        canvas  = new MyCanvas(this);
    }
    protected void startApp() {
        display.setCurrent(canvas);
    }
    protected void pauseApp() {
    }
    protected void destroyApp( boolean unconditional ) {
    }
    public void exitMIDlet() {
        destroyApp(true);
        notifyDestroyed();
    }
}
class MyCanvas extends Canvas implements CommandListener {
   
    private Command exit;
    private String message;
    private GameActionExample gameActionExample;
    private int x, y;
   
    public MyCanvas(GameActionExample gameActionExample) {
        x = 5;
        y = 5;
        message = "演示游戏动作按键";
        this.gameActionExample = gameActionExample;
        exit = new Command("退出", Command.EXIT, 1);
        addCommand(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 command, Displayable displayable) {
        if (command == exit) {
            gameActionExample.exitMIDlet();
        }
    }
    protected void keyPressed(int key) {
        switch ( getGameAction(key) ){
            case Canvas.UP:
                message = "向上";
                y--;
                break;
            case Canvas.DOWN:
                message = "向下";
                y++;
                break;
            case Canvas.LEFT:
                message = "向左";
                x--;
                break;
            case Canvas.RIGHT:
                message = "向右";
                x++;
                break;
            case Canvas.FIRE:
                message = "开火";
                break;
        }
        repaint();
    }
}