write a C++ program of tic tac toe game in 2-D
Answers
Explanation:
//tic tac toe game
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
//#include <iomanip>
//using std::setw;
int main()
{
// char square[3] [3];
char sq1('1');
char sq2('2');
char sq3('3');
char sq4('4');
char sq5('5');
char sq6('6');
char sq7('7');
char sq8('8');
char sq9('9');
int player(1);//player
bool gameover(true);
do
{
cout<< sq1 << "|" << sq2 << "|" << sq3 << "|"<<endl;
cout<< "----"<<endl;
cout<< sq4 << "|" << sq5 << "|" << sq6 << "|"<<endl;
cout<< "----"<<endl;
cout<< sq7 << "|" << sq8 << "|" << sq9 << "|"<<endl;
char playermark;//playersymbol
if (player == 1)
{
playermark = 'X';
}
else
{
playermark = 'O';
}
cout<<"It is player "<< player << "'s turn."<<endl;
bool realmove;
do
{
char nextmove;
cin>> nextmove;
realmove = true;
if (nextmove == '1' && sq1 == '1')
{
sq1 = playermark;
}
else if (nextmove == '2' && sq2 == '2')
{
sq2 = playermark;
}
else if (nextmove == '3' && sq3 == '3')
{
sq3 = playermark;
}
else if (nextmove == '4' && sq4 == '4')
{
sq4 = playermark;
}
else if (nextmove == '5' && sq5 == '5')
{
sq5 = playermark;
}
else if (nextmove == '6' && sq6 == '6')
{
sq6 = playermark;
}
else if (nextmove == '7' && sq7 == '7')
{
sq7 = playermark;
}
else if (nextmove == '8' && sq8 == '8')
{
sq8 = playermark;
}
else if (nextmove == '9' && sq9 == '9')
{
sq9 = playermark;
}
else
{
cout<< "You have entered a non-alid move. Please enter a valid move."<<endl;
realmove = false;
}
}
while(! realmove);
gameover = false;
bool wongame = true;
//something missing here??
if (sq1 != '1')
{
if (sq2 == sq1 && sq3 == sq1)
{
gameover = true;
}
if (sq4 == sq1 && sq7 == sq1)
{
gameover = true;
}
}
if (sq5 != '5')
{
if (sq1 == sq5 && sq9 == sq5)
{
gameover = true;
}
if (sq2 == sq5 && sq8 == sq5)
{
gameover = true;
}
if (sq4 == sq5 && sq6 == sq5)
{
gameover = true;
}
if (sq3 == sq5 && sq7 == sq5)
{
gameover = true;
}
}
if (sq9 != '9')
{
if (sq3 == sq9 && sq6 == sq9)
{
gameover = true;
}
if (sq7 == sq9 && sq8 == sq9)
{
gameover = true;
}
}
if (sq1 != '1' && sq2 != '2' && sq3 != '3' && sq4 != '4' && sq5 != '5' & sq6 != '6' && sq7 != '7' && sq8 != '8' && sq9 != '9' && !gameover)
{
gameover = true;
wongame = false;
}
if (gameover)
{
if (wongame)
{
cout<<"Player "<< layer <<" won the game!"<<endl; }
cout<< sq1 << "|" << sq2 << "|" << sq3 << "|"<<endl;
cout<< "----"<<endl;
cout<< sq4 << "|" << sq5 << "|" << sq6 << "|"<<endl;
cout<< "----"<<endl;
cout<< sq7 << "|" << sq8 << "|" << sq9 << "|"<<endl;
cout<<"Would you like to play again? (y or n)"<<endl;
char playagain;
cin>> playagain;
if (playagain == 'y')
{
gameover = false;
char sq1('1');
char sq2('2');
char sq3('3');
char sq4('4');
char sq5('5');
char sq6('6');
char sq7('7');
char sq8('8');
char sq9('9');
}
player = 1;
}
else
{
if (player == 1)
{
player = 2;
}
else
{
player = 1;
}
}
} while (!gameover);
return 0;
}