You are on page 1of 2

Tic tac toe game in C++

/*Zeeshan ahmad BSEE01113069 sect. B Comp. prog assignment 1 march 2012*/


#include <iostream> #include "conio.h" using namespace std; int matrix[3][3];

void settozero() {for(int y=0;y<=2;y++) for(int z=0;z<=2;z++) matrix[y][z]=0;} void printmatrix() {for(int y=0;y<=2;y++){ for(int z=0;z<=2;z++) cout<<" "<<matrix[y][z]; cout<<endl;}} void inputvalue(int plr){ int x=1,row,col; cout<<"\n player "<<plr; do{ cout<<"\n enter row number ";cin>>row; cout<<"\n enter coloumn number ";cin>>col; if(row<1 || row>3 || col<1 || col>3) {cout<<"\n enter valid value between 1-3 \n";x=1;} else if(matrix[row-1][col-1]==0) {matrix[row-1][col-1]=plr;x=0;} else {cout<<"\n already filled choose another \n";} }while(x); } int check(int plr) { int check=0;
// check all rows for consective same value

for(int y=0;y<=2;y++){ for(int z=0;z<=2;z++) check+=(matrix[y][z]==plr); if(check==3){return(plr);} else {check=0;} }


// check all coloumns for consective same value

for(int y=0;y<=2;y++){ for(int z=0;z<=2;z++) {check+=(matrix[z][y]==plr);} if(check==3){return(plr);} else {check=0;} }

Tic tac toe game in C++


// check main diagonal for consective same value

for(int z=0;z<=2;z++) {check+=(matrix[z][z]==plr);} if(check==3){return(plr);} else {check=0;}


// check secondry diagonal for consective same value

for(int z=0;z<=2;z++) {check+=(matrix[z][2-z]==plr);} if(check==3){return(plr);} else {check=0;} /* if check's value becomes 3 it means
there are 3 consecutive marks according to rule of game*/

return(0); }

void play(){
int i,j,player,win;
//loop from 0 to 8 runs maximum at 9 times as there are only 9 possible entries in a game

for( i=0;i<=8;i++) {
// for producing consecutive 1 and 2 for labely player 1 and player 2 get value for player PLAYER

player=i%2+1; inputvalue(player); printmatrix(); win=check(player);


// if win is not zero it means function has returned some players index who has won and breaks the loop

if(win!=0){cout<<" player "<<win<<" wins \n\n\n\n\n";break ;} }if(win==0){cout<<"\n game tie \n";}


// even after complition of game if win is still zero then it means that game is tie

void main(){ char playmore; settozero(); printmatrix();


do{
//using do while loop so keep the program running till the user want to play

play(); cout<<" \n playmore y/n

";playmore=getch();

}while(playmore=='y' || playmore=='Y'); getch();}

You might also like