我已经完成了一个井字游戏,但我唯一的问题是我无法确定游戏中的赢家/领带。我有一个专门用于寻找胜利者的方法,但它不起作用。我究竟做错了什么?这是代码:
import java.util.Scanner;
public class TicTacToe {
public static final int X = 1;
public static final int Y = 2;
public static void main(String[] args) {
final int X = 1;
final int Y = 2;
int[][] board = {{0, 0, 0},
{0, 0, 0},
{0, 0, 0}
};
int count = 0;
while (!checkWinner(board)) {
printBoard(board);
if (count % 2 == 0) {
System.out.println("X's turn");
move(X, board);
} else {
System.out.println("Y's turn");
move(Y, board);
}
System.out.println();
count++;
}
}
public static boolean checkWinner(int[][] board) {
if (board[0][0] == board[1][0] && board[1][0] == board[2][0] && (board[0][0] == "X" || board[0][0] == "Y")) {
return true;
} else if (board[0][1] == board[1][1] && board[1][1] == board[2][1] && (board[0][1] == "X" || board[0][1] == "Y")) {
return true;
} else if (board[0][2] == board[1][2] && board[1][2] == board[2][2] && (board[0][2] == "X" || board[0][2] == "Y")) {
return true;
} else if (board[0][0] == board[0][1] && board[0][1] == board[0][2] && (board[0][0] == "X" || board[0][0] == "Y")) {
return true;
} else if (board[1][0] == board[1][1] && board[1][1] == board[1][2] && (board[1][0] == "X" || board[1][0] == "Y")) {
return true;
} else if (board[2][0] == board[2][1] && board[2][1] == board[2][2] && (board[2][0] == "X" || board[2][0] == "Y")) {
return true;
} else if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && (board[0][0] == "X" || board[0][0] == "Y")) {
return true;
} else if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && (board[2][0] == "X" || board[2][0] == "Y")) {
return true;
} else {
return false;
}
}
public static void printBoard(int[][] board) {
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
if (board[i][j] == TicTacToe.X) {
System.out.print("X");
} else if (board[i][j] == TicTacToe.Y) {
System.out.print("Y");
} else {
System.out.print("-");
}
System.out.print(" | ");
}
System.out.println();
}
}
public static void move(int player, int[][] board) {
Scanner myScan = new Scanner(System.in);
System.out.print("Row: ");
int x = myScan.nextInt();
System.out.print("Column: ");
int y = myScan.nextInt();
board[x][y] = player;
}
}
我不需要为此程序添加其他方法,因为这就是我所需要的。
答案 0 :(得分:3)
如果没有获胜者 AND 主席未满,您应该将null
循环中的条件替换为
let foo:number = null; // Error foo is not nullable
我建议您重新访问while
方法,虽然该格式有效但效率很低,您可以找到一种更简单,更有趣的方法来实现它。例如,您可以利用以下内容:
while(!checkWinner(board) && /*board is not full*/) {
//...
}
if(checkWinner(board)) //→ there's a winner;
else //it's a draw;
答案 1 :(得分:0)
您的代码是否编译没有任何错误?
我看不出这是如何起作用的? board [1] [0] ==“X”
board是一个整数数组!您应该看到“不兼容的操作数类型int和String”!
答案 2 :(得分:0)
您的数组是整数类型,但您可以在函数中将其与&#34; X&#34;等字符串进行比较。和&#34; Y&#34;。你必须替换... ==&#34; X&#34;与... == TicTacToe.X和... ==&#34; Y&#34;在checkWinner()函数的所有if语句中使用... == TicTacToe.Y。