一个简单的猜谜游戏的代码(高级用户界面制作)

//MiDlet1.java

package test;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class MIDlet1 extends MIDlet {
    static MIDlet1 instance;
    Displayable1 displayable = new Displayable1(Display.getDisplay(this));
    public MIDlet1() {
        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;
    }

}

//Displayable1.java

package test;

import javax.microedition.lcdui.*;

public class Displayable1 extends Form implements CommandListener {
    /**题目内容*/
    String[] question = {
         "花园里都是草。(打一植物)",
         "一年后花园里还是草。(也打一植物)",
         "来了一只羊。(还打一植物)",
         "来了一只狼。(再打一植物)"
    };
    /**题目选项*/
    String[][] answer = {
                      {"桃花","草莓","梨花","梅花"},
                      {"人参果","梨树","草莓","野梅花"},
                      {"野梅花","梨树","草莓","灌木"},
                      {"桃花","梅花","梨花","扬梅"}
    };
    /**正确答案的序号,第一个是0,依次类推*/
    int[] rightAnswer={3,3,2,3};

    ChoiceGroup cgQuestion;
    /**当前题目编号*/
    int index = 0;

    /**确定按键*/
    Command cmdOk;

    Display display;
    public Displayable1(Display display) {
        super("猜谜语");
        this.display = display;
        //创建题目
        cgQuestion = new ChoiceGroup(question[index],ChoiceGroup.EXCLUSIVE);
        //填充选择项
        for(int i = 0;i < 4;i++){
            cgQuestion.append(answer[index][i],null);
        }
        append(cgQuestion);
        cmdOk = new Command("确定",Command.OK,1);
        addCommand(cmdOk);
        setCommandListener(this);
    }

    public void commandAction(Command command, Displayable displayable) {
        //确定按钮
        if(command == cmdOk){
            //获得用户的选择
            int selectIndex = cgQuestion.getSelectedIndex();

            //判断是否回答不正确
            if(selectIndex != rightAnswer[index]){
                Alert a = new Alert("猜谜语","回答错误,请仔细思考!",null,AlertType.INFO);
                a.setTimeout(3000);
                display.setCurrent(a);
                //返回
                return;
            }

            //如果不是最后一个题目,则显示下一题
            if(index < question.length - 1){
                index++;
                //修改界面显示的内容
                cgQuestion.setLabel(question[index]);
                //修改选项的内容
                for(int i = 0;i < 4;i++){
                    cgQuestion.set(i,answer[index][i],null);
                }
            }else{//显示成功界面
                Alert a = new Alert("猜谜语","游戏成功!",null,AlertType.INFO);
                a.setTimeout(Alert.FOREVER);
                display.setCurrent(a);
            }
        }
    }

}

你可能感兴趣的:(游戏,String,command,null,Class,import)