-
Notifications
You must be signed in to change notification settings - Fork 0
/
tic-tac-toe.cpp
115 lines (99 loc) · 2.35 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
using namespace std;
char grid[3][3] = {{'1','2','3'}, {'4','5','6'}, {'7','8','9'}};
char currentPlayer = 'X';
// Function to display the Tic Tac Toe grid
void displayGrid()
{
cout << "Tic Tac Toe Game:\n";
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
cout<<"|"<<grid[i][j]<<"| ";
}
cout<<endl;
}
}
// Function to check for a win
bool checkWin()
{
// Checking rows and columns
for (int i=0;i<3;i++)
{
if ((grid[i][0]==grid[i][1] && grid[i][1]==grid[i][2]) || (grid[0][i]==grid[1][i] && grid[1][i]==grid[2][i]))
{
return true;
}
}
// Checking diagonals
if ((grid[0][0]==grid[1][1] && grid[1][1]==grid[2][2]) || (grid[0][2]==grid[1][1] && grid[1][1]==grid[2][0]))
{
return true;
}
return false;
}
// Function to check if the grid is full, thus a draw
bool checkTie()
{
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
if (grid[i][j]!='X' && grid[i][j]!='O')
{
return false;
}
}
}
return true;
}
// Function to switch players
void switchPlayer()
{
currentPlayer=(currentPlayer=='X')?'O':'X';
}
// Function to make a move
void makeMove(int cell)
{
// Convert the cell number to grid coordinates
int row= (cell-1)/3;
int col= (cell-1)%3;
// Check if the cell is valid if not already taken by X or O
if (cell>=1 && cell<=9 && grid[row][col]!='X' && grid[row][col]!='O')
{
grid[row][col] = currentPlayer;
switchPlayer();
}
else
{
cout<<"Invalid move! Please try again.\n";
}
}
int main()
{
int cell;
bool gameWon=false;
//Checking while winning or draw conditions not met
while (!gameWon && !checkTie())
{
displayGrid();
//Asking user for cell value to be converted into grid coordinates
cout<<"Player "<<currentPlayer<<", enter a corresponding number(1-9): ";
cin>>cell;
makeMove(cell);
gameWon=checkWin();
}
displayGrid();
//If game won/draw
if (gameWon)
{
cout<<"Player"<<currentPlayer<<"losses\n";
cout<<"Player "<<switchPlayer<<" wins!";
}
else
{
cout<<"It's a draw!";
}
return 0;
}