-
Notifications
You must be signed in to change notification settings - Fork 0
/
Assignment 03 tictactoe.cpp
110 lines (97 loc) · 2.14 KB
/
Assignment 03 tictactoe.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
103
104
105
106
107
108
109
110
#include <iostream>
#include <string>
using namespace std;
int moveCounter = 0;
bool isWon(char xo, char board[][3]) {
bool won = false;
for (int i = 0; i < 3; i++) {
if (board[i][0] == xo && board[i][1] == xo && board[i][2] == xo) {
won = true;
}
}
for (int i = 0; i < 3; i++) {
if (board[0][i] == xo && board[1][i] == xo && board[2][i] == xo) {
won = true;
}
}
if (board[0][0] == xo && board[1][1] == xo && board[2][2] == xo) {
won = true;
}
if (board[0][2] == xo && board[1][1] == xo && board[2][0] == xo) {
won = true;
}
return won;
}
bool isDraw(char board[][3]) {
bool draw = false;
if (moveCounter == 9) {
if (isWon('x', board)) {
draw = true;
}
draw = true;
}
return draw;
}
void displayBoard(char board[][3]) {
for (int i = 0; i < 3; i++) {
cout << "\n-------------\n";
for (int j = 0; j < 3; j++) {
cout << "| " << board[i][j] << " ";
}
cout << "|";
}
cout << "\n-------------\n";
}
void makeAMove(char board[][3], char xo) {
int inputRow = 0;
int inputColumn = 0;
bool taken = true;
int a;
while (taken) {
cout << "Enter a row (0, 1, 2) for player " << xo << " : ";
cin >> inputRow;
cout << "Enter a column (0, 1, 2) for player " << xo << ": ";
cin >> inputColumn;
if (board[inputRow][inputColumn] == 'X' || board[inputRow][inputColumn] == 'O') {
cout << "This cell is already occupied. Try a different cell";
}
else {
board[inputRow][inputColumn] = xo;
taken = false;
}
cout << endl;
}
moveCounter++;
}
int main() {
//
// PLEASE DO NOT CHANGE function main
//
char board[3][3] = { { ' ', ' ', ' ' },{ ' ', ' ', ' ' },{ ' ', ' ', ' ' } };
displayBoard(board);
while (true) {
// The first player makes a move
makeAMove(board, 'X');
displayBoard(board);
if (isWon('X', board)) {
cout << "X player won" << endl;
exit(0);
}
else if (isDraw(board)) {
cout << "No winner" << endl;
exit(0);
}
// The second player makes a move
makeAMove(board, 'O');
displayBoard(board);
if (isWon('O', board)) {
cout << "O player won" << endl;
exit(0);
}
else if (isDraw(board)) {
cout << "No winner" << endl;
exit(0);
}
}
return 0;
}