简体   繁体   中英

Android Development : Don't understand for each loop with 2d array

I came across this code in a tutorial for creating a simple tic tac toe game. The complete code can be found here

what does this for loop and if do? Does the [0],[1],[2] increment itself when the for loop loops? If a 2d array is being convert into 1d array what will it look like? Does it maintain the same position?

eg

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}}; 

if converted into 1d array will be like this?:

{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 !!");
            }

No, the for loop will generate the following values for winningState (it iterates within an array of arrays):

{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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM