-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcbtc task 2.cpp
66 lines (53 loc) · 1.86 KB
/
cbtc task 2.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
#include <iostream>
#include <vector>
using namespace std;
// Function to print the Tic Tac Toe board
void printBoard(const vector<vector<char>>& board) {
for (const auto& row : board) {
for (char cell : row) {
cout << cell << " ";
}
cout << endl;
}
}
// Function to check if a player has won
bool checkWin(const vector<vector<char>>& board, char player) {
// Check rows, columns, and diagonals
for (int i = 0; i < 3; ++i) {
if ((board[i][0] == player && board[i][1] == player && board[i][2] == player) ||
(board[0][i] == player && board[1][i] == player && board[2][i] == player)) {
return true;
}
}
if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
(board[0][2] == player && board[1][1] == player && board[2][0] == player)) {
return true;
}
return false;
}
int main() {
vector<vector<char>> board(3, vector<char>(3, ' '));
char currentPlayer = 'X';
int row, col;
cout << "Let's play Tic Tac Toe!" << endl;
for (int turn = 0; turn < 9; ++turn) {
printBoard(board);
cout << "Player " << currentPlayer << ", enter row and column (0-2): ";
cin >> row >> col;
if (row < 0 || row > 2 || col < 0 || col > 2 || board[row][col] != ' ') {
cout << "Invalid move. Try again." << endl;
--turn;
continue;
}
board[row][col] = currentPlayer;
if (checkWin(board, currentPlayer)) {
printBoard(board);
cout << "Player " << currentPlayer << " wins! Congrats!" << endl;
return 0;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
printBoard(board);
cout << "It's a draw! Good game!" << endl;
return 0;
}