gpt4 book ai didi

java - 井字棋没有赢家

转载 作者:行者123 更新时间:2023-12-01 17:46:02 26 4
gpt4 key购买 nike

我是 Android 开发的初学者,我正在尝试在讲师指导类(class)的帮助下构建井字游戏。

我已经为两名玩家添加了两个获胜条件,但我想添加一个无获胜者或平局状态的条件。

我该怎么做?

这是我的代码:

public class MainActivity extends AppCompatActivity {

// 0 : yellow, 1 : red, empty : 2

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}};

int activePlayer = 0;

boolean gameActive = true;

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

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

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

gameState[tappedCounter] = activePlayer;

counter.setTranslationY(-1500);
if (activePlayer == 0) {

counter.setImageResource(R.drawable.yellow);
activePlayer = 1;

} else {

counter.setImageResource(R.drawable.red);
activePlayer = 0;
}
counter.animate().translationYBy(1500).setDuration(400);
for (int[] winningPosition : winningPositions) {
if (gameState[winningPosition[0]] == gameState[winningPosition[1]] && gameState[winningPosition[1]] == gameState[winningPosition[2]] && gameState[winningPosition[0]] != 2) {

String winner = "";

gameActive = false;
if (activePlayer == 1) {
winner = "Yellow";
} else {
winner = "Red";
}
//Toast.makeText(this, winner + " have won!", Toast.LENGTH_SHORT).show();

Button playAgainButton = (Button) findViewById(R.id.playAgainButton);
TextView winnerTextView = (TextView) findViewById(R.id.winnerTextView);

winnerTextView.setText(winner + " has won!");

playAgainButton.setVisibility(View.VISIBLE);
winnerTextView.setVisibility(View.VISIBLE);


}
}
}
}

public void playAgain(View view){
Button playAgainButton = (Button) findViewById(R.id.playAgainButton);
TextView winnerTextView = (TextView) findViewById(R.id.winnerTextView);
playAgainButton.setVisibility(View.INVISIBLE);
winnerTextView.setVisibility(View.INVISIBLE);

GridLayout gridLayout = findViewById(R.id.gridLayout);
for(int i=0; i < gridLayout.getChildCount(); i++){
ImageView counter = (ImageView) gridLayout.getChildAt(i);
counter.setImageDrawable(null);
}
for(int i = 0; i < gameState.length; i++){
gameState[i] = 2;
}

activePlayer = 0;

gameActive = true;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

最佳答案

这非常简单 - 你必须知道每个字段何时被占用(有人在上面加上“X”或“O”)因此,当所有字段都被占据并且没有获胜位置时 - 则为平局。

从程序的角度来看:

1) 当玩家 1 或玩家 2 移动时 - 计算剩余的空闲区域

2)当自由字段== 0时调用draw()函数或类似的函数

关于java - 井字棋没有赢家,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60864247/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com