对于我的作业,我必须创建一个方法来检查 TicTacToeArray 变量并确定是否有人获胜。特别是,如果游戏板的任何列、行或主对角线完全被 Xs 或 Os 填充,则获胜。当检测到获胜者时, scoreTTT() 应将获胜者变量设置为“X”或“O”,具体取决于谁获胜。如果 X 或 O 均未获胜,则获胜者变量应为“*”。
到目前为止,我有这个:
公共课井字游戏{
public static void main(String[] args){
}
//state variables
static char[][] TicTacToeArray; //the game board
static int step = 0; //the current step number
static char winner = '*'; //who has won (X/O/*) *=nobody
static char player = 'X'; //whose turn it is (X/O) *=nobody
//Creates a game board of size n x n and resets state variables to
//their initial conditions for a new game.
public static void startTTT(int n){
TicTacToeArray = new char [n][n];
for(int i = 0; i < n; i++){
for(int j=0; j < n; j++){
TicTacToeArray [i][j] = '*';
}
}
step = 0;
winner = '*';
player = 'X';
}
public static void displayTTT(){
String row;
int n = TicTacToeArray.length;
//now I'm priting row0
row = " Column";
System.out.println(row);
//row 1
row = " ";
for (int i=0; i<n; i++){
row = row + " "+ i;
}
row = row + " TicTacTow";
System.out.println(row);
//row 2
row = " +";
for (int i=0; i<n; i++){
row = row + "--";
}
System.out.println(row +" Step = " + step);
//row 3
row = " 0 |" ;
for (int i=0; i<n; i++){
row = row + " " + TicTacToeArray [0][i];
}
System.out.println(row + " Player = " + player);
//row 4
row = "Row 1 |";
for (int i=0; i<n; i++){
row = row + " " + TicTacToeArray[1][i];
}
System.out.println(row);
//row 5
row = "";
for( int i=2;i<n;i++){
row = " " + i + " |" ;
for( int j=0; j < n; j++){
row += " " + TicTacToeArray[i][j];
if (j == n)
System.out.println(row);
}
if(i == n-1)
row += " Winner = " + winner;
System.out.println(row);
}
}
//Updates a position on the game board, increments the step counter,
//and toggles the player from X to O (or vica versa). This method should
//test for invalid input (see assignment document) before changing
//the game state. If no error is encountered, it performs the update
//and returns true. Otherwise it returns false.
public static boolean updateTTT(char sym, int row, int col){
if (sym != 'X' && sym != 'O'){
return false;
}
if(row < 0 || col < 0 || row >= TicTacToeArray.length || col >= TicTacToeArray.length){
return false;
}
if (TicTacToeArray[row][col] == '*')
TicTacToeArray [row][col] = sym;
else
return false;
// toggle player
for(;;){
if (player =='X'){
player = 'O';
break;
}
if(player == 'O'){
player = 'X';
break;
}
}
//inc step count
step +=1;
return true;
}
//(这被注释掉了/到目前为止我对这个方法有什么,但是其余的代码应该可以工作) //public static void scoreTTT(){
//for(int i=0; i < TicTacToeArray.length; i++){
//for(int j =0; j < TicTacToeArray.length; j++)
//if (TicTacToeArray[i][j] == TicTacToeArray[i][j+1])
}
我想我需要创建 3 个不同的嵌套循环来检查对角线和行/列,它们还必须检查任何数组大小(例如 4 x 4)的完整行/列。我只是不确定如何我会让循环穿过整个行/列/对角线。谢谢你的帮助。