-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.cpp
More file actions
105 lines (94 loc) · 2.17 KB
/
Copy pathApp.cpp
File metadata and controls
105 lines (94 loc) · 2.17 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
#include <iostream>
#define rows 3
#define cols 3
#define player1 'X'
#define player2 'O'
using namespace std;
char board[rows][cols];
char turn = player1;
void display_board();
char check_winner();
void change_turn();
void reset_board();
void how_to_play();
int main() {
how_to_play();
char play = 'y';
while (play == 'y') {
int game_over = 0;
int step = 0;
reset_board();
while (!game_over) {
display_board();
if (step < 9) {
cout << turn << "'s turn: ";
int h, w;
cin >> h >> w;
if (h > 0 && h < 4 && w > 0 && w < 4 && board[h - 1][w - 1] == ' ') {
board[h - 1][w - 1] = turn;
step++;
}
else {
continue;
}
char result = check_winner();
if (result) {
display_board();
cout << result << " wins!";
game_over = 1;
}
change_turn();
}
else {
cout << "Draw!";
game_over = 1;
}
}
play = NULL;
cout << endl << "Play again (y/n) ?" << endl;
cin >> play;
}
return 0;
}
void display_board() {
system("cls");
cout << "-------------" << endl;
for (int i = 0; i < rows; i++) {
cout << "| ";
for (int j = 0; j < cols; j++) {
cout << board[i][j] <<" | ";
}
cout << endl << "-------------" << endl;
}
}
char check_winner() {
//checking rows
for (int i = 0; i < rows; i++) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ') return board[i][0];
}
//checking cols
for (int j = 0; j < cols; j++) {
if (board[0][j] == board[1][j] && board[1][j] == board[2][j] && board[0][j] != ' ') return board[0][j];
}
//checking diagonals
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ') return board[0][0];
if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[2][0] != ' ') return board[2][0];
return NULL;
}
void change_turn() {
if (turn == player1) turn = player2;
else turn = player1;
}
void reset_board() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
board[i][j] = ' ';
}
}
}
void how_to_play() {
cout << "Enter vertical index and horizontal index seperated by a space to play a turn ";
cout << "e.g (2 2).";
cout << endl << "Press enter to play...";
cin.get();
}