-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTicTacToe.cpp
More file actions
82 lines (76 loc) · 2.59 KB
/
TicTacToe.cpp
File metadata and controls
82 lines (76 loc) · 2.59 KB
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
#include <iostream>
#include <string>
using namespace std;
int main() {
char board[3][3] = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
const char playerX = 'X';
const char playerO = 'O';
char currentPlayer = playerO;
int row = -1;
int col = -1;
char winner = ' ';
for (int i = 0; i < 9; i++) {
cout << " | | " << endl;
cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl;
cout << "___|___|___" << endl;
cout << " | | " << endl;
cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl;
cout << "___|___|___" << endl;
cout << " | | " << endl;
cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl;
cout << " | | " << endl;
if (winner != ' ') {
break;
}
cout << "Current Player is " << currentPlayer << endl;
while (true) {
cout << "Enter row number from (0 to 2): ";
cin >> row;
cout << "Enter column number from (0 to 2): ";
cin >> col;
if (row < 0 || row > 2 || col < 0 || col > 2) {
cout << "Invalid input, try again." << endl;
}
else if (board[row][col] != ' ') {
cout << "Tile is full, try again." << endl;
}
else {
break;
}
row = -1;
col = -1;
cin.clear();
cin.ignore(10000, '\n');
}
board[row][col] = currentPlayer;
currentPlayer = (currentPlayer == playerX) ? playerO : playerX;
for (int row = 0; row < 3; row++) {
if (board[row][0] != ' ' && board[row][0] == board[row][1] && board[row][1] == board[row][2]) {
winner = board[row][0];
break;
}
}
for (int col = 0; col < 3; col++) {
if (board[0][col] != ' ' && board[0][col] == board[1][col] && board[1][col] == board[2][col]) {
winner = board[0][col];
break;
}
}
if (board[0][0] != ' ' && board[0][0] == board[1][1] && board[1][1] == board[2][2]) {
winner = board[0][0];
}
else if (board[0][2] != ' ' && board[0][2] == board[1][1] && board[1][1] == board[2][0]) {
winner = board[0][2];
}
}
if (winner != ' ') {
cout << "Player" << winner << " is the winner!" << endl;
}
else {
cout << "Tie!" << endl;
}
}