/* Tic-Tac-Toe program */

#include <iostream.h>
#include <matrix.h>
//#include <lvp\bool.h>

using namespace std;	// October 5, 2001

typedef matrix<char> TTTBoard;

//--------------------------------------------------------------------------------
void DisplayBoard(const TTTBoard &Board)
/*	Displays board
	Post: Board displayed */
{
	for (int Row=0; Row<Board.numrows(); Row++) {
		// Display a row
		for (int Col=0; Col<Board.numcols(); Col ++)
			cout << "[" << Board[Row][Col]<< "]" ;
		cout << endl;
	}
}
//--------------------------------------------------------------------------------
void GetMove(int &Row, int &Col, const TTTBoard &Board)
/*	Obtains a valid move (Row, Col) from user
	Post: Row and Col of matrix returned as valid move */
{
	while (true) {
		cout << "Enter row of move (0, 1, 2): ";
		cin  >> Row;
		cout << "Enter column of move (0, 1, 2): ";
		cin >> Col;
		if ((Row >= 0) && (Row < Board.numrows()) &&
			(Col >= 0) && (Col < Board.numcols()) && (Board[Row][Col] == ' '))
			break;
		cout << "Invalid move, please re-enter!" << endl;
	}
}
//--------------------------------------------------------------------------------
char Winner(const TTTBoard &Board)
/*	Returns X or O indicating the winner. If no winner, a blank is returned.
	If there are multiple winning sets, returns the first one encountered
	Post: X, O, or a blank returned                                                                   */
{
	int Row, Col;
	// Try all rows
	for(Row = 0; Row < Board.numrows(); Row++)
		if (Board[Row][0]==Board[Row][1] &&  Board[Row][1]==Board[Row][2]
			&& Board[Row][0] != ' ')
			return(Board[Row][0]);
	// Try all columns
	for(Col = 0; Col < Board.numcols(); Col++)
		if (Board[0][Col]==Board[1][Col] &&  Board[1][Col]==Board[2][Col]
			&& Board[0][Col] != ' ')
			return(Board[0][Col]);
	// Try one diagonal
	if (Board[0][0]==Board[1][1] &&  Board[1][1]==Board[2][2]
		&& Board[0][0] != ' ')
		return(Board[0][0]);
			// Try the other diagonal
	if (Board[0][2]==Board[1][1] &&  Board[1][1]==Board[2][0]
		&& Board[0][2] != ' ')
		return(Board[0][2]);
	// Return blank, if all others fail
	return(' ');
}
//--------------------------------------------------------------------------------
int main()
{
	TTTBoard Board(3, 3, ' ');
	char CurrPlayer;
	int Row, Col, NumMoves = 0;

	CurrPlayer = 'X';
	do {
		DisplayBoard(Board);
		GetMove(Row, Col, Board);
		Board[Row][Col] = CurrPlayer;
		NumMoves++;
		if (CurrPlayer == 'X')
			CurrPlayer = 'O';
		else
			CurrPlayer = 'X';
	} while ((Winner(Board) == ' ') && (NumMoves != 9));
	DisplayBoard(Board);
	cout << "Winner is " << Winner(Board) << endl;
	return(0);
}

