日期:2014-05-20 浏览次数:20808 次
import java.util.Scanner;
/**
* Tic-Tac-Toe: Two-player console, non-graphics, non-OO version.
* All variables/methods are declared as static (belong to the class)
* in the non-OO version.
*/
public class Tic {
// Name-constants to represent the seeds and cell contents
public static final int EMPTY = 0;
public static final int CROSS = 1;
public static final int NOUGHT = 2;
// Name-constants to represent the various states of the game
public static final int PLAYING = 0;
public static final int DRAW = 1;
public static final int CROSS_WON = 2;
public static final int NOUGHT_WON = 3;
// The game board and the game status
public static final int ROWS = 3, COLS = 3; // number of rows and columns
public static int[][] board = new int[ROWS][COLS]; // game board in 2D array
// containing (EMPTY, CROSS, NOUGHT)
public static int currentState; // the current state of the game
// (PLAYING, DRAW, CROSS_WON, NOUGHT_WON)
public static int currentPlayer; // the current player (CROSS or NOUGHT)
public static int currntRow, currentCol; // current seed's row and column
public static Scanner in = new Scanner(System.in); // the input Scanner
/** The entry main method (the program starts here) */
public static void main(String[] args) {
// Initialize the game-board and current status
initGame();
// Play the game once
do {
playerMove(currentPlayer); // update currentRow and currentCol
updateGame(currentPlayer, currntRow, currentCol); // update currentState
printBoard();
// Print message if game-over
if (currentState == CROSS_WON) {
System.out.println("'X' won! Bye!");
} else if (currentState == NOUGHT_WON) {
System.out.println("'O' won! Bye!");
} else if (currentState == DRAW) {
System.out.println("It's a Draw! Bye!");
}
// Switch player
currentPlayer = (currentPlayer == CROSS) ? NOUGHT : CROSS;
} while (currentState == PLAYING); // repeat if not game-over
}
/** Initialize the game-board contents and the current states */
public static void initGame() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
board[row][col] = EMPTY; // all cells empty