前段时间我问了一个问题。经过多次代码重写,我的井字游戏看起来不错,除了一个明显的问题。当我尝试玩游戏时,获胜条件似乎是随机激活的 - 我将 x - o - x 排成一行并说“玩家 X 赢了!”,但当我有 o - o - o 时,它不会检测到赢。绘图工作正常。
获胜条件代码:
// win conditions. if true, set win==true; else set win==false
if (square[0].getText().equals(square[1].getText())
&& square[1].getText().equals(square[2].getText())
!= square[0].getText().isEmpty()) {
win = true;}
if (square[3].getText().equals(square[4].getText())
&& square[4].getText().equals(square[5].getText())
!= square[3].getText().isEmpty()) {
win = true;}
if (square[6].getText().equals(square[7].getText())
&& square[7].getText().equals(square[8].getText())
!= square[6].getText().isEmpty()) {
win = true;}
if (square[0].getText().equals(square[3].getText())
&& square[3].getText().equals(square[6].getText())
!= square[0].getText().isEmpty()) {
win = true;}
if (square[1].getText().equals(square[4].getText())
&& square[4].getText().equals(square[7].getText())
!= square[1].getText().isEmpty()) {
win = true;}
if (square[2].getText().equals(square[5].getText())
&& square[5].getText().equals(square[8].getText())
!= square[2].getText().isEmpty()) {
win = true;}
if (square[0].getText().equals(square[4].getText())
&& square[4].getText().equals(square[8].getText())
!= square[0].getText().isEmpty()) {
win = true;}
if (square[6].getText().equals(square[4].getText())
&& square[4].getText().equals(square[2].getText())
!= square[6].getText().isEmpty()) {
win = true;}
else{win = false;
}
和动作代码:
public void actionPerformed (ActionEvent e) {
//one more move has gone by, calculate player turn + player letter
move++;
if (move % 2 == 0) {
player = 1; letter = "X";
}else{
player = 2; letter = "O";
}
playergo.setText("It is player " + player + "'s go!");
//set square letter to player's letter, disable square so no further moves can be made there
for (int i=0; i<=8; i++){
if (e.getSource() == square[i]){
square[i].setText(letter);
square[i].setEnabled(false);
}
}
完整的 pastebin 代码在这里。谢谢大家!!!