【发布时间】:2015-11-16 14:59:53
【问题描述】:
较早的帖子:How do I make my tictactoe program scalable
我试图使井字游戏程序(人类与计算机)具有可扩展性(可以更改棋盘大小)。我之前遇到过大问题,但大部分都解决了。
游戏的规则是基本的井字游戏,但一个不同的规则是,无论棋盘有多大(>= 5 时),玩家或计算机只需连续五个标记即可获胜。
现在,我的程序唯一的破局问题是确定谁赢得了比赛。比赛目前只能以“平局”结束。 (另外我还没有实现“>= 5”)。
具体的问题解释是我需要为“computer wins”和/或“player wins”之类的内容确定获胜者和结束画面。
package tictactoe;
import java.util.Scanner;
import java.util.Random;
public class TicTacToe {
public static int size;
public static char[][] board;
public static int score = 0;
public static Scanner scan = new Scanner(System.in);
/**
* Creates base for the game.
*
* @param args the command line parameters. Not used.
*/
public static void main(String[] args) {
System.out.println("Select board size");
System.out.print("[int]: ");
size = Integer.parseInt(scan.nextLine());
board = new char[size][size];
setupBoard();
int i = 1;
while (true) {
if (i % 2 == 1) {
displayBoard();
getMove();
} else {
computerTurn();
}
// isWon()
if (isDraw()) {
System.err.println("Draw!");
break;
}
i++;
}
}
/**
* Checks for draws.
*
* @return if this game is a draw
*/
public static boolean isDraw() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
/**
* Displays the board.
*
*
*/
public static void displayBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.printf("[%s]", board[i][j]);
}
System.out.println();
}
}
/**
* Displays the board.
*
*
*/
public static void setupBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = ' ';
}
}
}
/*
* Checks if the move is allowed.
*
*
*/
public static void getMove() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.printf("ROW: [0-%d]: ", size - 1);
int x = Integer.parseInt(sc.nextLine());
System.out.printf("COL: [0-%d]: ", size - 1);
int y = Integer.parseInt(sc.nextLine());
if (isValidPlay(x, y)) {
board[x][y] = 'X';
break;
}
}
}
/*
* Randomizes computer's turn - where it inputs the mark 'O'.
*
*
*/
public static void computerTurn() {
Random rgen = new Random(); // Random number generator
while (true) {
int x = (int) (Math.random() * size);
int y = (int) (Math.random() * size);
if (isValidPlay(x, y)) {
board[x][y] = 'O';
break;
}
}
}
/**
* Checks if the move is possible.
*
* @param inX
* @param inY
* @return
*/
public static boolean isValidPlay(int inX, int inY) {
// Play is out of bounds and thus not valid.
if ((inX >= size) || (inY >= size)) {
return false;
}
// Checks if a play have already been made at the location,
// and the location is thus invalid.
return (board[inX][inY] == ' ');
}
}
【问题讨论】:
-
每回合后检查是否有人赢了?
-
@MuratK。根据他的代码(这与他的要求相矛盾),他已经得出了这个结论。在每个玩家/电脑轮换后,他的
while(true)中都有// isWon()。尽管 OP 没有明确提出这个问题,但我假设他想知道如何实现isWon(),其中将检查三个/四个/五个(取决于板的大小)相邻的 X 或 O(水平、垂直或对角线)。同样,这只是我的假设,所以也许 OP 应该稍微编辑一下他的问题,并在isWon()-method 中展示他迄今为止所尝试的内容。
标签: java arrays tic-tac-toe