Created
April 25, 2019 16:59
-
-
Save RinkuMonani/5f573372f771067b54abe7d0e9a1c93c to your computer and use it in GitHub Desktop.
This is a simple c++ program for 2 player game tic tac toe. Both the players in this program are manual.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<stdlib.h> | |
using namespace std; | |
char array[9],turn = 'X'; //turn determines which player has to play | |
int chance = 1; | |
void display(){ | |
int i; | |
cout<<endl; | |
for(i=1;i<=9;++i){ | |
cout<<"\t"<<array[i]<<" "; //just an indentation thing | |
if(i%3 == 0) | |
cout<<"\n\n"; | |
} | |
} | |
void check(){ | |
int i; | |
for(i=1;i<=9;i=i+3){ //check rows | |
if(array[i] == turn && array[i] == array[i+1] && array[i] == array[i+2]){ | |
cout<<"\n\n**"<<turn<<" WINS ** \n\n"; | |
display(); | |
exit(1); | |
} | |
} | |
for(i=1;i<=3;++i){ //check columns | |
if(array[i] == turn && array[i] == array[i+3] && array[i] == array[i+6]){ | |
cout<<"\n\n**"<<turn<<" WINS ** \n\n"; | |
display(); | |
exit(1); | |
} | |
} | |
if(array[1] == turn && array[1] == array[5] && array[1] == array[9]){ //checks diagonals | |
cout<<"\n\n**"<<turn<<" WINS ** \n\n"; | |
display(); | |
exit(1); | |
} | |
if(array[3] == turn && array[3] == array[5] && array[3] == array[7]){ | |
cout<<"\n\n**"<<turn<<" WINS ** \n\n"; | |
display(); | |
exit(1); | |
} | |
} | |
void play(){ | |
int block; | |
cout<<"\nPlayer "<<turn<<" pick a block : "; | |
cin>>block; | |
if(array[block] == 'X' || array[block] == 'O'){ | |
cout<<"\nAlready selected! please enter another choice"; | |
} | |
else{ | |
array[block] = turn; | |
if(chance >=5) | |
check(); | |
chance++; | |
if(chance == 10){ | |
display(); | |
cout<<"\nSorry! game ended! Its a draw\n "; | |
} | |
if(chance % 2 == 0) | |
turn = 'O'; | |
else | |
turn = 'X'; | |
} | |
display(); | |
} | |
int main(){ | |
int i,j=49; | |
cout<<"\nPlayer 1 : X"<<"\nPlayer 2 : O \n"; | |
for(i=1;i<=9;++i){ //initialization to numerals for player conveniece | |
array[i] = (char)j; | |
++j; | |
} | |
display(); | |
while(1) | |
play(); | |
display(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment