[英]Java tic tac toe
嗨,我正在写井字游戏。 我已经在代码中的注释中阐明了我需要的内容。 我现在遇到的问题是制作getMove方法。 我假设在按行和列后需要在if / else语句中调用getMove方法吗?
我不确定如何获取行/列号并将其放入用户输入的板中。
这是我的代码:
import java.util.*;
public class TicTac{
//declare a constant variable
public static final int SIZE = 3; //size of each row and each column
public static void main(String[] args) {
//initialize the board
char[][] board = new char[3][3];
//display the board
displayBoard(board);
//prompt for the first player
//determine if X or O is pressed
System.out.println("Who wants to go first (X or O)? ");
Scanner xOrO = new Scanner(System.in);
String entOp = xOrO.nextLine();
char enterOp = entOp.charAt(0);
if (enterOp == 'X'){
System.out.println("Enter a row (0,1,2) for player X: ");
Scanner enterRow = new Scanner(System.in);
int fTurn = enterRow.nextInt();
System.out.println("Enter a column (0,1,2) for player X: ");
Scanner enterCol = new Scanner(System.in);
int fCol = enterCol.nextInt();
} else if (enterOp == 'O') {
System.out.println("Enter a row (0,1,2) for player O: ");
Scanner enterRow = new Scanner(System.in);
int fTurn = enterRow.nextInt();
System.out.println("Enter a column (0,1,2) for player X: ");
Scanner enterCol = new Scanner(System.in);
int fCol = enterCol.nextInt();
} else {
System.out.println("Must enter either X or O");
}
//and display the board
//displayBoard(board);
}
//initializeBoard method
//displayBoard method
public static void drawLine() {
for (int i = 0; i <= 9 * SIZE; i++) {
System.out.print("-");
}
System.out.println();
}
public static void displayBoard(char[][] board) {
drawLine();
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
System.out.print("| " + board[i][j] + " ");
}
System.out.println("|");
drawLine();
}
System.out.println();
}
//getMove method: to prompt the current player for target position. And place the mark in the position if the position is available.
// public static void getMove() {
//
//
//
//
//
// }
//findWinner method: after each move, check the board see if there is a winner
//hasEmptyCell method: check if there is still empty spot in the board
}
我会尝试像这样的举动。 请记住,自从我玩过Java以来,已有一点时间。 我假设2D char数组以空值开头。 我建议将声明更改为,然后将其移至全局:
char[][] board = {{'', '', ''},{'', '', ''},{'', '', ''}};
然后,在第二次读取完成后,我将这样调用getMove:
int x = Integer.parseInt(firstTurn);
int y = Integer.parseInt(firstCol);
getMove(x, y, 'X');
您可能想捕获一个异常,因为您不知道用户是否会实际输入整数。 某种循环(例如while)可以很好地做到这一点。
您的getMove函数应如下所示:
public static bool getMove(int x, int y, char player) {
if (board[x][y] == '') {
board[x][y] = player;
return true; //Here you are returning true to show the spot was available.
}
return false; //And here you are returning false to show the spot was not available.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.