package CANVAS3;
import java.util.Random;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Ticker;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
/**
* 產生一個0~9之間的隨機顏色的隨機數,點擊數字鍵相匹配,按錯扣2分,超時按1分
* 初始為5分
* @author Jakey
*
*/
public class Midlet2 extends MIDlet {
class GuessGame extends Canvas implements Runnable, CommandListener {
private String num = "-1";// 產生的隨機數
String action = "";
private int x = 0;
private int y = 0;
private int dots = 5;// 初始分數
private Thread th;
private boolean RUN = true;
private Random r = new Random();
private Command cmdReStart = new Command("重新開始", Command.SCREEN, 1);
public GuessGame() {
th = new Thread(this);
th.start();
}
public void commandAction(Command c, Displayable d) {
if (c == cmdReStart) {
RUN = true;
num = "-1";
dots = 5;
action = "";
this.removeCommand(cmdReStart);
th = new Thread(this);
th.start();
}
}
public void paint(Graphics g) {
this.setTitle("當前分數:"+(dots <= 0?0:dots));
g.setColor(255, 255, 255);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
Font f = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD,
Font.SIZE_LARGE);
g.setFont(f);
g.setColor(r.nextInt(256), r.nextInt(256), r.nextInt(256));
x = r.nextInt(this.getWidth());
y = r.nextInt(this.getHeight());
g.drawString(num.equals("-1") ? "" : num, x, y, Graphics.TOP
| Graphics.LEFT);
if (dots <= 0) {
//重新初始化
g.setColor(255, 255, 255);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(255, 0, 0);
g.drawString("您輸了", this.getWidth() / 2, this.getHeight() / 2,
Graphics.TOP | Graphics.HCENTER);
RUN = false;
th = null;
this.addCommand(cmdReStart);
this.setCommandListener(this);
}
}
public void keyPressed(int keyCode) {
if (dots > 0) {
action = this.getKeyName(keyCode);
if (num.equals(action)) {
dots += 1;
} else {
dots -= 2;
}
}
}
public void run() {
while (RUN) {
num = String.valueOf(r.nextInt(10));
repaint();
try {
Thread.currentThread().sleep(1000);
} catch (Exception e) {
}
if (action.equals("")) {// 控制如果超時則扣一分
dots--;
}
}
}
}
private Display dis;
private GuessGame gg = new GuessGame();
protected void startApp() throws MIDletStateChangeException {
dis = Display.getDisplay(this);
dis.setCurrent(gg);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
}