Sei sulla pagina 1di 2

//preprocessor directives & headers.

#include <iostream> //utilized to instate basic I/O functionality.


#include <iomanip> //required to use various useful manipulators.
#include "TicTacToe.h" //includes header file which contains class with prototyped functions.

//standard library
using namespace std; //allows the use of cout & endl without "std::" prefix.
char matrix[3][3] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; //TicTacToe board array labeled
'matrix'.
char player = 'X'; //initializes player as 'X'

//function formats array to 3 by 3


void TicTacToe::drawGrid(){
for (int row = 0; row < 3; row++){
for (int col = 0; col < 3; col++){
cout << setw(3) << matrix[row][col];
}
cout << endl;
}
}

void TicTacToe::input(int num){


int a; //initializes variable 'a'.

//prompts the user for position on TicTacToe & saves input to 'a'.
cout << "Enter the number of the desired position: ";
cin >> a;

//assigns players input to corresponding array location.


if (a == 1)
matrix[0][0] = player;
else if (a == 2)
matrix[0][1] = player;
else if (a == 3)
matrix[0][2] = player;
else if (a == 4)
matrix[1][0] = player;
else if (a == 5)
matrix[1][1] = player;
else if (a == 6)
matrix[1][2] = player;
else if (a == 7)
matrix[2][0] = player;
else if (a == 8)
matrix[2][1] = player;
else if (a == 9)
matrix[2][2] = player;
}

//switches player to opposite when function is called.


void TicTacToe::togglePlayer(){
if (player == 'X')
player = 'O';
else
player = 'X';
}

//determines win conditions.


char TicTacToe::win()
{
//first player
if (matrix[0][0] == 'X' && matrix[0][1] == 'X' && matrix[0][2] == 'X')
return 'X';
if (matrix[1][0] == 'X' && matrix[1][1] == 'X' && matrix[1][2] == 'X')
return 'X';
if (matrix[2][0] == 'X' && matrix[2][1] == 'X' && matrix[2][2] == 'X')
return 'X';

if (matrix[0][0] == 'X' && matrix[1][0] == 'X' && matrix[2][0] == 'X')


return 'X';
if (matrix[0][1] == 'X' && matrix[1][1] == 'X' && matrix[2][1] == 'X')
return 'X';
if (matrix[0][2] == 'X' && matrix[1][2] == 'X' && matrix[2][2] == 'X')
return 'X';

if (matrix[0][0] == 'X' && matrix[1][1] == 'X' && matrix[2][2] == 'X')


return 'X';
if (matrix[2][0] == 'X' && matrix[1][1] == 'X' && matrix[0][2] == 'X')
return 'X';

//second player
if (matrix[0][0] == 'O' && matrix[0][1] == 'O' && matrix[0][2] == 'O')
return 'O';
if (matrix[1][0] == 'O' && matrix[1][1] == 'O' && matrix[1][2] == 'O')
return 'O';
if (matrix[2][0] == 'O' && matrix[2][1] == 'O' && matrix[2][2] == 'O')
return 'O';

if (matrix[0][0] == 'O' && matrix[1][0] == 'O' && matrix[2][0] == 'O')


return 'O';
if (matrix[0][1] == 'O' && matrix[1][1] == 'O' && matrix[2][1] == 'O')
return 'O';
if (matrix[0][2] == 'O' && matrix[1][2] == 'O' && matrix[2][2] == 'O')
return 'O';

if (matrix[0][0] == 'O' && matrix[1][1] == 'O' && matrix[2][2] == 'O')


return 'O';
if (matrix[2][0] == 'O' && matrix[1][1] == 'O' && matrix[0][2] == 'O')
return 'O';

return '/';
}

Potrebbero piacerti anche