Skip to content

Commit 4c19b2f

Browse files
authored
Merge pull request #34 from akshit397a/patch-4
Create Tick_Tack_Toe.cpp
2 parents c6cc818 + 7f44ff1 commit 4c19b2f

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

games-based-on-dsa/Tick_Tack_Toe.cpp

+95
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// Tick-Tack-Toe
2+
// This C++ program implements a Tick-Tack-Toe game where two players take turns to input their moves.
3+
// The game checks for wins or draws after each move and displays the current board state.
4+
#include <iostream>
5+
#include <vector>
6+
#define SIZE 3
7+
8+
class TicTacToe {
9+
private:
10+
std::vector<std::vector<char>> board;
11+
char currentPlayer;
12+
13+
public:
14+
TicTacToe() {
15+
board.resize(SIZE, std::vector<char>(SIZE));
16+
initializeBoard();
17+
currentPlayer = 'X';
18+
}
19+
20+
void initializeBoard() {
21+
int count = 1;
22+
for (int i = 0; i < SIZE; i++) {
23+
for (int j = 0; j < SIZE; j++) {
24+
board[i][j] = '0' + count++;
25+
}
26+
}
27+
}
28+
29+
void printBoard() {
30+
for (int i = 0; i < SIZE; i++) {
31+
for (int j = 0; j < SIZE; j++) {
32+
std::cout << " " << board[i][j] << " ";
33+
if (j < SIZE - 1) std::cout << "|";
34+
}
35+
std::cout << "\n";
36+
if (i < SIZE - 1) std::cout << "---|---|---\n";
37+
}
38+
}
39+
40+
bool checkWin(char player) {
41+
for (int i = 0; i < SIZE; i++) {
42+
if ((board[i][0] == player && board[i][1] == player && board[i][2] == player) ||
43+
(board[0][i] == player && board[1][i] == player && board[2][i] == player)) {
44+
return true;
45+
}
46+
}
47+
if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
48+
(board[0][2] == player && board[1][1] == player && board[2][0] == player)) {
49+
return true;
50+
}
51+
return false;
52+
}
53+
54+
void playGame() {
55+
int moves = 0;
56+
57+
while (true) {
58+
printBoard();
59+
std::cout << "Player " << currentPlayer << ", enter your move (1-9): ";
60+
int move;
61+
std::cin >> move;
62+
63+
int row = (move - 1) / SIZE;
64+
int col = (move - 1) % SIZE;
65+
66+
if (move < 1 || move > 9 || board[row][col] == 'X' || board[row][col] == 'O') {
67+
std::cout << "Invalid move. Try again.\n";
68+
continue;
69+
}
70+
71+
board[row][col] = currentPlayer;
72+
moves++;
73+
74+
if (checkWin(currentPlayer)) {
75+
printBoard();
76+
std::cout << "Player " << currentPlayer << " wins!\n";
77+
break;
78+
}
79+
80+
if (moves == SIZE * SIZE) {
81+
printBoard();
82+
std::cout << "It's a draw!\n";
83+
break;
84+
}
85+
86+
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
87+
}
88+
}
89+
};
90+
91+
int main() {
92+
TicTacToe game;
93+
game.playGame();
94+
return 0;
95+
}

0 commit comments

Comments
 (0)