-
Notifications
You must be signed in to change notification settings - Fork 0
/
Task_3.cpp
74 lines (74 loc) · 2.51 KB
/
Task_3.cpp
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
#include <iostream>
#include <string>
using namespace std;
int main() {
char board[3][3] = {
{' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '}
};
const char playerX = 'X';
const char playerO = 'O';
char currentPlayer = playerX;
int r = -1;
int c = -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 r c from 0-2 for row and column: ";
cin >> r >> c;
if (r < 0 || r > 2 || c < 0 || c > 2) {
cout << "Invalid input, try again." << endl;
}
else if (board[r][c] != ' ') {
cout << "Tile is full, try again." << endl;
}
else {
break;
}
r = -1;
c = -1;
cin.clear();
cin.ignore(10000, '\n');
}
board[r][c] = currentPlayer;
currentPlayer = (currentPlayer == playerX) ? playerO : playerX;
for (int r = 0; r < 3; r++) {
if (board[r][0] != ' ' && board[r][0] == board[r][1] && board[r][1] == board[r][2]) {
winner = board[r][0];
break;
}
}
for (int c = 0; c < 3; c++) {
if (board[0][c] != ' ' && board[0][c] == board[1][c] && board[1][c] == board[2][c]) {
winner = board[0][c];
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;
}
}