我试图创建Tic Tac Toe,我能够填满我的董事会,我能够检查谁获胜的行和列。但是,我需要一些帮助来对角检查,看谁赢了。这就是我到目前为止所拥有的。我是初学者,所以请不要过于努力。
检查方法:
public boolean check(String[] [] board)
{
int j = 0;
for(int i = 0; i < board.length;i++) //row
{
if(board[i][j] == "X" || board[i][j+1] == "X" || board[i][j+2] == "X")
{
if(board[i][j] == board[i][j+1] & board[i][j] == board[i][j+2])
{
System.out.println("X wins!");
return true;
}
}
}
int e = 0;
for(j = 0; j < board.length;j++) //col
{
if(board[e][j] == "X" | board[e + 1][j] == "X" | board[e + 2][j] == "X" )
{
if(board[e][j] == board[e + 1][j] & board[e][j] == board[e + 2][j])
{
System.out.println("X, wins");
return true;
}
}
}
int d = 0;
for(int ii = 0; ii < board.length; ii++) //diag
{
if(board[d][ii] != null || board[d + 1][ii] != null | board[d + 2][ii] != null)
{
if(board[d][ii] == board[d + 1][ii+1] & board[d][ii] == board[d + 2][ii])
{
System.out.println("X, wins dig");
return true;
}
}
}
int k = 0;
for(int i = 0; i < board.length;i++) //row
{
if(board[i][k] == "O" || board[i][k+1] == "O" || board[i][k+2] == "O")
{
if(board[i][k] == board[i][k+1] & board[i][k] == board[i][k+2])
{
System.out.println("O wins!");
return true;
}
}
}
int z = 0;
for(k = 0; k < board.length; k++) //col
{
if(board[z][k] == "O" | board[z + 1][k] == "O" | board[z + 2][k] == "O" )
{
if(board[z][k] == board[z + 1][k] & board[z][k] == board[z + 2][k])
{
System.out.println("O, wins");
return true;
}
}
}
return false;
}
答案 0 :(得分:1)
这个问题有一些你想要做的事情:
首先确保价值已经不存在:(评论中的建议考虑在内)
public void fillX(String[][] board) {
attemptToFillValue(board, "x");
}
public void fillO(String[][] board) {
attemptToFillValue(board, "o");
}
private void attemptToFillValue(String[][]board, String value) {
do {
int r = Integer.parseInt(JOptionPane.showInputDialog("What row from 1-3?"));
int c = Integer.parseInt(JOptionPane.showInputDialog("What column from 1-3?"));
if (board[r - 1][c - 1] != null) {
board[r - 1][c - 1] = value;
return;
} else {
//Warn then that value already exists in some way
}
} while (true);
}
关于验证董事会是否有赢家,我建议使用for循环并进行3次单独检查。 水平,垂直和对角线。
我不想为你做整个任务,所以留给你