Create a Tic tac toe game using c++
The following program is the source code of a game called tic tac toe. The program is implemented using c++.
Code :
#include<iostream> #include<windows.h> using namespace std; char a[9]={'1','2','3','4','5','6','7','8','9'}; char c1,c2; void draw_board() { cout<<"\n\n"; cout<<" "<<a[0]<<" | "<<a[1]<<" | "<<a[2]<<" "; cout<<endl<<" | | "; cout<<"\n-------|-------|-------"; cout<<endl<<" "<<a[3]<<" | "<<a[4]<<" | "<<a[5]<<" "; cout<<endl<<" | | "; cout<<"\n-------|-------|-------"; cout<<endl<<" "<<a[6]<<" | "<<a[7]<<" | "<<a[8]<<" "; cout<<endl<<" | | "; } int check_res() { if(a[0]==a[1] && a[1]==a[2]) { if(a[0]==c1) return 1; else return 2; } else if(a[0]==a[3] && a[3]==a[6]) { if(a[0]==c1) return 1; else return 2; } else if(a[0]==a[4] && a[4]==a[8]) { if(a[0]==c1) return 1; else return 2; } else if(a[1]==a[4] && a[4]==a[7]) { if(a[1]==c1) return 1; else return 2; } else if(a[2]==a[4] && a[4]==a[6]) { if(a[2]==c1) return 1; else return 2; } else if(a[2]==a[5] && a[5]==a[8]) { if(a[2]==c1) return 1; else return 2; } else if(a[3]==a[4] && a[4]==a[5]) { if(a[3]==c1) return 1; else return 2; } else if(a[6]==a[7] && a[7]==a[8]) { if(a[6]==c1) return 1; else return 2; } else return 0; } void play_game() { int c,r; int p; cout<<"\nEnter your choice : \n1.X\t 2.O\n"; cin>>c; if(c==1) { c1='X'; c2='O'; } else if(c==2) { c1='O'; c2='X'; } else { cout<<"\nInvalid choice..."; } c=0; while(c<10) { A: cout<<"\n==>Player 1 turn :"; cout<<"\nEnter your choice : "; cin>>p; if(isdigit(a[p-1])) { c++; a[p-1]=c1; system("cls"); draw_board(); r=check_res(); if(r!=0) break; } else { cout<<"\nAlready filled up"; goto A; } B: cout<<"\n==>Player 2 turn :"; cout<<"\nEnter your choice : "; cin>>p; if(isdigit(a[p-1])) { a[p-1]=c2; system("cls"); draw_board(); r=check_res(); c++; if(r!=0) break; } else { cout<<"\nAlready filled up"; goto B; } } if(r!=0) cout<<"\nPlayer "<<r<<" wins the match"; else cout<<"\nDraw"; } int main() { draw_board(); play_game(); return 0; }
Comments
Post a Comment