增强了android java类中的循环2d数组

时间:2017-03-04 11:10:04

标签: java android

**大家好,我正在努力学习如何在Android中构建应用程序和小游戏。有人可以解释在这种情况下增强的for循环如何工作以及增强for循环中的if语句如何检查获胜者?代码来自红色和黄色圆圈的tic tac toe游戏。对不起,如果问题已被提出。 **

// 0= yellow player; 1 = red player;

int activePlayer=0;

boolean gameIsActive = true;

//2 means unplayed
int[] gameState = {2,2,2,2,2,2,2,2,2};

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

public void dropIn(View view) {
    ImageView counter = (ImageView) view;

    int tappedCounter = Integer.parseInt(counter.getTag().toString());

    if (gameState[tappedCounter] == 2 && gameIsActive) {

        gameState[tappedCounter]=activePlayer;

        counter.setTranslationY(-1000f);

        if (activePlayer == 0) {
            counter.setImageResource(R.drawable.yellow);
            activePlayer = 1;
        } else {
            counter.setImageResource(R.drawable.red);
            activePlayer = 0;
        }
        counter.animate().translationYBy(1000f).setDuration(300);

     for (int[] winningPositon : winningPositions){
         if (gameState[winningPositon[0]]== gameState[winningPositon[1]]&& gameState[winningPositon[1]]==gameState[winningPositon[2]]
                 && gameState[winningPositon[0]]!=2){

        //someone has won
        ....

1 个答案:

答案 0 :(得分:0)

增强循环只不过是常规for循环的简单方法。 下面是循环

for (int i = 0; i < myArray.length; i++) {
    System.out.println(myArray[i]);
}

可以转换为增强型for循环

for (int myValue : myArray) {
    System.out.println(myValue);
}

在你的情况下

for (int[] winningPositon : winningPositions){
         if (gameState[winningPositon[0]]== gameState[winningPositon[1]]&& gameState[winningPositon[1]]==gameState[winningPositon[2]]
                 && gameState[winningPositon[0]]!=2){

&#34; winningPositon&#34;是一个2D数组,所以如果遍历它的元素,你将在每次迭代时获得一个单维数组(&#34; winningPosition&#34;),其余部分是游戏逻辑。

ANKIT