-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.cpp
More file actions
130 lines (112 loc) · 2.64 KB
/
Copy pathCode.cpp
File metadata and controls
130 lines (112 loc) · 2.64 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#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 << "__________\n";
cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl;
cout << "__________\n";
cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl;
}
bool placeMarker(int slot)
{
int row = slot / 3;
int col;
if(slot % 3 == 0) {
row = row - 1;
col = 2;
}
else {
col = slot % 3 - 1;
}
if(board[row][col] != 'X' && board[row][col] != 'O') {
board[row][col] = current_marker;
return true;
} else {
return false;
}
}
int winner()
{
for(int i = 0; i < 3; i++)
{
//rows
if(board[i][0] == board[i][1] && board[i][1] == board[i][2])
{
return current_player;
}
// columns
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 swap_player_and_marker()
{
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 one, choose your marker: ";
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) {
cout << "That slot is invalid! Try another slot!"; i--; continue;
}
if(!placeMarker(slot)) {
cout << "That slot occupied! Try another slot!"; i--; continue;
}
drawBoard();
player_won = winner();
if(player_won == 1)
{
cout << "Player one won! Congratulations!"; break;
}
if(player_won == 2)
{
cout << "Player two won! Congratulations!"; break;
}
swap_player_and_marker();
}
if(player_won == 0)
{
cout << "That is a Tie!";
}
}
int main()
{
game();
}