-
Notifications
You must be signed in to change notification settings - Fork 0
/
task 3.cpp
102 lines (89 loc) · 3.23 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#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++) {
//print game board
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;
}
//get player input
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;
}
// Reset input values and clear the input stream
cin.clear(); //clear error flags
cin.ignore(10000, '\n'); //discard values
}
board[r][c] = currentPlayer;
currentPlayer = (currentPlayer == playerX) ? playerO : playerX;
//check winners
//rows - horizontal
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;
}
}
//columns - vertical
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;
}
}
//diagonal
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];
}
}
//print final game board
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 != ' ') {
cout << "Player " << winner << " is the winner!" << endl;
}
else {
cout << "Tie!" << endl;
}
}