-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4tictaktoe.cpp
More file actions
97 lines (80 loc) · 2.42 KB
/
4tictaktoe.cpp
File metadata and controls
97 lines (80 loc) · 2.42 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <iostream>
using namespace std;
char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
char current_marker;
int current_player;
void drawBoard() {
cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl;
cout << "---|---|---" << endl;
cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl;
cout << "---|---|---" << endl;
cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl;
}
bool placeMarker(int slot) {
int row = (slot - 1) / 3;
int col = (slot - 1) % 3;
if (board[row][col] != 'X' && board[row][col] != 'O') {
board[row][col] = current_marker;
return true;
}
return false;
}
int winner() {
for (int i = 0; i < 3; i++) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2])
return current_player;
if (board[0][i] == board[1][i] && board[1][i] == board[2][i])
return current_player;
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2])
return current_player;
if (board[0][2] == board[1][1] && board[1][1] == board[2][0])
return current_player;
return 0;
}
void swapPlayerAndMarker() {
if (current_marker == 'X')
current_marker = 'O';
else
current_marker = 'X';
if (current_player == 1)
current_player = 2;
else
current_player = 1;
}
void game() {
cout << "Player 1, choose your marker (X or O): ";
char marker_p1;
cin >> marker_p1;
current_player = 1;
current_marker = marker_p1;
drawBoard();
int player_won;
for (int i = 0; i < 9; i++) {
cout << "It's Player " << current_player << "'s turn. Enter your slot: ";
int slot;
cin >> slot;
if (slot < 1 || slot > 9 || !placeMarker(slot)) {
cout << "Invalid slot! Try again.\n";
i--;
continue;
}
drawBoard();
player_won = winner();
if (player_won == 1) {
cout << "Player 1 wins!\n";
break;
}
if (player_won == 2) {
cout << "Player 2 wins!\n";
break;
}
swapPlayerAndMarker();
}
if (player_won == 0)
cout << "It's a tie!\n";
}
int main() {
game();
return 0;
}