Implement Search
This commit is contained in:
72
Search.cpp
72
Search.cpp
@@ -1,3 +1,75 @@
|
||||
#include "Search.hpp"
|
||||
#include "Move.hpp"
|
||||
#include "Board.hpp"
|
||||
|
||||
int Search::search(Node *node, const Board &board, unsigned depth) {
|
||||
|
||||
if (depth == 0) {
|
||||
return evaluate(board);
|
||||
}
|
||||
|
||||
auto moves = Board::MoveVec();
|
||||
board.pseudoLegalMoves(moves);
|
||||
if (moves.empty()) {
|
||||
return evaluate(board);
|
||||
}
|
||||
|
||||
int maxValue = kNegInfinity;
|
||||
for (auto &kMove: moves) {
|
||||
Board nodeBoard = board;
|
||||
nodeBoard.makeMove(kMove);
|
||||
|
||||
Node child(kMove);
|
||||
child.value = search(&child, nodeBoard, depth - 1);
|
||||
|
||||
auto value = -child.value;
|
||||
if (value > maxValue) {
|
||||
maxValue = value;
|
||||
node->next = std::make_unique<Node>(child);
|
||||
}
|
||||
}
|
||||
|
||||
node->value = maxValue;
|
||||
|
||||
return maxValue;
|
||||
}
|
||||
|
||||
int Search::evaluate(const Board &board) {
|
||||
|
||||
return board.evaluate();
|
||||
}
|
||||
|
||||
PrincipalVariation Search::start(const Board &board) {
|
||||
auto rootMoves = Board::MoveVec();
|
||||
board.pseudoLegalMoves(rootMoves);
|
||||
|
||||
if (rootMoves.size() <= 1) {
|
||||
auto b = board;
|
||||
return PrincipalVariation(rootMoves, b);
|
||||
}
|
||||
|
||||
std::unique_ptr<RootNode> best = std::make_unique<RootNode>();
|
||||
for (const auto &kMove: rootMoves) {
|
||||
|
||||
auto node = Node(kMove);
|
||||
|
||||
Board nodeBoard = board;
|
||||
nodeBoard.makeMove(kMove);
|
||||
|
||||
auto value = -search(&node, nodeBoard, 4);
|
||||
if (value > best->value) {
|
||||
best->child = std::make_unique<Node>(node);
|
||||
best->board = nodeBoard;
|
||||
best->value = value;
|
||||
}
|
||||
}
|
||||
|
||||
auto moves = std::vector<Move>();
|
||||
auto current = std::move(best->child);
|
||||
do {
|
||||
moves.push_back(current->move);
|
||||
current = std::move(current->next);
|
||||
} while (current);
|
||||
|
||||
return PrincipalVariation(moves, best->board);
|
||||
}
|
||||
|
Reference in New Issue
Block a user