简体   繁体   中英

How To Check if all ImageView inside GridLayout is not Empty?

I'm trying to make a tictactoe game using Android Studio. I already write a code to set the button visibility when someone is win (and it work). I also want the game to show "play again" button when the board is full but no one win (tie). How do i do that.

Here's what I'm trying to code:

public boolean checkGameState () {
    boolean isBoardFull = false;
    androidx.gridlayout.widget.GridLayout gridLayout = findViewById(R.id.gridLayout);
    for (int i = 0; i < gridLayout.getChildCount(); i++) {
        ImageView reset = (ImageView) gridLayout.getChildAt(i);
        if(reset.getDrawable() != null) {
            isBoardFull = true;
        }
    }
    return isBoardFull;
}

Here's a screenshot of what the game look like:

游戏截图

as you can see in the image, the "Play again" button is visible even though the game hasn't been finished yet. The button will show if the someone is win or tie (the board is full).

There is slight mistake with your condition as once it found drawable it marks as isBoardFull as true , Which is wrong as all child haven't been checked yet so marking isBoardFull as true at this stage is wrong.

You can do like following:

public boolean checkGameState () {
    boolean isBoardFull = true; // first mark it as full
    androidx.gridlayout.widget.GridLayout gridLayout = findViewById(R.id.gridLayout);
    for (int i = 0; i < gridLayout.getChildCount(); i++) {
        ImageView reset = (ImageView) gridLayout.getChildAt(i);
        if(reset.getDrawable() == null) {
            isBoardFull = false; // if drawable not found that means it's not full
        }
    }
    return isBoardFull;
}

So now first it will mark board as full but once any drawable is found as null it will mark board as empty.

I think you should initialize a variable isEveryChildChecked = true before iterating the gridLayout child. While iterating the children, if a grid is not checked, set the field isEveryChildChecked = false .

Then after iteration, check the field isEveryChildChecked, If it is true, you can display play again else do nothing or hide the Play again button.

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