Android开发:不了解每个循环使用2d数组

时间:2016-01-05 05:19:25

标签: java android arrays if-statement for-loop

我在创建一个简单的tic tac toe游戏的教程中遇到了这段代码。可以找到完整的代码here

这个for循环是什么呢?当for循环循环时,[0],[1],[2]是否会自行递增?如果将2d数组转换为1d数组,它会是什么样子?它是否保持相同的位置?

例如

int[][] winningStates = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}}; 

如果转换成1d数组会是这样的吗?:

{0,1,2,3,4,5,6,7,8,0,3,6,1,4,7,2,5,8,0,4,8,2,4,6};
int[] gameState = {2,2,2,2,2,2,2,2,2};
int[][] winningStates = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
boolean gameIsActive = true;

for(int[] winningState : winningStates){
            if(gameState[winningState[0]] == gameState[winningState[1]] &&
                    gameState[winningState[1]] == gameState[winningState[2]] &&
                    gameState[winningState[0]] != 2){
                gameIsActive = false;
                String winner = "Black";

                if(gameState[winningState[0]] == 0){
                    winner = "Red";
                }
                //someone has won!
                playAgainMessage again = new playAgainMessage();
                again.playAgainMethod(winner + " has Won !!");
            }

1 个答案:

答案 0 :(得分:0)

不,for循环将为winsState生成以下值(它在数组数组中迭代):

{0,1,2} -> winningState[0] = 0, winningState[1] = 1, winningState[2] = 2
{3,4,5} -> winningState[0] = 3, winningState[1] = 4, winningState[2] = 5
{6,7,8}
{0,3,6} -> winningState[0] = 0, winningState[1] = 3, winningState[2] = 6
{1,4,7}
{2,5,8}
{0,4,8}
{2,4,6}