下面是我写的一个简单的俄罗斯方块游戏代码,代码中主要包含3个类:
lTerrisMIDlet——MIDlet类
lGameCanvas——游戏界面类
lGameEngine——游戏逻辑类
使用WTK2.5.1运行通过.
具体代码如下:
//MIDlet类
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
public class TerrisMIDlet extends MIDlet {
public TerrisMIDlet() {
Display.getDisplay(this).setCurrent(new GameCanvas());
}
protected void destroyApp(boolean arg0){}
protected void pauseApp() {}
protected void startApp() {}
}
//界面类
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
/**
* 俄罗斯方块游戏界面
*/
public class GameCanvas extends Canvasimplements Runnable{
GameEngine engine = new GameEngine();
int width;
int height;
/**游戏结束变量*/
boolean gameOver = false;
/**游戏暂停变量*/
boolean isPaused = false;
String pauseStr = "暂停";
String continueStr = "继续";
public GameCanvas(){
//全屏幕
setFullScreenMode(true);
width = getWidth();
height = getHeight();
//启动线程
Thread th = new Thread(this);
th.start();
}
protected void paint(Graphics g) {
//清屏
clearScreen(g);
//绘制边框
paintBoard(g);
//绘制背景
engine.paintMap(g);
//绘制当前下落方块
engine.paintBrick(g);
//绘制下一个方块
engine.paintNextBrick(g);
//绘制关卡和游戏得分
engine.paintLevelAndScore(g);
//绘制游戏结束
if(gameOver){
g.drawString("Game Over", 30, 85,
Graphics.TOP | Graphics.LEFT);
}
//绘制暂停按钮文字
if(isPaused){
g.drawString(pauseStr,width,height,
Graphics.RIGHT | Graphics.BOTTOM);
}else{
g.drawString(continueStr,width,height,
Graphics.RIGHT | Graphics.BOTTOM);
}
}
public void keyPressed(int keyCode){
if(keyCode == -7){ //右软键,暂停控制
isPaused = !isPaused;
}
if(!isPaused){
int action = getGameAction(keyCode);
switch(action){
case UP:
case FIRE:
engine.changeShape();
break;
case LEFT:
engine.moveToLeft();
break;
case RIGHT:
engine.moveToRight();
break;
case DOWN:
engine.highSpeed();//加速
break;
}
}
repaint();
}
public void keyReleased(int keyCode){
int action = getGameAction(keyCode);
switch(action){
case DOWN:
engine.normalSpeed(); //恢复正常速度
break;
}
}
/**