Here is a simple Tetris game code I wrote, which consists of 3 classes:
Lterrismidlet--midlet class
lgamecanvas--Game Interface Class
lgameengine--Game Logic Class
Use WTK2.5.1 to run through.
The specific code is as follows:
//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;
/**
* Tetris Game interface
*/
public class Gamecanvas extends Canvasimplements runnable{
GameEngine engine = new GameEngine ();
int width;
int height;
/** Game End variable * *
Boolean gameover = false;
/** Game Suspend variable * *
Boolean ispaused = false;
String pausestr = "Paused";
String continuestr = "Continue";
public Gamecanvas () {
//Full screen
Setfullscreenmode (TRUE);
width = getwidth ();
height = getheight ();
//Start thread
thread th = new thread (this);
Th.start ();
}
protected void Paint (Graphics g) {
//Clear Screen
Clearscreen (g);
//Draw Border
Paintboard (g);
//Drawing background
Engine.paintmap (g);
//Draw the current drop box
Engine.paintbrick (g);
//Draw next Square
Engine.paintnextbrick (g);
Draw checkpoints and game scores
Engine.paintlevelandscore (g);
//Draw game End
if (gameover) {
g.drawstring ("Game over", 30, 85,
Graphics.top | Graphics.left);
}
//Draw pause button text
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) {//Right soft key, pause control
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 ()/Accelerate
break;
}
}
repaint ();
}
public void keyreleased (int keycode) {
int action = getgameaction (KeyCode);
switch (action) {
Case down:
Engine.normalspeed (); Restore normal speed
break;
}
}
/**