forked from mrigaankzoro/Hacktoberfest24
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tic-tac-toe.cpp
95 lines (82 loc) · 2.09 KB
/
tic-tac-toe.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
// C++ program to implement tic tac toe game
#include <iostream>
using namespace std;
// Function to draw the Tic-Tac-Toe board
void drawBoard(char board[3][3])
{
cout << "-------------\n";
for (int i = 0; i < 3; i++) {
cout << "| ";
for (int j = 0; j < 3; j++) {
cout << board[i][j] << " | ";
}
cout << "\n-------------\n";
}
}
// Function to check for a win
bool checkWin(char board[3][3], 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)
return true;
if (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)
return true;
if (board[0][2] == player && board[1][1] == player
&& board[2][0] == player)
return true;
return false;
}
int main()
{
// Initialize the board and players
char board[3][3] = { { ' ', ' ', ' ' },
{ ' ', ' ', ' ' },
{ ' ', ' ', ' ' } };
char player = 'X';
int row, col;
int turn; // Declare turn here
cout << "Welcome to Tic-Tac-Toe!\n";
// Game loop
for (turn = 0; turn < 9; turn++) {
// Draw the board
drawBoard(board);
// Prompt for valid input
while (true) {
cout << "Player " << player
<< ", enter row (0-2) and column (0-2): ";
cin >> row >> col;
if (board[row][col] != ' ' || row < 0 || row > 2
|| col < 0 || col > 2) {
cout << "Invalid move. Try again.\n";
}
else {
break; // Valid input, exit the loop.
}
}
// Make the move
board[row][col] = player;
// Check for a win after making a move
if (checkWin(board, player)) {
drawBoard(board);
cout << "Player " << player << " wins!\n";
break; // Exit the loop after a win.
}
// Switch to the other player
player = (player == 'X') ? 'O' : 'X';
}
// End of the game
drawBoard(board);
// Check for a draw
if (turn == 9 && !checkWin(board, 'X')
&& !checkWin(board, 'O')) {
cout << "It's a draw!\n";
}
return 0;
}