用while循环结束我的游戏 - java

时间:2014-11-01 04:05:59

标签: java arraylist while-loop

我在尝试制作TicTacToe游戏时添加了此代码。最初这个游戏只玩了一个回合,但我需要一种方法让玩家在游戏完成后结束游戏。但是当我运行代码时,它甚至没有转弯。我之前用一个简单的while(a> 3){/ play turn / a ++;}进行了测试,但它在大多数情况下都有效,但是循环未能正确结束,只是让它逐渐变细并强制执行我手动关闭我的终端。

http://hastebin.com/iziselusex.tex

这是我的转身方法,因为你要求它

http://hastebin.com/isoxifufeq.axapta

这包含Initialize方法,以及turn函数

中提到的方法
    int[][] anArray = new int[3][3];
    aBoard.initialize();

    int end = 0;

    int t = 0;

    while(end != 1){ //so long as end isn't reached, the game will still play
        while(t < 4){ //there are a total of 4 turns that can take place before the board is filled up. 5 if you include the last piece, but i wasn't sure about including it.
            anArray = this.turns(anArray);//this starts the turn

            if((anArray[0][0] == anArray[1][1]) && (anArray[1][1] == anArray[2][2])){
                end = 1;
            }else if((anArray[0][2] == anArray[1][1]) && (anArray[1][1] == anArray[2][0])){
                end = 1;
            }else if((anArray[0][0] == anArray[0][1]) && (anArray[0][1] == anArray[0][2])){
                end = 1;
            }else if((anArray[1][0] == anArray[1][1]) && (anArray[1][1] == anArray[1][2])){
                end = 1;
            }else if((anArray[2][0] == anArray[2][1]) && (anArray[2][1] == anArray[2][2])){
                end = 1;
            }else if((anArray[0][0] == anArray[1][0]) && (anArray[1][0] == anArray[2][0])){
                end = 1;
            }else if((anArray[0][1] == anArray[1][1]) && (anArray[1][1] == anArray[2][1])){
                end = 1;
            }else if((anArray[0][2] == anArray[1][2]) && (anArray[1][2] == anArray[2][2])){
                end = 1;
            }else{
                end = 0;
            }//this checks for possible victories that could have been made during the last turn

            t++; //starts the next cycle over again
        }
        end = 1; //once all the turns are exhausted, the game ends

        if(end == 1){
           aView.println("The game is finished!");
           System.exit(0);
        }
    }

编辑:我在最后添加了退出函数并修复了第二个while循环问题(不再是t&gt; 4)

2 个答案:

答案 0 :(得分:1)

首先,第二个while需要为while(t <4),因为t从0开始,t> 4会立即评估为false,甚至不会运行循环体。

答案 1 :(得分:0)

正如@Andrew指出的那样,你的第二个循环条件while(t > 4)永远不会评估为true,因为它进入你的第一个循环,其值为0.将此更改为while(t < 4),你至少会进入你的游戏循环&#34;。

您还应该在第一次循环之后但在第二次循环之前设置t = 0的值,如下所示:

while(end != 1) { //so long as end isn't reached, the game will still play
    t = 0; // reset the value of 't' so we will enter inner loop again
    while(t < 4) {
    ...