diff --git a/grid.cpp b/grid.cpp index b77b837..cf7e7f8 100644 --- a/grid.cpp +++ b/grid.cpp @@ -11,6 +11,7 @@ grid::grid() { memset(tiles, 0, sizeof(tiles)); score = 0; empty = SIZE * SIZE; + blocked = false; add(); add(); } diff --git a/main.cpp b/main.cpp index 7a75935..cb98455 100644 --- a/main.cpp +++ b/main.cpp @@ -17,10 +17,8 @@ int main() { int move; do { - int bestScore = 0; - int bestDir = -1; - bestMove(g, 12, bestScore, bestDir); - move = bestDir; + int a = 0; + move = move::bestMove(g, 6); g.move(move); g.show(); std::cout << "Score: " << g.getScore() << std::endl; diff --git a/move.cpp b/move.cpp index 39c381e..d1d69ca 100644 --- a/move.cpp +++ b/move.cpp @@ -7,32 +7,42 @@ #define max(a, b) ((a) > (b) ? (a) : (b)) -inline int evaluate(const grid& g) { - return (g.getEmpty() << 16) + g.getScore(); -} - -int bestMove(const grid& g, int depth, int &bestScore, int &bestDir, int move) { - - if (depth == 0 || g.isBlocked()) { - return evaluate(g); +namespace move { + int bestMove(const grid& g, int depth) { + int bestScore = 0, bestDir = -1; + bestMoveHelper(g, depth, bestScore, bestDir, -1); + return bestDir; } - if (move == -1) { - // if the move is -1, we are at the root of the tree - // we will have dynamic depth based on the number of empty tiles - // the less empty tiles, the more depth - depth = max(depth * (SIZE - g.getEmpty() / SIZE) / SIZE, 4); + inline int evaluate(const grid& g) { + return (g.getEmpty() << 16) + g.getScore(); } - for (int dir : DIRECTIONS) { - grid g1(g); - g1.move(dir); - int score = bestMove(g1, depth - 1, bestScore, bestDir, (move == -1 ? dir : move)); - if (score > bestScore) { - bestScore = score; - bestDir = move; + namespace { + int bestMoveHelper(const grid& g, int depth, int &bestScore, int &bestDir, int move) { + if (depth == 0 || g.isBlocked()) { + return evaluate(g); + } + + if (move == -1) { + // if the move is -1, we are at the root of the tree + // we will have dynamic depth based on the number of empty tiles + // the less empty tiles, the more depth + depth = max(depth * (SIZE - g.getEmpty() / SIZE) / SIZE, 4); + } + + for (int dir : DIRECTIONS) { + grid g1(g); + g1.move(dir); + int score = bestMoveHelper(g1, depth - 1, bestScore, bestDir, (move == -1 ? dir : move)); + if (score > bestScore) { + bestScore = score; + bestDir = move; + } + } + + return bestScore; } } - return bestScore; } \ No newline at end of file diff --git a/move.h b/move.h index 109f484..048af39 100644 --- a/move.h +++ b/move.h @@ -7,6 +7,13 @@ #include "move.h" #include "grid.h" -int bestMove(const grid& g, int depth, int &bestScore, int &bestDir, int move=-1); +namespace move { + int bestMove(const grid &g, int depth); -inline int evaluate(const grid& g); \ No newline at end of file + inline int evaluate(const grid &g); + + namespace { + int bestMoveHelper(const grid& g, int depth, int &bestScore, int &bestDir, int move); + } + +} \ No newline at end of file