我正试着用Android制作一个tictactoe游戏。我已经写了一个代码来设置按钮的可见性,当有人赢了(而且它能工作)。我也希望游戏显示“再玩”按钮时,董事会是满的,但没有人赢(平局)。我该怎么做呢。
下面是我想要的代码:
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;
}
下面是游戏的截图:
正如你在图片中所看到的,即使游戏还没有完成,“再次播放”按钮也是可见的。按钮将显示某人是否获胜或平局(董事会已满)。
发布于 2022-01-20 20:18:48
您的条件有轻微的错误,因为一旦发现可绘制,它就将其标记为isBoardFull
为true
,这是错误的,因为还没有检查所有的子级,所以在这个阶段将isBoardFull
标记为true
是错误的。
你可以这样做:
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;
}
因此,首先,它将标记板为满,但一旦发现任何可绘制为空,它将标记板为空。
发布于 2022-01-20 20:14:32
我认为您应该在迭代isEveryChildChecked = true
子变量之前初始化一个变量gridLayout。在迭代子元素时,如果没有检查网格,则设置字段isEveryChildChecked = false
。
然后,在迭代之后,检查字段isEveryChildChecked,如果是真的,您可以再次显示play,否则什么都不做,或者隐藏Play按钮。
https://stackoverflow.com/questions/70796246
复制