Reference no: EM131103075
Create a Board class using the following code and change the main function so that it uses your class instead of the data and functions it currently uses.
You should not include game-specific code (i.e. TicTacToe code) in your Board class. Your Board class should only include the actual board data (char **data) and the size of the board (int rows, cols) and the functions that operate only on that data. That way, we can reuse our board class for another game.
#include <iostream>
#include <iomanip>
usingnamespacestd;
voidset(char**data,introw,intcol,charvalue)
{
data[row][col]=value;
}
charget(char**data,introw,intcol)
{
returndata[row][col];
}
voidprintLine(intcols)
{
cout<<" ";
for(size_ti=0;i<cols;i++)
{
cout<<"+---";
}
cout<<"+n";
}
voidprint(char**data,introws,intcols)
{
cout<<" ";
for(size_ti=0;i<cols;i++)
{
cout<<" "<<char('A'+i)<<" ";
}
cout<<"n";
for(size_ti=0;i<rows;i++)
{
printLine(cols);
cout<<setw(2)<<i+1<<" ";
for(size_tj=0;j<cols;j++)
{
cout<<"| "<<data[i][j]<<" ";
}
cout<<"|n";
}
printLine(cols);
}
// assumes a 3x3 board
boolcheckGameOverTicTacToe(char**board,charplayer)
{
boolhasEmpty=false;
for(size_ti=0;i<3;i++)
{
for(size_tj=0;j<3&&!hasEmpty;j++)
{
if(get(board,i,j)==' ')
hasEmpty=true;
}
if((get(board,i,0)!=' '&&get(board,i,0)==get(board,i,1)&&get(board,i,1)==get(board,i,2))||(get(board,0,i)!=' '&&get(board,0,i)==get(board,1,i)&&get(board,1,i)==get(board,2,i)))
{
print(board,3,3);
cout<<player<<" wins!n";
returntrue;
}
}
if((get(board,0,0)!=' '&&get(board,0,0)==get(board,1,1)&&get(board,1,1)==get(board,2,2))||(get(board,2,0)!=' '&&get(board,2,0)==get(board,1,1)&&get(board,1,1)==get(board,0,2)))
{
print(board,3,3);
cout<<player<<" wins!n";
returntrue;
}
if(!hasEmpty)
{
print(board,3,3);
cout<<"Tie!n";
returntrue;
}
returnfalse;
}
intmain()
{
// board properties
introws=3;
intcols=3;
// construct the board
char**data=newchar*[rows];
for(inti=0;i<rows;i++)
{
data[i]=newchar[cols];
for(intj=0;j<cols;j++)
data[i][j]=' ';
}
// game loop
charplayer='o';
while(!checkGameOverTicTacToe(data,player))
{
if(player=='x')
player='o';
else
player='x';
print(data,rows,cols);
size_t row,col;
cout<<player<<", enter a row and col: ";
cin>>row>>col;
while(row>2||col>2||get(data,row,col)!=' ')
{
cout<<"Please enter a valid row and col: ";
cin>>row>>col;
}
set(data,row,col,player);
}
return0;
}