-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tictactoe.cpp
128 lines (102 loc) · 2.52 KB
/
Tictactoe.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
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
// Tictactoe data members:-
// size
// board
// currentPlayer
// Tictactoe member functions:-
// getCurrentPlayer();
// makeMove();
// checkWin();
// switchPlayer();
// boardFull();
// printBoard();
#include<bits/stdc++.h>
using namespace std;
class TicTacToe {
private:
int size;
vector<vector<char>>board;
char currentPlayer;
public: TicTacToe(int n) {
size = n;
board = vector<vector<char>>(n, vector<char>(n, '_'));
currentPlayer = 'X';
}
void printBoard() const {
for (const auto & row: board) {
for (char cell: row) {
cout << cell << " ";
}
cout << endl;
}
cout << endl;
}
bool makeMove(int row, int col) {
if (row < 0 || row >= size || col < 0 || col >= size || board[row][col] != '_') {
cout << "Invalid move! Try again." << endl;
return false;
}
board[row][col] = currentPlayer;
return true;
}
bool checkWin(int row, int col) {
// Checking rows
int rowCnt = 0, colCnt = 0, digCnt1 = 0, digCnt2 = 0;
for (int i = 0; i < size; i++) {
if (board[row][i] == currentPlayer)
rowCnt++;
if (board[i][col] == currentPlayer)
colCnt++;
if (board[i][i] == currentPlayer)
digCnt1++;
if (board[i][size - i] == currentPlayer)
digCnt2++;
if (rowCnt == size || colCnt == size || digCnt1 == size || digCnt2 == size)
break;
}
if (rowCnt == size || colCnt == size || digCnt1 == size || digCnt2 == size)
return true;
return false;
}
bool boardFull() const {
for (const auto & row: board) {
for (char cell: row) {
if (cell == '_') {
return false; // Board is not full
}
}
}
return true; // Board is full
}
void switchPlayer() {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
char getCurrentPlayer() const {
return currentPlayer;
}
};
int main() {
int n;
cout << "Enter size of a board" << endl;
cin >> n;
TicTacToe game(n);
while (true) {
game.printBoard();
int row, col;
cout << "Player " << game.getCurrentPlayer() << ", enter your move (row and column): ";
cin >> row >> col;
if (game.makeMove(row, col)) {
if (game.checkWin(row, col)) {
game.printBoard();
cout << "Player " << game.getCurrentPlayer() << " wins!" << endl;
break;
}
if (game.boardFull()) {
game.printBoard();
cout << "It's a draw!" << endl;
break;
}
game.switchPlayer();
}
}
return 0;
}