嗨大家我真的需要帮助完成我的任务。我试过这样做,但我无法弄清楚。
启动板:
1 2 3
4 5 6
7 8 9
结果欲望:
x 2 3
o x 6
7 o x
但每次执行时,只要有胜利者,我总会得到以下信息:
x 2 3
o x 6
7 o 9
最后,如何计算赢得最多的玩家的胜率?
限制:
您必须在井字游戏板上使用2D阵列。 (我知道我没有使用2D数组,因为我无法弄清楚如何使编译器接受来自2D数组的1-9输入。)
您无法使用类来解决此问题。
如果您愿意,可以使用静态方法。
import java.util.Scanner;
public class TicTacToe { public static String answer = "yes";
public static Scanner input = new Scanner(System.in);
public static String getName(int noPlayer) {
System.out.print("Enter name of Player " + noPlayer + ": ");
return input.next();
}
public static int getMove(String board[], String player) {
printBoard(board);
System.out.print("Enter move for " + player + ": ");
int move = input.nextInt() - 1;
while (moveTaken(board, move)) {
System.out.println("Move taken.");
System.out.print("Enter move for " + player + ": ");
move = input.nextInt() - 1;
}
return move;
}
public static String gameResult(String board[]) {
final int checkWin[][] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
{0, 3, 6}, {1, 4, 7}, {2, 5, 8},
{0, 4, 8}, {2, 4, 6}};
for (int[] i: checkWin) {
if (board[i[0]].equals(board[i[1]]) && board[i[0]].equals(board[i[2]]) && board[i[1]].equals(board[i[2]])) {
if (board[i[0]].equals("O")) {
return "X wins";
}
else {
return "O wins";
}
}
}
if (!board[0].equals("1") && !board[1].equals("2") && !board[2].equals("3") &&
!board[3].equals("4") && !board[4].equals("5") && !board[5].equals("6") &&
!board[6].equals("7") && !board[7].equals("8") && !board[8].equals("9")) {
return "draw";
}
return "not completed";
}
public static boolean moveTaken(String board[], int move) {
if (board[move].equals("O") || board[move].equals("X")) {
return true;
}
return false;
}
public static void printBoard(String board[]) {
System.out.println(" " + board[0] + " " + board[1] + " " + board[2] +
"\n" +
" " + board[3] + " " + board[4] + " " + board[5] +
"\n" +
" " + board[6] + " " + board[7] + " " + board[8]);
}
public static void conclusion(String result, String pO, String pX) {
if (result.equals("O wins")) {
System.out.println(pO + " wins!");
}
else if (result.equals("X wins")) {
System.out.println(pX + " wins!");
}
else {
System.out.println("Draw.");
}
}
public static void main(String args[]) {
String X = getName(1);
String O = getName(2);
int count = 1;
do{
String nextPlayer = X;
String board[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
int move;
while (gameResult(board).equals("not completed")) {
move = getMove(board, nextPlayer);
if (nextPlayer == X) {
board[move] = "X";
nextPlayer = O;
}
else {
board[move] = "O";
nextPlayer = X;
}
}
System.out.println("game up to date: " + count);
conclusion(gameResult(board), X, O);
System.out.println("Do you want to play again? yes or no");
answer = input.next();
count++;
}
while(answer.equalsIgnoreCase("yes"));
}
}
答案 0 :(得分:0)
您只能在执行移动之前在getMove
中打印电路板。因此,永远不会显示最后一步。
您应该在游戏结束时添加对printBoard
的通话。
这里有一个可以添加它的地方:
...
System.out.println("game up to date: " + count);
printBoard(board);
conclusion(gameResult(board), X, O);
...