Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "peg_solitaire.h"
- const std::vector<std::pair<int, int>> lab4::peg_solitaire::moves = { {0,2}, {0,-2}, {2,0}, {-2,0} };
- bool lab4::peg_solitaire::is_move_possible(int x_from, int y_from, int x_to, int y_to) const
- {
- if (x_from < 0 || x_from >= width || x_to < 0 || x_to >= width)
- return false;
- if (y_from < 0 || y_from >= height || y_to < 0 || y_to >= height)
- return false;
- if (!((abs(x_from - x_to) == 2 && y_from == y_to) || (abs(y_from - y_to) == 2 && x_from == x_to)))
- return false;
- if (board[y_from*width + x_from] == 0 || board[y_to*width + x_to] != 0 || board[(y_from + y_to)/2*width + (x_from + x_to)/2] == 0)
- return false;
- return true;
- }
- int lab4::peg_solitaire::make_move(int x_from, int y_from, int x_to, int y_to)
- {
- int& from = board[y_from*width + x_from];
- int& over = board[(y_from + y_to) / 2 * width + (x_from + x_to) / 2];
- int score = from * over;
- board[y_to*width + x_to] = from;
- from = 0;
- over = 0;
- --stone_count;
- return score;
- }
- void lab4::peg_solitaire::undo_move(int x_from, int y_from, int x_to, int y_to, int score)
- {
- int& to = board[y_to*width + x_to];
- board[(y_from + y_to) / 2 * width + (x_from + x_to) / 2] = score / to;
- board[y_from*width + x_from] = to;
- to = 0;
- ++stone_count;
- }
- bool lab4::can_win(peg_solitaire game)
- {
- if (game.stone_count == 1)
- return true;
- bool canwin = false;
- int score = 0;
- for (int y = 0; y < game.height; ++y)
- {
- for (int x = 0; x < game.width; ++x)
- {
- for (const std::pair<int, int>& pair : game.moves)
- {
- if (game.is_move_possible(x, y, x + pair.first, y + pair.second))
- {
- score = game.make_move(x, y, x + pair.first, y + pair.second);
- canwin = canwin || can_win(game);
- if (canwin) return canwin;
- game.undo_move(x, y, x + pair.first, y + pair.second, score);
- }
- }
- }
- }
- return canwin;
- }
- int lab4::best_win_score(peg_solitaire game)
- {
- if (game.stone_count == 1)
- return 0;
- int best_score = -1;
- int score;
- int this_best_score;
- for (int y = 0; y < game.height; ++y)
- {
- for (int x = 0; x < game.width; ++x)
- {
- for (const std::pair<int, int>& pair : game.moves)
- {
- if (game.is_move_possible(x, y, x + pair.first, y + pair.second))
- {
- score = game.make_move(x, y, x + pair.first, y + pair.second);
- this_best_score = best_win_score(game);
- if (this_best_score != -1)
- best_score = std::max(this_best_score + score, best_score);
- game.undo_move(x, y, x + pair.first, y + pair.second, score);
- }
- }
- }
- }
- return best_score;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement