-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
93 lines (83 loc) · 2.46 KB
/
main.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
#include <iostream>
#include <vector>
using namespace std;
class TicTacToe {
public:
TicTacToe() : board(3, vector<char>(3, ' ')), currentPlayer('X') {}
void play() {
while (true) {
printBoard();
playerMove();
if (checkWin()) {
printBoard();
cout << "Player " << currentPlayer << " wins!" << endl;
break;
}
if (checkDraw()) {
printBoard();
cout << "It's a draw!" << endl;
break;
}
switchPlayer();
}
}
private:
vector<vector<char>> board;
char currentPlayer;
void printBoard() {
cout << " 0 1 2" << endl;
for (int i = 0; i < 3; ++i) {
cout << i << " ";
for (int j = 0; j < 3; ++j) {
cout << board[i][j] << ' ';
}
cout << endl;
}
}
void playerMove() {
int row, col;
while (true) {
cout << "Player " << currentPlayer << ", enter your move (row and column): ";
cin >> row >> col;
if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == ' ') {
board[row][col] = currentPlayer;
break;
} else {
cout << "This move is not valid. Try again." << endl;
}
}
}
void switchPlayer() {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
bool checkWin() {
// Check rows and columns
for (int i = 0; i < 3; ++i) {
if ((board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) ||
(board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer)) {
return true;
}
}
// Check diagonals
if ((board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) ||
(board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer)) {
return true;
}
return false;
}
bool checkDraw() {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
};
int main() {
TicTacToe game;
game.play();
return 0;
}