我的有限状态机过早地过了

时间:2014-09-14 02:36:03

标签: java state-machine

我现在已经看了两个小时同样的问题了。我希望一些新鲜的眼睛可以帮助我。

这是我正在制作的一场愚蠢的小游戏。

一旦我的机器进入PLAY,它就会在下一个循环中自动进入OVER,无论如何。我希望它能够持续循环播放状态直到达到游戏目标。我在这里做错了什么?

 //program stuff below
enum State {INTRO, BEGIN, PLAY, OVER, END}
static State gamestate;

public static void print(String s){

    System.out.println(s);
}


public static void main(String[] args){

    Scanner in = new Scanner(System.in);
    int rings = 0;
    gamestate = State.INTRO;
    Towers t = new Towers(1);
    do {
        switch(gamestate){

        case INTRO: System.out.print("Towers of Hanoi: A Children's Game\n by Julio Ollarvia\n\n\n");
                    gamestate = State.BEGIN;

        case BEGIN: System.out.print("How many rings would you risk?: ");

                    try{
                        rings = in.nextInt();
                        t = new Towers(rings);
                        print("\nturn out the lights and light a candle...");
                        gamestate = State.PLAY;

                    }catch(IllegalArgumentException e){
                        System.out.println("/n lets keep it between 0 and 64, bad boy.");

                    }



        case PLAY: print(t.toString());
                   print("this ring is free, grab 1,2, or 3... ");
                   try{
                    int movefrom = in.nextInt();
                    print("to complete your fun, choose 3,2, or 1...");
                    int moveto = in.nextInt();
                    t.move(movefrom,moveto);
                    if (t.peg2.getRingCount() == rings){
                        print("rings: "+rings);
                        print("peg: "+t.peg2.getRingCount());
                        gamestate = State.OVER;
                    }
                   }catch (IllegalArgumentException e){
                    print("Pegs are numbered between 1 and 3. Please choose just 1,2,3. And don't choose the same one.");

                   }
                   print(gamestate == State.OVER? "over": "still goin'");




        case OVER: print("Better luck next time.\n   wait... no. You won!  "+5*rings+" paraBitCoin has been deposited into your account.\n Please allow"+
                " 28 business days for transaction to complete.");

                gamestate = State.END;
        }

    }while(gamestate != State.END);
    in.close();
}

1 个答案:

答案 0 :(得分:2)

您的代码存在的问题是您的案件中没有break个陈述。

在Java中,交换机中case语句的默认值是通过的。也就是说,在执行一个案例之后,下一个案例也会运行:

    int a = 1;
    switch (a) {
        case 1:
            System.out.println("This gets printed");
        case 2:
            System.out.println("So does this");
    }

如果只想执行匹配的大小写,则需要在匹配大小写结束时显式中断switch语句:

    int b = 1;
    switch (b) {
        case 1:
            System.out.println("This gets printed");
            break;
        case 2:
            System.out.println("This doesn't");
    }

在您的代码中,无论您使用的是哪个gamestate,都会执行匹配后的每个案例,最终结果OVER将状态设置为END并转储给您离开你的循环。