-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask3.cpp
More file actions
123 lines (106 loc) · 2.86 KB
/
Copy pathTask3.cpp
File metadata and controls
123 lines (106 loc) · 2.86 KB
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
116
117
118
119
120
121
122
123
#include<iostream>
#include<vector>
#include<string.h>
#include<cstring>
#include<unordered_map>
#include<algorithm>
#include<limits.h>
using namespace std;
bool Check_winner(const vector<vector<char>>& Board, char player) {
for (int i = 0; i < 3; ++i) {
// Check rows and columns
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;
}
}
// Check diagonals
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;
}
void Display_Board(vector<vector<char>>Board){
for(int i=0 ; i<3 ; i++){
for(int j=0 ; j<3 ; j++){
cout<<Board[i][j];
if ( j < 2){
cout << " | ";
}
}
cout << endl;
if (i < 2) {
cout << "------------------" << endl;
}
}
}
int main(){
while(true){
int x = 3 , y= 3;
int Total_moves = 9;
char player = 'X';
int move;
vector<vector<char>>Board={
{'1' , '2' , '3'},
{'4' , '5' , '6'},
{'7' , '8' , '9'}
};
cout<<"----------- Tic - Toe Game ---------------"<<endl;
cout<<endl;
cout<<"Player 1 : X"<<endl;
cout<<"Player 2 : O"<<endl;
cout<<endl;
cout<<"Press any key to continue ..... ";
getchar();
system("cls");
do{
Display_Board(Board);
cout<<endl;
int r , c;
cout<<"Current Player : "<<player<<endl;
cout<<"Enter your move : "<<endl;
cin >> move;
cout<<endl;
--Total_moves;
if(move < 1 && move > 9){
cout<<"Invalid move !!"<<endl;
continue;
}
// Formulas to find row and col //
r = (move - 1) / x;
c = (move - 1) % y;
if(Board[r][c]=='X' ||Board[r][c] == 'O'){
cout<<"Move Already Taken !! "<<endl;
continue;
}
else
{
Board[r][c] = player;
}
if(Check_winner(Board,player)){
cout<<"Player "<<player<<" wins !!"<<endl;
break;
}
if(Total_moves == 0){
cout<<"It's a Draw !! "<<endl;
break;
}
// Player change //
if(player == 'X'){
player = 'O';
}
else
player = 'X';
}while(true);
cout<<"------- Game ends ----------"<<endl;
cout<<"Do you want to play again ? "<<endl;
cout<<"1) Yes "<<endl;
int opt;
cin >> opt;
if(opt == 2){
break;
}
}
return 0;
}