-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtictactoeai.h
More file actions
127 lines (113 loc) · 2.99 KB
/
tictactoeai.h
File metadata and controls
127 lines (113 loc) · 2.99 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
124
125
126
127
#include <iostream>
#include <vector>
#include <unistd.h>
#include <conio.h>
using namespace std;
void makeAIMove(vector<vector<char>> &board)
{
int bestMove = -1;
int bestScore = -1000;
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
if (board[i][j] == ' ')
{
board[i][j] = 'O';
int moveScore = minimax(board, 0, false);
board[i][j] = ' ';
if (moveScore > bestScore)
{
bestScore = moveScore;
bestMove = i * 3 + j + 1;
}
}
}
}
int row, col;
convertMove(bestMove, row, col);
board[row][col] = 'O';
}
void tictactoeai()
{
vector<vector<char>> board(3, vector<char>(3, ' '));
char currentPlayer = 'X';
string charmove;
int move, flag = 0;
while (true)
{
printBoard(board, "AI");
if (currentPlayer == 'X')
{
cout << "Player " << currentPlayer << ",\nEnter your move (1-9): ";
getline(cin, charmove);
move = ValidateMove(board, charmove);
if (move == -1 && flag == 1)
{
cout << "Invalid Move. Please Enter Valid Move" << endl;
getch();
continue;
}
else if (flag == 1)
{
int row, col;
convertMove(move, row, col);
board[row][col] = currentPlayer;
}
}
else
{
cout << "Thinking";
for (int j = 0; j < 3; ++j)
{
cout << ".";
usleep(500000);
}
cout << endl;
makeAIMove(board);
}
if (checkWin(board, currentPlayer))
{
printBoard(board, "AI");
if (currentPlayer == 'O')
{
cout << "AI Wins!" << endl;
cout << "Press any Key to Continue...";
getch();
system("cls");
}
else
{
cout << "Player " << currentPlayer << " Wins!" << endl;
cout << "Press any Key to Continue...";
getch();
system("cls");
}
break;
}
if (isBoardFull(board))
{
printBoard(board, "AI");
cout << "It's a tie!" << endl;
cout << "Press any Key to Continue...";
getch();
system("cls");
break;
}
if (flag == 1)
{
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
flag = 1;
}
}
// int main()
// {
// cout << "Welcome to Tic Tac Toe!" << endl;
// while (1)
// {
// tictactoeai();
// getch();
// }
// return 0;
// }