-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAI.cc
More file actions
97 lines (88 loc) · 3.12 KB
/
AI.cc
File metadata and controls
97 lines (88 loc) · 3.12 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
#include "AI.h"
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <utility>
#include <stdexcept>
#include <exception>
#include <iostream>
AI::AI(bool color, bool inCheck, bool hasCastled, bool isComputer, ChessBoard *board):
Player{color, inCheck, hasCastled, isComputer, board} {}
AI::~AI() {}
Move AI::handleMove() {
return generateMove();
}
int AI::randNumBetween(int start, int end) {
time_t curTime = time(nullptr);
srand(curTime);
int num = (rand() % (end - start + 1)) + start;
return num;
}
vector<Move> AI::getAllLegalMoves() {
vector<Move> allMoves;
vector<Move> legalMoves;
ChessBoard * board = getBoard();
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
pair<int, int> pos = make_pair(i, j);
if (board->isOccupied(pos) && board->getPiece(pos)->isWhite() == getColor()) {
Piece * p = board->getPiece(pos);
vector<Move> moves = p->generateMoves();
for(int i = 0; i < (int)moves.size(); i++){
if(board->isOccupied(moves[i].getEndPos())){
moves[i] = {p, moves[i].getStartPos(), moves[i].getEndPos(), board->getPiece(moves[i].getEndPos())};
}
else if (p->getPieceSymbol() == 'K' && !p->hasMoved()) {
moves[i] = castleMoveCreator(moves[i]);
}
}
allMoves.insert(allMoves.begin(), moves.begin(), moves.end());
}
}
}
for (int i = 0; i < (int)allMoves.size(); ++i) {
try {
if (board->checkMoveLegal(allMoves[i])) {
legalMoves.push_back(allMoves[i]);
}
}
catch (std::invalid_argument& err) {
continue;
}
}
return legalMoves;
}
vector<Move> AI::getAllEnemyLegalMoves() {
vector<Move> allMoves;
vector<Move> legalMoves;
ChessBoard * board = getBoard();
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
pair<int, int> pos = make_pair(i, j);
if (board->isOccupied(pos) && board->getPiece(pos)->isWhite() != getColor()) {
Piece * p = board->getPiece(pos);
vector<Move> moves = p->generateMoves();
for(int i = 0; i < (int)moves.size(); i++){
if(board->isOccupied(moves[i].getEndPos())){
moves[i] = {p, moves[i].getStartPos(), moves[i].getEndPos(), board->getPiece(moves[i].getEndPos())};
}
else if (p->getPieceSymbol() == 'K' && !p->hasMoved()) {
moves[i] = castleMoveCreator(moves[i]);
}
}
allMoves.insert(allMoves.begin(), moves.begin(), moves.end());
}
}
}
for (int i = 0; i < (int)allMoves.size(); ++i) {
try {
if (board->checkMoveLegal(allMoves[i])) {
legalMoves.push_back(allMoves[i]);
}
}
catch (std::invalid_argument& err) {
continue;
}
}
return legalMoves;
}