[英]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.