Sep 21, 2014 at 12:47pm UTC
Hi,so i have made a game of tic tac toe where the user plays against the computer. And so far everything works except, i cant end the game because i am having trouble determining the winner.My code is down below,have a look at it and please let me know what i am doing wrong.
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main(){
char board[3][3];
int row,col;
int r,c,x,y;
int player;
for(row=0;row<3;row++){
for(col=0;col<3;col++){
board[row][col]=' ';
}
}
cout << endl << endl;
for(row=0;row<3;row++){
for(col=0;col<3;col++){
cout << "|" << board[row][col] << "|" ;
}
cout << endl << "|-||-||-|" ;
cout << endl;
}
cout << endl << endl << endl;
bool notGameover=false;
while(!notGameover){
cout << "Enter row: ";
cin >> r;
cout << "Enter column: ";
cin >> c;
bool notvalid=false;
while(!notvalid){
if(r<0 || r>2 || c<0 || c>2){
cout << "The row or column you have entered is wrong.";
cout << endl << endl << endl;
cout << "Re-enter row:";
cin >> r;
cout << "Re-enter column: ";
cin >> c;
}else if(board[r][c]!=' '){
cout << "Invalid move.That space is already occupied.";
cout << endl << endl << endl;
cout << "Re-enter row:";
cin >> r;
cout << "Re-enter column: ";
cin >> c;
}else{
notvalid=true;
}
}
board[r][c]='O';
srand(time(0));
x=rand()%3;
y=rand()%3;
notvalid=false;
while(!notvalid){
if(board[x][y]!=' '){
srand(time(0));
x=rand()%3;
y=rand()%3;
}else{
notvalid=true;
}
}
board[x][y]='X';
for(row=0;row<3;row++){
for(col=0;col<3;col++){
cout << "|" << board[row][col] << "|" ;
}
cout << endl << "|-||-||-|" ;
cout << endl;
}
cout << endl << endl << endl;
if((board[0][0]==board[0][1]&&board[0][1]==board[0][2]&&board[0][0]=='O')||
(board[1][0]==board[1][1]&&board[1][1]==board[1][2]&&board[1][0]=='O')||
(board[2][0]==board[2][1]&&board[2][1]==board[2][2]&&board[2][0]=='O')||
(board[0][0]==board[1][0]&&board[1][0]==board[2][0]&&board[0][0]=='O')||
(board[0][1]==board[1][1]&&board[1][1]==board[2][1]&&board[0][1]=='O')||
(board[0][2]==board[1][2]&&board[1][2]==board[2][2]&&board[0][2]=='O')||
(board[0][0]==board[1][2]&&board[1][1]==board[2][2]&&board[0][0]=='O')||
(board[0][2]==board[1][1]&&board[1][1]==board[2][0]&&board[0][2]=='O')){
cout << "Human wins.";
return 0;
}
}
}