#include <iostream>
#include <iomanip>
using namespace std;

#include "gameBoard.h"

gameBoard::gameBoard() {
	for ( int r=0; r < ROWS; r++ ) {
		for ( int c=0; c < COLS; c++ ) {
			cell[r][c]=EMPTY_CELL;
		}
	}
}

void gameBoard::display() {
	system("cls");
	cout << endl;
	cout << "    A   B   C\n";
	for ( int r=0; r < ROWS; r++ ) {
		cout << "  +---+---+---+ \n";
		cout << " " << (r+1) << "|";
		for ( int c=0; c < COLS; c++ ) {
			cout << " " << cell[r][c] << " |";
		}
		cout << endl;
	}
	cout << "  +---+---+---+ \n";
}

bool gameBoard::captureCell(int row, int col, int playerNum) {

	bool validMove=true;

	if ( playerNum < 0 || playerNum >= PLAYERS ) {
		cout << "\nInvalid player number\n";
		validMove=false;
	}
	if ( row < 0 || row >= ROWS ) {
		cout << "\nInvalid row\n";
		validMove=false;
	}
	if ( col < 0 || col >= COLS ) {
		cout << "\nInvalid column\n";
		validMove=false;
	}
	if ( cell[row][col] != EMPTY_CELL ) {
		cout << "\nThat cell is not empty\n";
		validMove=false;
	}

	if ( validMove ) {
		cell[row][col]=PLAYER_CELL[playerNum];
	}

	return validMove;
}

int gameBoard::getGameState() {
	/* return values:
	   -1 = game is still in progress
	   -2 = game is a tie
	   any positive value (p): game is over with player (p) as the winner
   */

	// check each player for possible winning positions
	for ( int p=0; p < PLAYERS; p++ ) {
		if ( playerHasWon(p) ) { 
			return p;
		}
	}

	// check for empty cells
	for ( int r=0; r < ROWS; r++ ) {
		for ( int c=0; c < COLS; c++ ) {
			if ( cell[r][c] == EMPTY_CELL ) {
				return GAME_IN_PROGRESS;
			}
		}
	}

	// only possibility left is a tie, no empty cells and no winners
	return GAME_TIE;

}

bool gameBoard::playerHasWon(int playerNum) {

	// check each row
	for ( int r=0; r < ROWS; r++ ) 
	{
		if ( 
			cell[r][0] == PLAYER_CELL[playerNum] &&
			cell[r][1] == PLAYER_CELL[playerNum] &&
			cell[r][2] == PLAYER_CELL[playerNum]
			) return true;			
	}

	// check each column
	for ( int c=0; c < COLS; c++ ) 
	{
		if ( 
			cell[0][c] == PLAYER_CELL[playerNum] &&
			cell[1][c] == PLAYER_CELL[playerNum] &&
			cell[2][c] == PLAYER_CELL[playerNum]
			) return true;
			
	}

	// check the two diagonals
	if ( 
		cell[0][0] == PLAYER_CELL[playerNum] &&
		cell[1][1] == PLAYER_CELL[playerNum] &&
		cell[2][2] == PLAYER_CELL[playerNum] 
	 ) return true;

	if ( 
		cell[0][2] == PLAYER_CELL[playerNum] &&
		cell[1][1] == PLAYER_CELL[playerNum] &&
		cell[2][0] == PLAYER_CELL[playerNum] 
	 ) return true;

	 return false;
}

bool gameBoard::cellIsEmpty(int row, int col)
{
	if ( cell[row][col] == EMPTY_CELL ) 
		return true;
	else
		return false;
}
bool gameBoard::isCellMine(int row, int col, int playerNum)
{
	if ( cell[row][col] == PLAYER_CELL[playerNum] ) 
		return true;
	else
		return false;
}