我在Tic Tac Toe Java程序的代码中遇到了挫折。每次我运行它,游戏板打印3次,第二次打印,X都填写一行表示玩家X获胜。我一直试图解决这个问题,但我仍然无法找到问题。我要问的是,代码打印出来的主要问题是什么,而不是填写内容?
我希望我正确格式化。
import java.util.Scanner;
public class TicTacToeWork {
//Variable declaration.
public static char[][] GameBoard = new char[3][3];
public static Scanner keyboard = new Scanner(System.in);
public static int column, row;
public static char PlayerTurn = 'X';
public static void main(String args[]) {
for (int i = 0; i > 3; i++) {
for (int j = 0; j < 3; j++) {
GameBoard[i][j] = '_';
}
}
System.out.println("Enter coordinates of row then column to choose your space.");
Playing();
}
public static void Playing() {
boolean PlayerPlaying = true;
while (PlayerPlaying) {
boolean playing = true;
while (playing) {
row = keyboard.nextInt() - 1;
column = keyboard.nextInt() - 1;
GameBoard[row][column] = PlayerTurn;
if (EndGame(row, column)) {
playing = false;
System.out.println("Game over player " + PlayerTurn + " wins!");
}
BoardPrint();
if (PlayerTurn == 'X') {
PlayerTurn = 'O';
} else {
PlayerTurn = 'X';
}
}
}
}
public static void BoardPrint() {
//Print out the game board.
for (int i = 0; i < GameBoard.length; i++) {
for (int n = 0; n < 3; n++) {
System.out.println();
for (int j = 0; j < 3; j++) {
if (j == 0) {
System.out.print("| ");
}
System.out.print(GameBoard[i][j] + " | ");
}
}
System.out.println();
}
System.out.println();
}
public static boolean EndGame(int RowMove, int ColumnMove) {
//Deciding factors on who wins and ties.
if (GameBoard[0][ColumnMove] == GameBoard[1][ColumnMove]
&& GameBoard[1][ColumnMove] == GameBoard[2][ColumnMove]) {
return true;
}
if (GameBoard[RowMove][0] == GameBoard[1][RowMove]
&& GameBoard[RowMove][0] == GameBoard[RowMove][2]) {
return true;
}
if (GameBoard[0][0] == GameBoard[1][1] && GameBoard[0][0] == GameBoard[2][2]
&& GameBoard[1][1] != '_') {
return true;
}
if (GameBoard[0][2] == GameBoard[1][1] && GameBoard[0][2] == GameBoard[2][0]
&& GameBoard[1][1] != '_') {
return true;
} else {
return false;
}
}
}
答案 0 :(得分:0)
你的BoardPrint方法都错了。你必须做这样的事情..
public static void BoardPrint() {
System.out.println("-------------");
for (int i = 0; i < 3; i++) {
System.out.print("| ");
for (int j = 0; j < 3; j++) {
System.out.print(GameBoard[i][j] + " | ");
}
System.out.println();
System.out.println("-------------");
}
您还必须重做支票以获得胜利。
一点提示..你没有正确使用布尔方法。这句话if(EndGame(row, column))
表示如果EndGame为真则停止游戏。您设置方法的方式是没有正确地进行检查。你不得不说“如果不是真的” - 所以它看起来像这样if(!EndGame(row, column))
还有其他一些错误,但这应该会给你一个完成项目的良好开端。