ITPub博客

首页 > Linux操作系统 > Linux操作系统 > GameAction的使用范例(转)

GameAction的使用范例(转)

原创 Linux操作系统 作者:jcszjswkzhou 时间:2018-12-28 15:03:05 0 删除 编辑

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();
}
}


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10294527/viewspace-127157/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2007-08-29

  • 博文量
    176
  • 访问量
    98121