package rollBall;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
/**
* 自由滚动的小球
*
* @author kf156(亚日)
*
*/
public class GameCanvas extends Canvas implements Runnable {
public Thread thread;
public boolean running = true;
public int width, height, ballX = 0, ballY = 0, ballAngle = 0;
private final int DIAMETER = 40;// 小球直径
public int[] key = new int[4];
private final int DISTANCE = 5;// 每次移动的距离
private final int ANGLE = 12;// 每次转动的角度
public final static int KEY_UP = -1;// 上
public final static int KEY_DOWN = -2;// 下
public final static int KEY_LEFT = -3;// 左
public final static int KEY_RIGHT = -4;// 右
public GameCanvas() {
setFullScreenMode(true);
startThread();
init();
}
public void free() {
}
public void init() {
width = getWidth();
height = getHeight();
}
public void input() { // 判断
key[0] = key[2];
key[1] = key[3];
key[2] = 0;
}
public void update() {
switch (key[1]) {
case KEY_UP:
ballY -= DISTANCE;
ballAngle += ANGLE;
if (ballY < -DIAMETER)
ballY = height;
break;
case KEY_DOWN:
ballY += DISTANCE;
ballAngle -= ANGLE;
if (ballY > height)
ballY = -DIAMETER;
break;
case KEY_LEFT:
ballX -= DISTANCE;
ballAngle += ANGLE;
if (ballX < -DIAMETER)
ballX = width;
break;
case KEY_RIGHT:
ballX += DISTANCE;
ballAngle -= ANGLE;
if (ballX > width)
ballX = -DIAMETER;
break;
}
}
protected void paint(Graphics g) {
g.setColor(0x000000);
g.fillRect(0, 0, width, height);
// 正转的小球
g.setColor(0x00ff00);
g.fillArc(ballX, ballY, DIAMETER, DIAMETER, 0, 360);
g.setColor(0x0000ff);
g.fillArc(ballX, ballY, DIAMETER, DIAMETER, ballAngle + 60, 60);
g.fillArc(ballX, ballY, DIAMETER, DIAMETER, ballAngle + 180, 60);
g.fillArc(ballX, ballY, DIAMETER, DIAMETER, ballAngle + 300, 60);
}
public void startThread() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void run() {
int debug = 0;
try {
while (running) {
long start = System.currentTimeMillis();
input();
debug = 1;
update();
debug = 2;
repaint();
serviceRepaints();
Thread.yield();
long end = System.currentTimeMillis() - start;
if (end < 50)
Thread.sleep(50 - end);
}
GameMIDlet.quitApp();
} catch (Exception e) {
System.err.println("run error:" + e + "debug:" + debug);
}
}
// 当按键按下时
protected void keyPressed(int keyCode) {
key[2] = key[3] = keyCode;
}
// 当按键释放时
public void keyReleased(int keyCode) {
key[3] = 0;
}
}