1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include<iostream>
#include<vector>
using namespace std;
void DisplayBoard(char Board);
void GetMove(int&row,int&col,const char Board);
char Winner(const char Board);
//--------------------------------------------------------------
int main()
{
char Board[4][4];
for(int row=0;row<3;row++){
for(int col=0;col<3;col++){
Board[row][col]=' ';
}
}
char CurrPlayer;
int row,col,nummoves=0;
CurrPlayer = 'X';
do{
DisplayBoard(Board[4][4]);
GetMove(row,col,Board[4][4]);
Board[row][col]=CurrPlayer;
nummoves++;
if(CurrPlayer=='X')
CurrPlayer='O';
else
CurrPlayer='X';
}while((Winner(Board[4][4])==' ')&&(nummoves!=9));
DisplayBoard(Board[4][4]);
cout<<"Winner is "<<Winner(Board[4][4])<<endl;
return (0);
}
//--------------------------------------------------------------
void DisplayBoard(char Board)
{
for(int row=0;row<2;row++){
for(int col=0;col<2;col++)
cout<<"["<<Board[row][col]<<"]";
cout<<endl;
}
}
//--------------------------------------------------------------
void GetMove(int&row,int&col,const char Board)
{
while(true){
cout<<"Enter row of move(0,1,2): ";cin>>row;
cout<<"Enter col of move(0,1,2): ";cin>>col;
if((row>=0)&&(row<3)&&
(col>=0)&&(col<3)&&
(Board[row][col]==' '))
break;
cout<<"Invalid move,please re-enter!"<<endl;
}
}
//--------------------------------------------------------------
char Winner(const char Board)
{
int row,col;
for(row=0;row<3;row++){
if((Board[row][0]==Board)
&&(Board[row][1]==Board[row][2])
&&(Board[row][0]!=' '))
return(Board[row][0]);
}
for(col=0;col<3;col++){
if((Board[0][col]==Board[1][col])
&&(Board[1][col]==Board[2][col])
&&(Board[0][col]!=' '))
return(Board[col][0]);
}
if((Board[0][0]==Board[1][1])
&&(Board[1][1]==Board[2][2])
&&(Board[0][0]!=' '))
return(Board[0][0]);
if((Board[0][2]==Board[1][1])
&&(Board[1][1]==Board[2][0])
&&(Board[0][2]!=' '))
return(Board[0][2]);
return ' ';
}
|