gpt4 book ai didi

java - Tic Tac Toe 程序未确定获胜者

转载 作者:行者123 更新时间:2023-12-01 09:53:13 24 4
gpt4 key购买 nike

我的井字棋程序有一个小问题。我有一个嵌套计数器,用于检查 X block 的垂直和水平胜利(我还没有为 O 完成它)。由于某种原因,它永远不会结束,让我可以放置越来越多的碎片。

对于某些上下文,这里有一些代码片段。

public static void game (String winner, Board pointer)
{
boolean win = false;
int turnCount = 1;
winner = "Tie";
while (win == false || turnCount < 9)
{
int row = Integer.parseInt(JOptionPane.showInputDialog(pointer.getName1() + ", it is your turn. " + "\n" + "What row would you like your 'x' to be in?"));
int col = Integer.parseInt(JOptionPane.showInputDialog("What column would you like it to be in?"));
pointer.play[row] [col] = pointer.x;
SpotCheck1(winner, pointer, row, col);
System.out.println(BoardStat(pointer));
winCheck(win, pointer, winner);
int row2 = Integer.parseInt(JOptionPane.showInputDialog(pointer.getName2() + ", it is your turn. " + "\n" + "What row would you like your 'o' to be in?"));
int col2 = Integer.parseInt(JOptionPane.showInputDialog("What column would you like it to be in?"));
SpotCheck2(winner, pointer, row2, col2);
pointer.play[row2] [col2] = pointer.o;
System.out.println(BoardStat(pointer));
winCheck(win, pointer, winner);
turnCount++;
}
//return winner;
}

public static void winCheck (boolean win, Board pointer, String winner)
{
for (int counter = 1; counter <= 3; counter++)
{
if ( pointer.play [counter] [1].compareTo(pointer.x) > 0 && pointer.play [counter] [2].compareTo(pointer.x) > 0 && pointer.play [counter] [3].compareTo(pointer.x) > 0)
{
win = true;
winner = pointer.getName1();
win(winner, pointer);
}
else if (pointer.play [1] [counter].compareTo(pointer.x) > 0 && pointer.play [2] [counter].compareTo(pointer.x) > 0 && pointer.play [3] [counter].compareTo(pointer.x) > 0)
{
win = true;
winner = pointer.getName1();
win(winner, pointer);
}
}
//return win;

}

SpotChecks 1 和 2 是检查玩家是否已经下棋的方法。我认为问题出在 WinCheck 方法中。如果有人能帮助我,那就太好了!第一次发帖,如有错误请多多包涵。

最佳答案

您正在修改参数win在方法winCheck中并且您期望这会更改局部变量 win在方法game中。但事实并非如此 - Java 按值传递方法参数,因此 winwinCheck是一个副本,任何更改都不会反射(reflect)回来。您可以将方法的返回类型设置为 winCheck一个boolean .

public static boolean winCheck (boolean win, Board pointer, String winner)
{
// Other code is unchanged

return win;
}

在你的 game 中方法,您更改方法的任何调用 winCheck至:

win = winCheck(...);

关于java - Tic Tac Toe 程序未确定获胜者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37461238/

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