0
我的代碼只打印空白空格,而不是每次提示輸入行號和列號,並查看空格是否爲空。我要生成電腦玩家的隨機數,但如果我這樣做是不知道正確的帶計算機端隨機數發生器的2D TicTacToe
import java.util.*;
public class TicTacToe
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int row, column;
char player = 'X';
char[][] board = new char[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;++j){
board[i][j] = ' ';
}
}
while(!checkWin(board,'O')==true)
{
computerPlay(board);
displayBoard(board);
if(checkWin(board,'X'))
{
System.out.println("Computer Wins");
System.exit(0);
}
if(checkTie(board))
{
System.out.println("Tie game");
System.exit(0);
}
playerPlay(board);
displayBoard(board);
if(checkWin(board,'O'))
{
System.out.println("Player Wins");
System.exit(0);
}
if(checkTie(board))
{
System.out.println("Tie game");
System.exit(0);
}
}
}
// Prompt the user for row & column index. Continue asking
// until an empty cell is selected. set the cell to 'O'
public static void playerPlay(char[][] board)
{
int row, column;
Scanner in = new Scanner(System.in);
while(checkTie(board)!= true)
{
System.out.println("Enter a row and column (0, 1, or 2); for player
:");
row = in.nextInt();
column = in.nextInt();
}
}
// Check by row, column, and diagonals
public static boolean checkWin(char[][] board,char ch)
{
if ( board[0][0] == 'O' && board[0][1] == 'O' && board[0][2] == 'O' || //
1st row
board[1][0] == 'O' && board[1][1] == 'O' && board[1][2] == 'O' || //
2nd row
board[2][0] == 'O' && board[2][1] == 'O' && board[2][2] == 'O' || //
3rd row
board[0][0] == 'O' && board[1][0] == 'O' && board[2][0] == 'O' || //
1st col.
board[0][1] == 'O' && board[1][1] == 'O' && board[2][1] == 'O' || //
2nd col.
board[0][2] == 'O' && board[1][2] == 'O' && board[2][2] == 'O' || //
3rd col.
board[0][0] == 'O' && board[1][1] == 'O' && board[2][2] == 'O' || //
Diagonal \
board[2][0] == 'O' && board[1][1] == 'O' && board[0][2] == 'O') //
Diagonal /
{
return true;
}
else {
return false;
}
}
// check for tie. If there no empty cells, then it is a tie
public static boolean checkTie(char[][] board)
{
for (int i = 0; i< board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] != 'O' && board[i][j] != 'X') {
return true;
}
}
}
return false;
}
// Display the board
public static void displayBoard(char[][] board)
{
System.out.println(board[0][0] + " | " + board[0][1] + " | " + board[0][2]
+ "\n---------");
System.out.println(board[1][0] + " | " + board[1][1] + " | " + board[1][2]
+ "\n---------");
System.out.println(board[2][0] + " | " + board[2][1] + " | " + board[2][2]
+ "\n");
}
// Continue generating random values for row and col until an
// empty cell selected. Set the cell to 'X'
public static void computerPlay(char[][]board)
{
while(checkTie(board)!= true)
{
for (int i=0; i<board.length; i++){
for(int j = 0; j<board.length; j++){
board[i][j] = (char)(Math.random()*10);
}
}
}
}
}