應用高級用戶界面技巧開發的簡略的猜數字游戲:隨機天生一個0-50之間的數字,假如用戶輸進的數字大於實際的數字則顯示“大了”,假如輸進的數字小了,則顯示“小了”,假如相等則顯示“佩服佩服”。
游戲源代碼如下:
//文件名:CaiMIDlet.Java
package caichuzi;
import Javax.microedition.midlet.*;
import Javax.microedition.lcdui.*;
public class CaiMIDlet extends MIDlet {
static CaiMIDlet instance;
CaiForm displayable = new CaiForm(this);
public CaiMIDlet() {
instance = this;
}
public void startApp() {
Display.getDisplay(this).setCurrent(displayable);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public static void quitApp() {
instance.destroyApp(true);
instance.notifyDestroyed();
instance = null;
}
}
//文件名:CaiForm.Java
package caichuzi;
import Javax.microedition.lcdui.*;
import Java.util.*;
public class CaiForm extends Form implements CommandListener {
CaiMIDlet caiMIDlet;
/**提交按鈕*/
Command cmdCommit;
/**退出*/
Command cmdExit;
/**數字輸進框*/
TextFIEld tfNumber;
/**隨機對象*/
Random rd;
/**隨機數字*/
int randomNumber;
/**標記是否是第一個運行游戲*/
boolean flag;
public CaiForm(CaiMIDlet caiMIDlet) {
super("猜數字");
this.caiMIDlet = caiMIDlet;
tfNumber = new TextField("請輸進0-50之間的數字","",25,TextFIEld.NUMERIC);
cmdCommit = new Command("提交",Command.OK,1);
cmdExit = new Command("退出",Command.EXIT,1);
append(tfNumber);
addCommand(cmdCommit);
addCommand(cmdExit);
rd = new Random();
randomNumber = rd.nextInt(50);
//標記游戲第一次運行
flag = true;
this.setCommandListener(this);
}
public void commandAction(Command command, Displayable displayable) {
//退出按鈕
if (command == cmdExit) {
// stop the MIDlet
CaiMIDlet.quitApp();
}
//提交按鈕
if(command == cmdCommit){
//獲得輸進
String input = tfNumber.getString();
//轉換成數字
int temp = Integer.parseInt(input);
Alert alert = new Alert("猜數字","",null,AlertType.INFO);
alert.setTimeout(3000);
//根據輸進顯示提示信息
if(temp > randomNumber){
alert.setString("大了,笨蛋!");
Display.getDisplay(caiMIDlet).setCurrent(alert);
}
if(temp == randomNumber){
alert.setString("佩服佩服!");
Display.getDisplay(caiMIDlet).setCurrent(alert);
}
if(temp < randomNumber){
alert.setString("小了,笨蛋!");
Display.getDisplay(caiMIDlet).setCurrent(alert);
}
}
}
}