gpt4 book ai didi

java - 井字棋 - 2D 阵列

转载 作者:行者123 更新时间:2023-12-02 13:42:34 28 4
gpt4 key购买 nike

我尝试创建 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;
}

最佳答案

这个问题有一些您想要做的事情:

首先确保值不存在:(考虑评论中的建议)

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 次单独的检查。水平、垂直和对角线。

我不想为你完成整个作业,所以把它留给你

关于java - 井字棋 - 2D 阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42658872/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com