我是java android开发的初学者,我创造了一个tic tac toe游戏。我已经完成了游戏的代码。但我对游戏的胜利条件感到困惑,因为我只是在网上向教练学习。 这是我对游戏毫无头绪的具体代码
//winning condition
//for(int [] winningPosition : winningPositions){
if(gameState[winningPosition[0]] == gameState[winningPosition[1]] &&
gameState[winningPosition[1]] == gameState[winningPosition[2]] &&
gameState[winningPosition[0]] != 2)
这是代码。 (我没有发布整个代码,因为我只想展示相关代码,以帮助您理解我想要问的内容)
public class MainActivity extends AppCompatActivity {
//0 = yellow , 1 = red;
int activePlayer = 0;
boolean gameIsActive = true;
//2 mean 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,5,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).rotation(360).setDuration(300);
for(int []winningPosition : winningPositions){
if(gameState[winningPosition[0]] == gameState[winningPosition[1]] &&
gameState[winningPosition[1]] == gameState[winningPosition[2]] &&
gameState[winningPosition[0]] != 2)
{
//Someone has won!
gameIsActive = false;
String winner = "Red";
if(gameState[winningPosition[0]] == 0){
winner = "Yellow";
}
LinearLayout layout = (LinearLayout) findViewById(R.id.playAgainLayout);
TextView winnerMessage = (TextView) findViewById(R.id.winnerMessage);
winnerMessage.setText( winner +" has won!");
layout.setVisibility(View.VISIBLE);
} else {
boolean gameIsOver = true;
for(int counterState : gameState){
if(counterState == 2) gameIsOver = false;
}
if(gameIsOver){
LinearLayout layout = (LinearLayout) findViewById(R.id.playAgainLayout);
TextView winnerMessage = (TextView) findViewById(R.id.winnerMessage);
winnerMessage.setText( "It's a draw!");
layout.setVisibility(View.VISIBLE);
}
}
}
}
}
答案 0 :(得分:1)
winningPositions
包含您可以举行以赢得比赛的所有可能的场组合(三行,三列和两个对角线)。您的代码会迭代这些winningPositions
,并且每次检查是否所有三个字段都由同一个人持有,并且此人不是一个人(//2 mean unplayed
)。
答案 1 :(得分:0)
答案 2 :(得分:0)
基本上它的作用是: 对于每个获胜状态(每个可能的三个框的行),它想知道它们是否具有相同的状态(X,O或无效),并且它们是否无效(这是我认为数字2的含义)