gpt4 book ai didi

java - 井字游戏(有条件)

转载 作者:行者123 更新时间:2023-11-30 09:13:11 32 4
gpt4 key购买 nike

出于某种原因,当我编写 getWinner() 时,它仅适用于 2 种情况(最后一行)。就对角线和列而言,我拥有其他一切,但第 2 行(嗯,三,但数组,所以 2)基本上只适用于 o。只有当 o 位于 0,0 和 1,1 或 0,2 和 1,1 时,x 才会获胜。 (本质上,仅当 o 位于顶角和中心时。

import java.util.Scanner;  
public class TicTacToeRunner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String player = "x";
TicTacToe game = new TicTacToe();
boolean done = false;
while (!done)
{
System.out.print(game.toString());
System.out.print(
"Row for " + player + " (-1 to exit): ");
int row = in.nextInt();
if (row < 0)
{
done = true;
}
else if (row > 2)
System.out.println("Invalid, please enter a number from 0 to 2");
else
{
System.out.print("Column for " + player + ": ");
int temp = in.nextInt();
if (temp>2)
System.out.println("Invalid, please enter a number from 0 to 2");
else
{
int column = temp;
game.set(row, column, player);
if (player.equals("x"))
player = "o";
else
player = "x";
}


if(game.getWinner().equals("x"))
{
System.out.println("x is the winner!");
done = true;
}
if(game.getWinner().equals("o"))
{
System.out.println("o is the winner!");
done = true;
}
}
}
}

public class TicTacToe  
{
private String[][] board;
private static final int ROWS = 3;
private static final int COLUMNS = 3;
public TicTacToe()
{
board = new String[ROWS][COLUMNS];
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLUMNS; j++)
board[i][j] = " ";
}
public void set(int i, int j, String player)
{
if (board[i][j].equals(" "))
board[i][j] = player;
//what if the spot is filled???
}
public String toString()
{
String r = "";
for (int i = 0; i < ROWS; i++)
{
r = r + "|";
for (int j = 0; j < COLUMNS; j++)

r = r + board[i][j];
r = r + "|\n";
}
return r;
}
public String getWinner() //which one isn't working? I tried a few attempts at the third col and third row, and both worked.
{
for (int i = 0; i <= 2; i++) //HORIZONTAL
{
if (board[i][0].equals(board[i][1]) && board[i][1].equals(board[i][2]))
return board[i][0];
}
for (int j = 0; j <= 2; j++) //VERTICAL
{ if (board[0][j].equals(board[1][j]) && board[1][j].equals(board[2][j]))
return board[0][j];
}
if (board[0][0].equals(board[1][1]) && board[1][1].equals(board[2][2]))
return board[0][0];
if (board[0][2].equals(board[1][1]) && board[1][1].equals(board[2][0]))
return board[1][1];
return " ";
}

}有什么建议吗?

最佳答案

如果一行或一列或对角线上没有空格,那么它们都将是""。但是,这仍然会满足一个条件,例如

board[i][0].equals(board[i][1]) && board[i][1].equals(board[i][2])

然后它会立即返回"",而不检查其他位置。 "" 是赢家!但是您还使用 "" 来表示没有赢家。

在您的条件中添加额外的检查,以确保您检查的第一个位置不等于 "",然后再检查条件表达式的其余部分:

!" ".equals(board[i][0]) &&
board[i][0].equals(board[i][1]) &&
board[i][1].equals(board[i][2])

您可以类似地更改其他条件。

关于java - 井字游戏(有条件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21122500/

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