Problem 1 Tiotactoe Write the function implementatios for a
Solution
#include <iostream>
using namespace std;
struct ticTacToeBoard{
int curr_player; //1 or -1
int points[4*4]; // 0 for \'\', 1 for \'X\', -1 for \'O\'
};
void printBoard( ticTacToeBoard board ){
for(int j = 0; j < 4; j++){
for(int i = 0; i < 4; i++){
cout << \"|\";
if( board.points[ i*4 +j ] == 0 ){ cout << \" \"; }
else if( board.points[ i*4 + j ] == 1 ){ cout << \"X\"; }
else{ cout << \"O\"; }
}
cout << \"|\" << endl;
}
}
void initBoard( ticTacToeBoard& board ){
board.curr_player = 1;
for(int i = 0; i < 4; i++){
for(int j =0; j < 4; j++){
board.points[ i*4 + j ] = 0;
}
}
}
bool isEmpty( ticTacToeBoard board, int x, int y ){ return board.points[ (x-1)*4 + (y-1) ] == 0; }
void mark( ticTacToeBoard& board, int x, int y){
if( isEmpty(board,x,y) ){
board.points[ (x-1)*4 + (y-1) ] = board.curr_player;
}
}
bool boardFull( ticTacToeBoard board ){
for(int i = 0; i < 16; i++){
if( board.points[i] == 0 ){ return false; }
}
return true;
}
bool winnerHelper( ticTacToeBoard board, int player ){
for(int i = 0; i < 4; i++ ){
if( (board.points[i*4 + 0] == player && board.points[i*4 + 1] == player) &&
(board.points[i*4 + 2] == player && board.points[i*4 + 3] == player ) ){
return true;
}
}
for(int i = 0; i < 4; i++ ){
if( (board.points[0*4 + i] == player && board.points[1*4 + i] == player) &&
(board.points[2*4 + i] == player && board.points[3*4 + i] == player ) ){
return true;
}
}
if( (board.points[ 0*4 + 0 ] == player && board.points[ 1*4 + 1] == player) &&
(board.points[2*4 + 2] == player && board.points[ 3*4 + 3] == player ) ){
return true; }
if( (board.points[ 0*4 + 3 ] == player && board.points[ 1*4 + 2] == player) &&
(board.points[2*4 + 1] == player && board.points[ 3*4 + 0] == player ) ){
return true; }
return false;
}
int winner( ticTacToeBoard board ){
if( winnerHelper( board, 1 ) ){ return 1; }
if( winnerHelper( board, -1 )){ return -1; }
return 0;
}
int main(){
ticTacToeBoard board;
initBoard( board );
int x,y;
while( winner(board) == 0 && !boardFull(board) ){
printBoard( board );
cout << \"Player \" << board.curr_player << \" \" << \": Enter your move x y \" << endl;
cin >> x >> y;
mark( board, x , y );
board.curr_player *= -1;
}
printBoard( board );
int win = winner( board );
if( win == 0 ){ cout << \"DRAW!!!\" << endl; }
cout << \"Player \" << win << \" wins!!!\" << endl;
}

