Skip to content

Commit a78f22d

Browse files
committed
Create Tic_Tac_Toe.cpp
1 parent e0b072d commit a78f22d

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

games/Tic_Tac_Toe.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
Get your friend ready and play the tic-tac-toe in the C++ terminal, no need to worry about pen paper 😊
3+
*/
4+
5+
#include <iostream>
6+
using namespace std;
7+
8+
char board[3][3] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'} };
9+
char player_turn = 'X';
10+
11+
void show_board() {
12+
for (int i = 0; i < 3; i++) {
13+
cout << " " << board[i][0] << " | " << board[i][1] << " | " << board[i][2] << " ";
14+
cout << endl;
15+
if (i < 2)
16+
cout << "---|---|---" << endl;
17+
}
18+
}
19+
20+
bool is_winner() {
21+
for (int i = 0; i < 3; i++)
22+
if (board[i][0] == board[i][1] && board[i][1] == board[i][2]) return true;
23+
for (int i = 0; i < 3; i++)
24+
if (board[0][i] == board[1][i] && board[1][i] == board[2][i]) return true;
25+
if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) return true;
26+
if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) return true;
27+
return false;
28+
}
29+
30+
void tic_tac_toe() {
31+
for (int moves = 0; moves < 9; moves++) {
32+
show_board();
33+
cout << "Player " << player_turn << ", enter your move: ";
34+
int move;
35+
cin >> move;
36+
37+
if (move < 1 || move > 9) {
38+
cout << "Invalid Move.Enter a number between 1-9." << endl;
39+
moves--;
40+
continue;
41+
}
42+
43+
int row = (move - 1) / 3;
44+
int col = (move - 1) % 3;
45+
46+
if (board[row][col] == 'X' || board[row][col] == 'O') {
47+
cout << "Invalid move. The number is already taken. Choose different" << endl;
48+
moves--;
49+
continue;
50+
}
51+
52+
board[row][col] = player_turn;
53+
54+
if (is_winner()) {
55+
show_board();
56+
cout << "Player " << player_turn << " wins!" << endl;
57+
return;
58+
}
59+
60+
if (player_turn == 'X') {
61+
player_turn = 'O';
62+
} else {
63+
player_turn = 'X';
64+
}
65+
}
66+
67+
show_board();
68+
cout << "DRAW.." << endl;
69+
}
70+
71+
int main() {
72+
tic_tac_toe();
73+
}

0 commit comments

Comments
 (0)