-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtictactoe.cpp
177 lines (142 loc) · 3.55 KB
/
tictactoe.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#include <bits/stdc++.h>
using namespace std;
struct Move
{
int row, col;
};
char player = 'x', opponent = 'o';
bool isMovesLeft(char board[3][3])
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (board[i][j] == '_')
return true;
return false;
}
int evaluate(char b[3][3])
{
for (int row = 0; row < 3; row++)
{
if (b[row][0] == b[row][1] &&
b[row][1] == b[row][2])
{
if (b[row][0] == player)
return +10;
else if (b[row][0] == opponent)
return -10;
}
}
for (int col = 0; col < 3; col++)
{
if (b[0][col] == b[1][col] &&
b[1][col] == b[2][col])
{
if (b[0][col] == player)
return +10;
else if (b[0][col] == opponent)
return -10;
}
}
if (b[0][0] == b[1][1] && b[1][1] == b[2][2])
{
if (b[0][0] == player)
return +10;
else if (b[0][0] == opponent)
return -10;
}
if (b[0][2] == b[1][1] && b[1][1] == b[2][0])
{
if (b[0][2] == player)
return +10;
else if (b[0][2] == opponent)
return -10;
}
return 0;
}
int minimax(char board[3][3], int depth, bool isMax)
{
int score = evaluate(board);
if (score == 10)
return score;
if (score == -10)
return score;
if (isMovesLeft(board) == false)
return 0;
if (isMax)
{
int best = -1000;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i][j] == '_')
{
board[i][j] = player;
best = max(best,
minimax(board, depth + 1, !isMax));
board[i][j] = '_';
}
}
}
return best;
}
else
{
int best = 1000;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i][j] == '_')
{
board[i][j] = opponent;
best = min(best,
minimax(board, depth + 1, !isMax));
board[i][j] = '_';
}
}
}
return best;
}
}
Move findBestMove(char board[3][3])
{
int bestVal = -1000;
Move bestMove;
bestMove.row = -1;
bestMove.col = -1;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (board[i][j] == '_')
{
board[i][j] = player;
int moveVal = minimax(board, 0, false);
board[i][j] = '_';
if (moveVal > bestVal)
{
bestMove.row = i;
bestMove.col = j;
bestVal = moveVal;
}
}
}
}
cout<<"The value of the best Move is "<<
bestVal<<"\n"<<endl;
return bestMove;
}
int main()
{
char board[3][3] =
{
{'x', 'o', 'x'},
{'o', 'x', 'x'},
{'_', '_', '_'}};
Move bestMove = findBestMove(board);
cout<<"The Optimal Move is"<<endl;
cout<<"ROW :"<<bestMove.row;
cout<<"COL :"<<bestMove.col;
return 0;
}