Issue
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).
Solution
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.
Answered By - Bhavin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.