gpt4 book ai didi

java - Tic Tac Toe 获胜者检查器问题

转载 作者:行者123 更新时间:2023-12-01 21:40:02 28 4
gpt4 key购买 nike

我对编码和 Java 比较陌生,在我的 CS-173 类(class)中,我的任务是创建一个 Tic Tac Toe 游戏。然而,当谈到创建确定获胜者的方法时,每当我获得“胜利”时,代码都不会运行说我赢了。我确实有代码来检查每种获胜方式,但是,我从代码中提取了它以进行一些个人故障排除。另外,我对错误的代码表示歉意。

     public static void playGame(char[][] board, int size){
Scanner input = new Scanner(System.in);

int turn = 0;
int spaces = board.length * board.length;
boolean valid = false;
boolean winner = false;

for (int i = 0; i<spaces; i++){
int startchecker = 3;
int xcord = 0;
int ycord = 0;

do{
do{

System.out.println("Player 1 please type your coordinates with a space");
xcord = input.nextInt();
ycord = input.nextInt();


valid = isValid (board, xcord, ycord);

if(i >= spaces){

}


}while(!valid);
board[xcord][ycord] = 'X';
printBoard(board);
winner = isWinner(board);

do{
System.out.println("Player 2 please type your coordinates with a space");
xcord = input.nextInt();
ycord = input.nextInt();
valid = isValid (board, xcord, ycord);

winner = isWinner(board);

}while(!valid);
board[xcord][ycord] = 'O';
printBoard(board);



if(i >= spaces){
winner = true;
System.out.println("It is a tie!");


}
}while(!winner);

}
}


public static boolean isWinner (char[][] board){
boolean determiner = false;
int XCounter = 0;
int OCounter = 0;
int size = board.length-1;
int winner = 3;


//Check Horizontal
for(int j = 0; j > size; j++){
for(int i = 0; i > size; i++){
if(board[i][j]=='X'){
XCounter++;

}
else if(board[i][j]=='O'){
OCounter++;

}
if(XCounter == winner){
determiner = true;
System.out.println("Player 1 Wins!");
}
else if(OCounter == winner){
System.out.println("Player 2 Wins!");
determiner = true;
}
}
}

return determiner;
}

最佳答案

您的 isWinner 方法不会检查所有获胜方式。

为了清晰起见,我建议使用 2 个 for 循环(一个用于水平线,另一个用于垂直线),并使用 2 个 if 语句(循环外部)来检查对角线。

例如,

for(int i=0; i<size; i++){
boolean flag = true; // Assume this line is a winning line
for(int j=0; j<size; j++){ // Check each tile to see if it has a tile
// Set the flag to false when it is not the tile you're looking for
}
}

关于java - Tic Tac Toe 获胜者检查器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58793517/

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