1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
void choosingTile(string& tiles, int& turn){
srand(static_cast<unsigned int>(time(0)));
int number = -1;
while(!(number >= 0 && number <= 8)){
if(turn == 0){
while(!(number >= 0 && number <= 8) || (tiles[number]=='X'||tiles[number]=='O')){
cout << "Enter the number of the tile that you want to choose: "; cin >> number;
}
tiles[number] = 'X';
turn = 1;
}
else if(turn == 1){
do{
number = rand()%9;
}while(tiles[number]=='X'||tiles[number]=='O');
tiles[number] = 'O';
turn = 0;
}
}
}
int determineWinner(string tiles){
string test, ett, tva, tre;
int grej = 0;
for(int x=0;x<9;x+=3){
if(tiles.substr(x,3)=="XXX")
return 1;
else if(tiles.substr(x,3)=="OOO")
return 2;
}for(int x=0;x<3;x++){
ett = tiles[x], tva = tiles[x+3], tre = tiles[x+6];
test = ett + tva + tre;
if(test == "XXX")
return 1;
else if(test == "OOO")
return 2;
}
ett = tiles[0], tva = tiles[4], tre = tiles[8];
test = ett + tva + tre;
if(test == "XXX")
return 1;
else if(test == "OOO")
return 2;
ett = tiles[2], tva = tiles[4], tre = tiles[6];
test = ett + tva + tre;
if(test == "XXX")
return 1;
else if(test == "OOO")
return 2;
else{
for(int x=0;x<9;x++){
if(tiles[x] == 'X' || tiles[x] == 'O')
grej++;
}
if(grej == 9)
return 3;
}
}
int main(){
string tiles = "0123456789";
int win = 0, turn = 0;
while(win != 1 && win != 2 && win != 3){
system("CLS");
cout << " -= Tic-Tac-Toe =-\n\n\t" << tiles[0] << " | " << tiles[1] << " | " << tiles[2] << "\n"
<< "\t----------\n"
<< "\t" << tiles[3] << " | " << tiles[4] << " | " << tiles[5] << "\n"
<< "\t----------\n"
<< "\t" << tiles[6] << " | " << tiles[7] << " | " << tiles[8] << "\n\n";
choosingTile(tiles, turn);
win = determineWinner(tiles);
}
if(win == 1)
cout << "Congratulations! You won!" << endl;
else if(win == 2)
cout << "The computer won!" << endl;
else
cout << "No one won!" << endl;
}
|