-1
我創建了一個可以玩tic tac toe的程序。現在,玩家和機器只是來回玩耍。我需要幫助,創造一種方法,使機器玩家阻止勝利。我知道我需要檢查是否有2個X在一行,一列或對角線上。我如何去做這件事?Tic Tac Toe block獲獎動作
任何幫助,將不勝感激。仍然是編碼的初學者。
下面是代碼:
import java.util.Scanner;
import java.io.PrintStream;
import java.util.Random;
public class TicTacToe
{
static Scanner stdin = new Scanner(System.in);
static PrintStream stdout = System.out;
public static void main(String[] arg)
{
Board bd = new Board();
char currentPlayer = 'X';
while(true) {
getmove(bd, currentPlayer); //puts move on the board
bd.print();
if(bd.won(currentPlayer)) {
stdout.printf("Player %c has won!\n", currentPlayer);
return; //end main
}
if(bd.done()) {
stdout.println("Stalemate!");
return;
}
if(currentPlayer == 'X')
currentPlayer = 'O';
else
currentPlayer = 'X';
}
}
static void getmove(Board bd, char player) {
if(player == 'X') {
usermove(bd);
} else {
machinemove(bd);
}
}
static Random r = new Random(99);
static void machinemove(Board bd) {
int row = r.nextInt(3);
int col = r.nextInt(3);
while(!bd.play(row, col, 'O')) {
row = r.nextInt(3);
col = r.nextInt(3);
}
}
static void usermove(Board bd) {
int row = getpos("row (1,2,3): ");
int col = getpos("col (1,2,3): ");
while(!bd.play(row, col, 'X')) {
stdout.println("Cannot play on non-blank location!");
row = getpos("row (1,2,3): ");
col = getpos("col (1,2,3): ");
}
}
static int getpos(String prompt) {
int i;
stdout.print(prompt);
try {
i = stdin.nextInt();
}
catch(Exception e) {
return getpos(prompt);
}
if(1 <= i && i <= 3)
return i - 1; //our coords in range 0..2
return getpos(prompt);
}
}
class Board {
char[][] b;
int moves;
boolean done() {
return moves == 9;
}
boolean won(char p) { //either 'X' or 'O'
for(int i = 0; i < 3; ++i)
if((eq(i,0,p) && eq(i,1,p) && eq(i,2,p)) ||
(eq(0,i,p) && eq(1,i,p) && eq(2,i,p))
) return true;
if((eq(0,0,p) && eq(1,1,p) && eq(2,2,p)) ||
(eq(0,2,p) && eq(1,1,p) && eq(2,0,p))
) return true;
return false;
}
private boolean eq(int i, int j, char p) {
return b[i][j] == p;
}
Board() {
b = new char[3][3];
for(int r = 0; r < 3; ++r)
for(int c = 0; c < 3; ++c)
b[r][c] = ' ';
}
boolean play(int row, int col, char p) {
if(b[row][col] == ' ') {
b[row][col] = p;
++moves;
return true;
} else return false;
}
void print() {
System.out.println();
System.out.printf(" %c | %c | %c \n", b[0][0], b[0][1], b[0][2]);
System.out.println("-----------");
System.out.printf(" %c | %c | %c \n", b[1][0], b[1][1], b[1][2]);
System.out.println("-----------");
System.out.printf(" %c | %c | %c \n", b[2][0], b[2][1], b[2][2]);
System.out.println();
}
}