// TicTacToe.java
// Description: Game engine for TicTacToe game
// Author: Chris Wilcox
// Date: 4/9/2015

import java.util.Random;

public class TicTacToe { 

    public enum eStatus {
        IN_PROGRESS,
        TIE_GAME,
        COMPUTER_WINS,
        PLAYER_WINS,
    }
    
    // Instance data
    private char board[][];
    private Random random;
    
    // Constructor
    public TicTacToe() {
        
        // Create random
        random = new Random();

        // Allocate board
        board = new char[3][3];
        
        // Initialize board
        initialize();
    }
    
    // Returns board
    public char[][] data() {
        return board;
    }
    
    // Initialize board
    private void initialize() {
        for (int row = 0; row <= 2; ++row) {
            for (int col = 0; col <= 2; ++col) {
                board[row][col] = '-';
            }
        }
    }

    // Computer moves
    public void computer() {

        while (true) {
        
            int row = (int) random.nextInt(3);
            int col = (int) random.nextInt(3);

            // Check occupied
            if (board[row][col] == '-') {
                board[row][col] = 'O';
                break;
            }
        }
    }
    
    // Player moves
    public boolean player(int row, int col) {

        // Check occupied
        if (board[row][col] == '-') {
            board[row][col] = 'X';
            return true;
        }
        return false;
    }

    // Game status
    public eStatus status() {

        // Check tie
        boolean tieGame = true;
        for (int row = 0; row <= 2; ++row)
            for (int col = 0; col <= 2; ++col)
                    if (board[row][col] == '-')
                        tieGame = false;
        // Tie game
        if (tieGame)
            return eStatus.TIE_GAME;
        
        // Player wins
        else if (runOfThree('X'))
            return eStatus.PLAYER_WINS;

        // Computer wins
        else if (runOfThree('O'))
            return eStatus.COMPUTER_WINS;

        return eStatus.IN_PROGRESS;
    }

    // Run of three?
    private boolean runOfThree(char c) {

        // Check rows
        for (int row = 0; row <= 2; ++row) {
            if ((board[row][0] == c) &&
                (board[row][1] == c) &&
                (board[row][2] == c))
                return true;
        }
        
        // Check columns
        for (int col = 0; col <= 2; ++col) {
            if ((board[0][col] == c) &&
                (board[1][col] == c) &&
                (board[2][col] == c))
                return true;
        }
        
        // Check diagonals
        if ((board[0][0] == c) && 
            (board[1][1] == c) &&
            (board[2][2] == c))
            return true;
        if ((board[2][0] == c) && 
            (board[1][1] == c) &&
            (board[0][2] == c))
            return true;

        return false;
    }
}

© 2015 CS160 Colorado State University. All Rights Reserved.