From aa32d81f8da39e4456a91c244c8a8c2fad1e05fc Mon Sep 17 00:00:00 2001 From: Mark Bluemer Date: Wed, 19 Apr 2017 20:31:20 -0400 Subject: [PATCH] Added alpha-beta... still getting seg faults --- include/MinimaxSearch.h | 3 ++- src/MinimaxSearch.cpp | 31 +++++++++++++++++++++++++++++-- src/main.cpp | 2 +- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/include/MinimaxSearch.h b/include/MinimaxSearch.h index 53413df..9665a54 100644 --- a/include/MinimaxSearch.h +++ b/include/MinimaxSearch.h @@ -10,10 +10,11 @@ class MinimaxSearch { private: - static const int maxDepth = 7; + static const int maxDepth = 6; double minValue(std::unique_ptr &board, int currentDepth) const; double maxValue(std::unique_ptr &board, int currentDepth) const; + double alphaBeta(std::unique_ptr &board, double alpha, double beta, int depth) const; public: diff --git a/src/MinimaxSearch.cpp b/src/MinimaxSearch.cpp index f4cf743..8b1c41c 100644 --- a/src/MinimaxSearch.cpp +++ b/src/MinimaxSearch.cpp @@ -32,6 +32,32 @@ double MinimaxSearch::maxValue(bup &board, int currentDepth) const return v; } +// +double MinimaxSearch::alphaBeta(bup &board, double alpha, double beta, int depth) const +{ + if (depth == maxDepth) return board->utility(board->player()); + + // black is max player here + double v; + if (board->player() == "black") { + v = std::numeric_limits::lowest(); + for (Move move : board->actions()) { + bup result = board->result(move); + v = std::max(v, alphaBeta(result, alpha, beta, depth + 1)); + if (v >= beta) return v; + alpha = std::max(alpha, v); + } + } else { + v = std::numeric_limits::max(); + for (Move move : board->actions()) { + bup result = board->result(move); + v = std::min(v, alphaBeta(result, alpha, beta, depth + 1)); + if (v <= alpha) return v; + beta = std::max(beta, v); + } + } + return v; +} /* Public Functions */ Move MinimaxSearch::minimaxDecision(bup &board) const @@ -43,10 +69,10 @@ Move MinimaxSearch::minimaxDecision(bup &board) const if (bestMove.isEmpty()) { bestMove = move; bup result = board->result(bestMove); - bestMoveValue = minValue(result, 0); + bestMoveValue = alphaBeta(result, std::numeric_limits::lowest(), std::numeric_limits::max(), 0); } else { bup result = board->result(move); - double nextMoveValue = minValue(result, 0); + double nextMoveValue = alphaBeta(result, std::numeric_limits::lowest(), std::numeric_limits::max(), 0); if (bestMoveValue < nextMoveValue) { bestMove = move; bestMoveValue = nextMoveValue; @@ -56,3 +82,4 @@ Move MinimaxSearch::minimaxDecision(bup &board) const return bestMove; } + diff --git a/src/main.cpp b/src/main.cpp index 45d8722..fbff2ca 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -10,7 +10,7 @@ int main(int argc, const char * argv[]) { std::unique_ptr board (new BitBoard); MinimaxSearch searchDriver; - for (int i = 0; i < 20; ++i) { + for (int i = 0; i < 40; ++i) { board->printState(); Move bestMove = searchDriver.minimaxDecision(board); board = board->result(bestMove);