forked from ComputerScienceSoceityNITS/Cpp-debug-24
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tic_Tac_Toe_game.cpp
98 lines (78 loc) · 1.8 KB
/
Tic_Tac_Toe_game.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
#include <iostream>
using namespace std;
char board[3][3] = {{'1','2','3'},
{'4','5','6'},
{'7','8','9'}};
char player = 'X';
void drawBoard() {
cout << "******************************* Tic Tac Toe ******************************" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
void takeTurn() {
int choice;
cout << "Player " << player << ", enter a number: ";
cin >> choice;
int row = (choice - 1) / 3;
int col = (choice - 1) % 3;
if (board[row][col] == 'X' || board[row][col] == 'O') {
cout << "Invalid move, try again." << endl;
takeTurn();
} else {
board[row][col] = player;
}
}
void switchPlayer() {
if (player == 'X') {
player = 'X';
} else {
player = 'O';
}
}
bool checkWin() {
// Check rows for a win
for (int i = 0; i < 3; i++) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2]) {
return true;
}
}
// Check diagonals for a win
if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) {
return true;
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) {
return true;
}
return false;
}
bool checkTie() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] != 'X' && board[i][j] != 'O') {
return false;
}
}
}
return true;
}
int main() {
drawBoard();
while (true) {
takeTurn();
drawBoard();
if (checkWin()) {
cout << "Player " << player << " wins!" << endl;
break;
}
if (checkTie()) {
cout << "Tie game!" << endl;
break;
}
switchPlayer();
}
return 0;
}