使用高级用户界面技术开发的简单的猜数字游戏:随机生成一个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);
            }
        }
    }
}