From 819a1064c5142a9b2f04ff8149d34fc915c18322 Mon Sep 17 00:00:00 2001 From: Charlie Blake Date: Fri, 8 Jun 2018 10:31:22 +0100 Subject: Refactor legal moves gen and moves logic --- src/main/evaluation/benchmark.cpp | 2 +- src/main/game/game_state.cpp | 558 --------------------- src/main/game/game_state.h | 111 ---- src/main/game/game_state.legal_moves.cpp | 410 --------------- src/main/game/global_cache.cpp | 8 +- src/main/game/global_cache.h | 4 +- src/main/game/move.cpp | 22 + src/main/game/move.h | 20 + src/main/game/pile.h | 1 + src/main/game/search-state/game_state.cpp | 558 +++++++++++++++++++++ src/main/game/search-state/game_state.h | 119 +++++ .../game/search-state/game_state.legal_moves.cpp | 406 +++++++++++++++ .../input/json-parsing/deal_parser.cpp | 6 +- src/main/input-output/output/state_printer.cpp | 14 +- src/main/input-output/output/state_printer.h | 8 +- src/main/solver/solver.cpp | 41 +- src/main/solver/solver.h | 10 +- src/test/test_helper.cpp | 10 +- src/test/unit_tests/foundations_dominance_test.cpp | 2 +- src/test/unit_tests/global_cache_test.cpp | 2 +- src/test/unit_tests/legal_move_gen_test.cpp | 123 ++--- 21 files changed, 1243 insertions(+), 1192 deletions(-) delete mode 100644 src/main/game/game_state.cpp delete mode 100644 src/main/game/game_state.h delete mode 100644 src/main/game/game_state.legal_moves.cpp create mode 100644 src/main/game/move.cpp create mode 100644 src/main/game/move.h create mode 100644 src/main/game/search-state/game_state.cpp create mode 100644 src/main/game/search-state/game_state.h create mode 100644 src/main/game/search-state/game_state.legal_moves.cpp (limited to 'src') diff --git a/src/main/evaluation/benchmark.cpp b/src/main/evaluation/benchmark.cpp index 0712032..42fff9d 100644 --- a/src/main/evaluation/benchmark.cpp +++ b/src/main/evaluation/benchmark.cpp @@ -7,7 +7,7 @@ #include #include "benchmark.h" -#include "../game/game_state.h" +#include "../game/search-state/game_state.h" #include "../solver/solver.h" using namespace std; diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp deleted file mode 100644 index 2e79f41..0000000 --- a/src/main/game/game_state.cpp +++ /dev/null @@ -1,558 +0,0 @@ -// -// Created by thecharlesblake on 10/24/17. -// - -#include -#include -#include -#include -#include - -#include - -#include "game_state.h" -#include "../../../lib/rapidjson/document.h" -#include "../input-output/input/json-parsing/deal_parser.h" -#include "../input-output/output/state_printer.h" -#include "../input-output/output/log_helper.h" - -using namespace std; -using namespace rapidjson; -using namespace boost; - -typedef sol_rules::build_policy pol; -typedef sol_rules::stock_deal_type sdt; - -////////////////// -// CONSTRUCTORS // -////////////////// - -// A private constructor used by both of the public ones. Initializes all of the -// piles and pile refs specified by the rules -game_state::game_state(const sol_rules& s_rules) : rules(s_rules), - stock(255), - waste(255), - hole(255) { - // If there is a hole, creates pile - if (rules.hole) { - piles.emplace_back(); - hole = static_cast(piles.size() - 1); - } - - // If there are foundation piles, creates the relevant pile vectors - if (rules.foundations) { - for (uint8_t i = 0; i < 4*(rules.two_decks ? 2:1); i++) { - piles.emplace_back(); - foundations.push_back(static_cast(piles.size() - 1)); - auto_foundation_moves.push_back(true); - } - } - - // If there are cell piles, creates the relevant cell vectors - if (rules.cells > 0) { - for (uint8_t i = 0; i < rules.cells; i++) { - piles.emplace_back(); - cells.push_back(static_cast(piles.size() - 1)); - original_cells.push_back(static_cast(piles.size() - 1)); - } - } - - // If there is a stock, creates a pile - if (rules.stock_size > 0) { - piles.emplace_back(); - stock = static_cast(piles.size() - 1); - - // If the stock deals to a waste, create the waste - if (rules.stock_deal_t == sdt::WASTE) { - piles.emplace_back(); - waste = static_cast(piles.size() - 1); - } - } - - // If there is a reserve, creates piles - if (rules.reserve_size > 0) { - uint8_t pile_count = rules.reserve_stacked ? - uint8_t(1) : rules.reserve_size; - for (uint8_t i = 0; i < pile_count; i++) { - piles.emplace_back(); - reserve.push_back(static_cast(piles.size() - 1)); - original_reserve.push_back(static_cast(piles.size() - 1)); - } - } - - // Creates the tableau piles - for (uint8_t i = 0; i < rules.tableau_pile_count; i++) { - piles.emplace_back(); - tableau_piles.push_back(static_cast(piles.size() - 1)); - original_tableau_piles.push_back(static_cast(piles.size() - 1)); - } -} - -// Constructs an initial game state from a JSON doc -game_state::game_state(const sol_rules& s_rules, const Document& doc) - : game_state(s_rules) { - deal_parser::parse(*this, doc); -} - -// Constructs an initial game state from a seed -game_state::game_state(const sol_rules& s_rules, int seed) - : game_state(s_rules) { - vector deck = gen_shuffled_deck(seed, rules.max_rank, rules.two_decks); - - // If there is a hole, moves the ace of spades to it - if (rules.hole) { - deck.erase(find(begin(deck), end(deck), card("AS"))); - place_card(hole, card("AS")); - } - - // If the foundations begin filled, then fills them - if (rules.foundations_init_card) { - for (uint8_t f_idx = 0; f_idx < 4*(rules.two_decks ? 2:1); f_idx++) { - card c = card(f_idx % uint8_t(4), 1); - - deck.erase(find(begin(deck), end(deck), c)); - place_card(foundations[f_idx], c); - } - } - - // If there is a stock, deals to it and set up a waste pile too - if (rules.stock_size > 0) { - for (unsigned int i = 0; i < rules.stock_size; i++) { - place_card(stock, deck.back()); - deck.pop_back(); - } - } - - // If there is a reserve, deals to it. - // We treat a regular reserve like multiple single-card piles, - // but a stacked reserve as a single multiple-card pile. - if (rules.reserve_size > 0) { - for (unsigned int i = 0; i < rules.reserve_size; i++) { - int idx = rules.reserve_stacked ? 0 : i; - place_card(original_reserve[idx], deck.back()); - deck.pop_back(); - } - } - - // This only occurs during testing - if (rules.tableau_pile_count == 0) return; - - // Deals to the tableau piles (row-by-row) - for (int t = 0; !deck.empty(); t++) { - card c = deck.back(); - - // Add the randomly generated card to the tableau piles - auto p = t % original_tableau_piles.size(); - - // If we are doing a diagonal deal, each row should have one fewer card. - // Leftover cards are dealt normally in full rows. - auto row_idx = t / original_tableau_piles.size(); - if (rules.diagonal_deal && row_idx < original_tableau_piles.size()) { - p = original_tableau_piles.size()-p-1; - pile_ref tableau_pile = original_tableau_piles[p]; - - if (p >= row_idx) { - place_card(tableau_pile, c); - deck.pop_back(); - } - } else { - pile_ref tableau_pile = original_tableau_piles[p]; - place_card(tableau_pile, c); - deck.pop_back(); - } - } - - // The size of all piles must equal the deck size - int piles_sz = 0; - for (auto& p : piles) piles_sz += p.size(); - if (piles_sz != rules.max_rank * (rules.two_decks ? 8:4)) { - throw runtime_error("Error: incorrect number of cards in starting piles"); - } -} - -game_state::game_state(const sol_rules& s_rules, - std::initializer_list il) - : game_state(s_rules) { - pile_ref pr = 0; - for (const pile& p : il) { - for (const card c : p.pile_vec) { - place_card(pr, c); - } - pr++; - } -} - -// Generates a randomly ordered vector of cards -vector game_state::gen_shuffled_deck(int seed, card::rank_t max_rank, - bool two_decks) { - vector values; - vector v_ptrs; - for (int i = 0; i < max_rank * 4; i++) { - values.emplace_back(i); - if (two_decks) values.emplace_back(i); - } - for (auto& v : values) { - v_ptrs.emplace_back(&v); - } - - // Randomly shuffle the pointers - auto rng = default_random_engine(seed+1); - shuffle(begin(v_ptrs), end(v_ptrs), rng); - - vector deck; - for (uint8_t *i : v_ptrs) { - auto r = static_cast(((*i) % max_rank) + 1); - card::suit_t s = (*i) / max_rank; - deck.emplace_back(card(s, r)); - } - - assert(deck.size() == pile::size_type(max_rank * (two_decks ? 8 : 4))); - return deck; -} - -const pile::size_type game_state::move::dominance_flag = pile::max_size_type; - -game_state::move::move(pile_ref f, pile_ref t, pile::size_type i) - : from(f), to(t), count(i) { - assert(i >= 1); -} - -// Returns true is the move has been flagged as a special 'dominance' move -bool game_state::move::is_dominance() const { - return count == dominance_flag; -} - - -///////////////////////// -// MODIFYING FUNCTIONS // -///////////////////////// - -void game_state::make_move(const move m) { - // Handles stock moves - if (m.from == stock) { - // Handles special stock-to-tableau-piles move - if (rules.stock_deal_t == sdt::TABLEAU_PILES) { - assert(m.from == stock); - assert(m.to == 255); - - for (pile_ref tab_pr = original_tableau_piles.front(); - tab_pr < pile_ref(original_tableau_piles.front() + m.count); - tab_pr++) { - place_card(tab_pr, take_card(stock)); - } - } - // Handles stock-to-waste moves - else { - if (piles[stock].empty()) { - // Re-deal waste back to stock - while (!piles[waste].empty()) { - place_card(stock, take_card(waste)); - } - } else { - assert(m.to == waste); - for (int i = 0; i < m.count; i++) { - place_card(waste, take_card(stock)); - } - } - } - } - - // If this is not a built-pile move - else if (m.count == 1 || m.is_dominance()) { - assert(m.from < piles.size()); - assert(m.to < piles.size()); - - place_card(m.to, take_card(m.from)); -#ifndef NO_AUTO_FOUNDATIONS - update_auto_foundation_moves(m.to); -#endif - } - - // If this is a built-pile move - else { - assert(m.from < piles.size() ); - assert(m.to < piles.size() ); - assert(m.count <= rules.max_rank); - - // Adds the cards to the 'to' pile - for (auto pile_idx = m.count; pile_idx-- > 0;) { - place_card(m.to, piles[m.from][pile_idx]); - } - - // Removes the cards from the 'from' pile - for (uint8_t rem_count = 0; rem_count < m.count; rem_count++) { - take_card(m.from); - } - } -} - -void game_state::undo_move(const move m) { - assert(m.from < piles.size()); - - // Handles stock moves - if (m.from == stock) { - // Handles special stock-to-tableau-piles move - if (rules.stock_deal_t == sdt::TABLEAU_PILES) { - for (pile_ref tab_pr = original_tableau_piles.front() + m.count; - tab_pr-- > original_tableau_piles.front(); - ) { - place_card(stock, take_card(tab_pr)); - } - } - // Handles stock-to-waste moves - else { - if (piles[waste].empty()) { - // Re-deal waste back to stock - while (!piles[stock].empty()) { - place_card(waste, take_card(stock)); - } - } else { - for (int i = 0; i < m.count; i++) { - place_card(stock, take_card(waste)); - } - } - } - } - - // If this is not a built-pile move - else if (m.count == 1 || m.is_dominance()) { - assert(m.to < piles.size()); - place_card(m.from, take_card(m.to)); -#ifndef NO_AUTO_FOUNDATIONS - update_auto_foundation_moves(m.from); -#endif - } - - // If this is a built-pile move - else { - assert(m.to < piles.size()); - assert(m.count <= rules.max_rank); - // Adds the cards to the 'from' pile - for (auto pile_idx = m.count; pile_idx-- > 0;) { - place_card(m.from, piles[m.to][pile_idx]); - } - - // Removes the cards from the 'to' pile - for (uint8_t rem_count = 0; rem_count < m.count; rem_count++) { - take_card(m.to); - } - } -} - -// Places a card on a pile and if it is on a tableau, cell or reserve pile, -// reorders the pile refs so that the largest pile is first -void game_state::place_card(pile_ref pr, card c) { - piles[pr].place(c); -#ifndef NO_PILE_SYMMETRY - // If the stock deals to the tableau piles, there is no pile symmetry - if (rules.stock_size == 0 || rules.stock_deal_t != sdt::TABLEAU_PILES) { - eval_pile_order(pr, true); - } -#endif -} - -// Same as above but for taking cards -card game_state::take_card(pile_ref pr) { - card c = piles[pr].take(); -#ifndef NO_PILE_SYMMETRY - // If the stock deals to the tableau piles, there is no pile symmetry - if (rules.stock_size == 0 || rules.stock_deal_t != sdt::TABLEAU_PILES) { - eval_pile_order(pr, false); - } -#endif - return c; -} - -// Assesses whether the pile ref that was modified was a tableau, cell or -// reserve pile, and if so makes the relevant function call -void game_state::eval_pile_order(pile_ref pr, bool is_place) { - if (!original_tableau_piles.empty() - && pr >= original_tableau_piles[0] - && pr < original_tableau_piles[0] + original_tableau_piles.size()) { - - eval_pile_order(tableau_piles, pr, is_place); - } else if (!original_cells.empty() - && pr >= original_cells[0] - && pr < original_cells[0] + original_cells.size()) { - - eval_pile_order(cells, pr, is_place); - } else if (!original_reserve.empty() - && pr >= original_reserve[0] - && pr < original_reserve[0] + original_reserve.size()) { - - eval_pile_order(reserve, pr, is_place); - } -} - -// Finds the pile ref in the list and evaluates whether it should be moved to -// maintain the "pile order" -void game_state::eval_pile_order(list& pile_lst, pile_ref changed_pr, - bool is_place) { - // Finds the first pile that is larger/smaller than the ref pile - // (the comp pile). - // If the card has been placed, search for the ref from the right hand side - // and if not from the lhs - if (is_place) { - auto changed_ref_iter = find(rbegin(pile_lst), rend(pile_lst), changed_pr); - auto comp_iter = changed_ref_iter; - - while (++comp_iter != rend(pile_lst) - && piles[*comp_iter] < piles[*changed_ref_iter]); - - if (comp_iter != ++changed_ref_iter) { - // Places the ref pile before the comp pile - pile_lst.insert(comp_iter.base(), changed_pr); - pile_lst.erase(changed_ref_iter.base()); - } - } else { - auto changed_ref_iter = find(begin(pile_lst), end(pile_lst), changed_pr); - auto comp_iter = changed_ref_iter; - - while (++comp_iter != end(pile_lst) - && piles[*comp_iter] > piles[*changed_ref_iter]); - - if (comp_iter != ++changed_ref_iter) { - // Places the ref pile before the comp pile - pile_lst.insert(comp_iter, changed_pr); - pile_lst.erase(--changed_ref_iter); - } - } - -#ifndef NDEBUG - // Makes sure the piles are in order - if (pile_lst.size() > 1) { - auto prev = begin(pile_lst); - auto cur = begin(pile_lst); - cur++; - - while (cur != end(pile_lst)) { - assert(piles[*prev] >= piles[*cur]); - prev++; cur++; - } - } -#endif -} - -// Decides which 'auto foundation' booleans should be 'true' currently -void game_state::update_auto_foundation_moves(pile_ref target_pile) { - // If there are no foundations, or this is not a foundation move, do nothing - if (!rules.foundations - || target_pile < foundations.front() - || target_pile > foundations.back()) { - return; - } - - // Turns the 'auto' boolean for the target foundation false - - for (pile_ref pr : foundations) { - auto_foundation_moves[pr] = is_valid_auto_foundation_move(pr); - } -} - -bool game_state::is_valid_auto_foundation_move(pile_ref target_pile) const { -#ifndef AUTO_FOUNDATIONS_STREAMLINER - if (rules.build_pol == pol::NO_BUILD || rules.build_pol == pol::SAME_SUIT) -#endif - return true; - - card::suit_t target_suit(target_pile - foundations.front()); - card::rank_t target_rank = piles[target_pile].empty() - ? card::rank_t(0) - : piles[target_pile].top_card().get_rank(); - // The card to be moved up - card move_up_card(target_suit, card::rank_t(target_rank + 1)); - - // The max difference between the 'move up' card and the foundations of the - // same colour and the other colour - int same_rank_diff = 0; - int other_rank_diff = 0; - for (pile_ref pr : foundations) { - if (pr == target_pile) continue; - - card::suit_t s(pr - foundations.front()); - card::rank_t r = piles[pr].empty() ? card::rank_t(0) - : piles[pr].top_card().get_rank(); - card c(s, r); - - auto rank_diff = int(move_up_card.get_rank() - r); - if (move_up_card.get_suit() == c.get_suit() - || (rules.build_pol == pol::RED_BLACK - && move_up_card.get_colour() == c.get_colour())) { - same_rank_diff = rank_diff; - } else { - other_rank_diff = max(other_rank_diff, rank_diff); - } - } - - bool other_within_1 = other_rank_diff <= 1; - bool other_within_2 = other_rank_diff <= 2; - bool same_within_3 = same_rank_diff <= 3; - - if (rules.build_pol == pol::RED_BLACK) { - return other_within_1 || (other_within_2 && same_within_3); - } else { - assert(rules.build_pol == pol::ANY_SUIT); - return other_within_2; - } -} - - -//////////////////////// -// INSPECT GAME STATE // -//////////////////////// - -bool game_state::is_solved() const { - bool solved = true; - if (rules.hole) { - solved = piles[hole].size() - == rules.max_rank * 4 * (rules.two_decks ? 2 : 1); - } else { - assert(rules.foundations); - for (auto f : foundations) { - if (piles[f].size() != rules.max_rank) { - solved = false; - } - } - } - - // Runs some alternative checks in debug mode to make sure the game state - // is consistent -#ifndef NDEBUG - bool rest_empty = true; - for (pile_ref pr = 0; pr < piles.size(); pr++) { - // All piles other than the hole must be empty - if (rules.hole) { - if (pr != hole && !piles[pr].empty()) { - rest_empty = false; - break; - } - } - // All piles other than the foundations must be empty - else { - bool non_foundation_ref = - pr < foundations.front() - || pr >= foundations.front() + foundations.size(); - if (non_foundation_ref && !piles[pr].empty()) { - rest_empty = false; - break; - } - } - } - assert(solved == rest_empty); -#endif - - return solved; -} - -const std::vector& game_state::get_data() const { - return piles; -} - - -/////////// -// PRINT // -/////////// - -ostream& operator<< (ostream& str, const game_state& gs) { - return state_printer::print(str, gs); -} diff --git a/src/main/game/game_state.h b/src/main/game/game_state.h deleted file mode 100644 index 1e527ea..0000000 --- a/src/main/game/game_state.h +++ /dev/null @@ -1,111 +0,0 @@ -// -// Created by thecharlesblake on 10/24/17. -// - -#ifndef SOLVITAIRE_GAME_STATE_H -#define SOLVITAIRE_GAME_STATE_H - -#include -#include -#include - -#include -#include - -#include "../../../lib/rapidjson/document.h" -#include "card.h" -#include "pile.h" -#include "sol_rules.h" - -class game_state { - friend class deal_parser; - friend class state_printer; - friend class predicate; - friend class hasher; - friend class global_cache; - friend class cached_game_state; -public: - // Defines types - typedef uint8_t pile_ref; - struct move { - move(pile_ref, pile_ref, pile::size_type = 1); - bool is_dominance() const; - friend bool operator==(const move&, const move&); - - const static pile::size_type dominance_flag; - pile_ref from; pile_ref to; pile::size_type count; - }; - - // Constructors - // Creates a game state representation from a JSON doc - game_state(const sol_rules&, const rapidjson::Document&); - // Does the same from a seed - game_state(const sol_rules&, int seed); - // Does the same but with an initialiser list (useful for testing) - game_state(const sol_rules&, std::initializer_list); - - // Alters state - void make_move(move); - void undo_move(move); - void place_card(pile_ref, card); - card take_card(pile_ref); - - std::vector get_legal_moves(move = move(255, 255, 255)); - - // Inspects state - bool is_solved() const; - const std::vector& get_data() const; - boost::optional get_dominance_move() const; - - friend std::ostream& operator<< (std::ostream&, const game_state&); - -private: - static std::vector gen_shuffled_deck(int, card::rank_t, bool); - - // Private constructor - explicit game_state(const sol_rules&); - - // Used to maintain pile order invariant - void eval_pile_order(pile_ref, bool); - void eval_pile_order(std::list&, pile_ref, bool); - - // Used in get_legal_moves() - move get_stock_tableau_move() const; - bool is_valid_tableau_move(pile_ref, pile_ref) const; - bool is_valid_foundations_move(pile_ref, pile_ref) const; - bool is_valid_hole_move(pile_ref) const; - void get_built_group_moves(std::vector&) const; - pile::size_type get_built_group_height(pile_ref) const; - bool valid_built_group_move(card, card, card) const; - void add_built_group_move(std::vector&, pile_ref, pile_ref) const; - void add_empty_built_group_moves(std::vector&, pile_ref, pile_ref, - card) const; - bool dominance_blocks_foundation_move(pile_ref); - bool is_ordered_pile(pile_ref) const; - - void update_auto_foundation_moves(pile_ref); - bool is_valid_auto_foundation_move(pile_ref) const; - - // References to piles - const sol_rules rules; - std::list tableau_piles; - std::list cells; - pile_ref stock; - pile_ref waste; - std::list reserve; - std::vector foundations; - pile_ref hole; - - // Stores the original pile refs of the commutative piles so that they can - // be printed in the order the user expects - std::vector original_tableau_piles; - std::vector original_cells; - std::vector original_reserve; - - std::vector auto_foundation_moves; - - // The core piles - std::vector piles; -}; - -#endif //SOLVITAIRE_GAME_STATE_H diff --git a/src/main/game/game_state.legal_moves.cpp b/src/main/game/game_state.legal_moves.cpp deleted file mode 100644 index 5a49ec9..0000000 --- a/src/main/game/game_state.legal_moves.cpp +++ /dev/null @@ -1,410 +0,0 @@ -// -// Created by thecharlesblake on 1/3/18. -// - -#include - -#include "game_state.h" - -using namespace std; -using namespace boost; - -typedef sol_rules::build_policy pol; -typedef sol_rules::spaces_policy s_pol; -typedef sol_rules::stock_deal_type sdt; - -vector game_state::get_legal_moves(move parent_move) { - // The next legal moves - vector moves; - - // If we have a stock that can deal to the tableau piles, adds this move - if (rules.stock_size > 0 - && rules.stock_deal_t == sdt::TABLEAU_PILES - && !piles[stock].empty()) { - - moves.emplace_back(get_stock_tableau_move()); - } - - // If the stock is empty and we are allowed to re-deal, move the waste - // back onto the stock - if (rules.stock_size > 0 - && rules.stock_redeal - && rules.stock_deal_t == sdt::WASTE - && piles[stock].empty() - && !piles[waste].empty()) { - moves.emplace_back(stock, waste); - } - - // Cycles through each pile which we may be able to remove a card from - for (pile_ref rem_ref = 0; rem_ref < piles.size(); rem_ref++) { - // Never removes a card from the hole, an empty pile, or the pile we - // just moved a card to - if ((rules.hole && rem_ref == hole) - || piles[rem_ref].empty() - || (rem_ref == parent_move.to - && parent_move.count <= 1 - && parent_move.from != stock) - ) continue; - - // If we have a foundations card as the rem_ref - if (rules.foundations - && rem_ref >= foundations.front() - && rem_ref <= foundations.back()) { - - // If the foundations are removable, checks to see if a dominance - // prevents us from removing from it. Otherwise, skips the pile ref - if (!rules.foundations_removable -#ifndef NO_AUTO_FOUNDATIONS - || dominance_blocks_foundation_move(rem_ref) -#endif - ) { - continue; - } - } - - // Stock cards can only be moved to the waste (assuming there is a waste) - if (rules.stock_size > 0 && rem_ref == stock) { - if (rules.stock_deal_t == sdt::WASTE) { - uint8_t cards_to_move = - min(rules.stock_deal_count, piles[stock].size()); - moves.emplace_back(stock, waste, cards_to_move); - } - continue; - } - - // For each tableau pile, check if moving from the rem pile is a valid - // tableau move according to the rules - for (auto add_ref : tableau_piles) { - if (is_valid_tableau_move(rem_ref, add_ref)) { - moves.emplace_back(rem_ref, add_ref); - } - } - - // Any card can be moved to a cell, so long as the cell isn't full - for (auto add_ref : cells) { - if (add_ref != rem_ref && piles[add_ref].empty()) { - moves.emplace_back(rem_ref, add_ref); - } - } - - // For each foundation pile, check if moving from the rem pile is a valid - // move according to the rules - for (auto add_ref : foundations) { - if (is_valid_foundations_move(rem_ref, add_ref)) { - moves.emplace_back(rem_ref, add_ref); - } - } - - // Does the same for the hole - if (rules.hole && is_valid_hole_move(rem_ref)) { - moves.emplace_back(rem_ref, hole); - } - - // Note that the stock and the reserve aren't mentioned here, as - // they cannot be added to - } - - if (rules.move_built_group) { - get_built_group_moves(moves); - } - - // If only complete built piles can be moved to the foundations, - if (rules.foundations_comp_piles) { - for (pile_ref tab_pr : tableau_piles) { - if (is_ordered_pile(tab_pr)) { - - for (pile_ref found_pr : foundations) { - if (piles[found_pr].empty()) { - moves.emplace_back(tab_pr, found_pr, rules.max_rank); - break; - } - } - } - } - } - - - return moves; -} - -// This is a special kind of move which the solver handles differently. Hence -// the arbitrary second param. We must supply the number of stock cards -// that we will deal, so that the move can be undone in backtracking -game_state::move game_state::get_stock_tableau_move() const { - pile::size_type stock_moves = - piles[stock].size() >= tableau_piles.size() - ? pile::size_type(tableau_piles.size()) - : piles[stock].size(); - - assert(stock_moves > 0 && stock_moves <= piles[stock].size()); - return {stock, 255, stock_moves}; -} - -// If a tableau pile is empty and the space policy is -// no-build, do not add. Otherwise any card with the right -// suit/rank can be moved to a tableau -bool game_state::is_valid_tableau_move(const pile_ref rem_ref, - const pile_ref add_ref) const { - if (rem_ref == add_ref) { - return false; - } else if (rules.build_pol == pol::NO_BUILD) { - return false; - } else if (piles[add_ref].empty()) { - switch(rules.spaces_pol) { - case sol_rules::spaces_policy::NO_BUILD: - return false; - case sol_rules::spaces_policy::KINGS: - return piles[rem_ref].top_card().get_rank() == 13; - case sol_rules::spaces_policy::ANY: - return true; - } - } - - card rem_c = piles[rem_ref].top_card(); - card add_c = piles[add_ref].top_card(); - - // Checks violation of same suit policy - if (rules.build_pol == pol::SAME_SUIT - && rem_c.get_suit() != add_c.get_suit()) { - return false; - } - - // Checks violation of red-black suit policy - else if (rules.build_pol == pol::RED_BLACK - && rem_c.get_colour() == add_c.get_colour()) { - return false; - } - - // Checks rank - else if (rem_c.get_rank() + 1 != add_c.get_rank()) { - return false; - } else { - return true; - } -} - -bool game_state::is_valid_foundations_move(const pile_ref rem_ref, - const pile_ref add_ref) const { - if (rules.foundations_comp_piles || rem_ref == add_ref) return false; - - card rem_c = piles[rem_ref].top_card(); - - // Checks violation of same suit policy - uint8_t suit_idx = (add_ref - foundations.front()) % uint8_t(4); - if (rem_c.get_suit() != suit_idx) { - return false; - } - - // Checks rank - else { - card::rank_t add_rank = piles[add_ref].empty() - ? card::rank_t(0) - : piles[add_ref].top_card().get_rank(); - return rem_c.get_rank() - 1 == add_rank; - } -} - -bool game_state::is_valid_hole_move(const pile_ref rem_ref) const { - if (rem_ref == hole) return false; - card::rank_t rank = piles[rem_ref].top_card().get_rank(); - card::rank_t hole_rank = piles[hole].top_card().get_rank(); - return rank + 1 == hole_rank - || rank - 1 == hole_rank - || (rank == rules.max_rank && hole_rank == 1) - || (rank == 1 && hole_rank == rules.max_rank); -} - - -/////////////////////// -// BUILT-GROUP MOVES // -/////////////////////// - -void game_state::get_built_group_moves(vector& moves) const { - assert(rules.built_group_pol != pol::NO_BUILD); - - // Cycles through each pile to see if it contains a built group of size > 1 - for (auto rem_ref : tableau_piles) { - if (piles[rem_ref].size() < 2) continue; - - auto built_group_height = get_built_group_height(rem_ref); - if (built_group_height == 1) continue; - - // We have found a built group, so cycles through each pile to see if - // this group can be added to it - for (auto add_ref : tableau_piles) { - if (add_ref == rem_ref) continue; - - card bg_low = piles[rem_ref].top_card(); - card bg_high = piles[rem_ref][built_group_height - 1]; - - // If the pile is empty, and we can move to empty piles, does so - if (piles[add_ref].empty()) { - if (rules.spaces_pol == s_pol::ANY || - (rules.spaces_pol == s_pol::KINGS - && bg_high.get_rank() == 13)) { - add_empty_built_group_moves(moves, rem_ref, add_ref, bg_high); - } - } - // Otherwise, checks to see if it is a valid move - else { - card add_card = piles[add_ref].top_card(); - - // Adds the move to the list of moves, as a special built group move - if (valid_built_group_move(bg_low, bg_high, add_card)) { - add_built_group_move(moves, rem_ref, add_ref); - } - } - } - } -} - -// Finds the size of the built group at the top of a pile -pile::size_type game_state::get_built_group_height(pile_ref ref) const { - - // The index of the currently examined card, the current card, previous card - // and whether we currently have a valid built group. - pile::size_type group_card_idx = 0; - bool built_group = true; - - do { - card prev_c = piles[ref][group_card_idx++]; - card c = piles[ref][group_card_idx]; - - // If the build policy is same suit, makes sure group has same suit - if (rules.built_group_pol == pol::SAME_SUIT - && c.get_suit() != prev_c.get_suit()) { - built_group = false; - } - // If the build policy is red black, makes sure group alternates - // in correct phase - else if (rules.built_group_pol == pol::RED_BLACK - && c.get_colour() == prev_c.get_colour()) { - built_group = false; - } - - // Makes sure the rank of the cards is sequential - built_group = built_group - && c.get_rank() == prev_c.get_rank()+1; - - } - // Continues until group_card_idx points to a card outside the built - // Group - while (built_group && group_card_idx < piles[ref].size()); - - return group_card_idx; -} - -bool game_state::valid_built_group_move(card bg_low, card bg_high, card add_card) -const { - // The rank of the card we're moving the built group to must be greater than - // the second-from-top card of the built group, and less than or equal to the - // card that would come next at the top of the built pile - if (add_card.get_rank() <= bg_low.get_rank() + 1 - || add_card.get_rank() > bg_high.get_rank() + 1) { - return false; - } - - // Checks to see if the suits are correct - switch (rules.built_group_pol) { - case pol::SAME_SUIT: - return bg_low.get_suit() == add_card.get_suit(); - - case pol::RED_BLACK: { - bool same_suit = bg_low.get_suit() == add_card.get_suit(); - bool even_diff = (add_card.get_rank() - bg_low.get_rank()) % 2 == 0; - return (same_suit && even_diff) || (!same_suit && !even_diff); - } - default: return true; - } -} - -void game_state::add_built_group_move(vector& moves, pile_ref rem_ref, - pile_ref add_ref) const { - moves.emplace_back(rem_ref, add_ref, 2); -} - -void game_state::add_empty_built_group_moves(vector& moves, - pile_ref rem_ref, - pile_ref add_ref, - card bg_high) const { - // Loops through each possible built group move to an empty pile and adds it - // to the list - pile::size_type card_idx = 1; - do { - moves.emplace_back( - rem_ref, add_ref, static_cast(card_idx + 1) - ); - } while (piles[rem_ref][card_idx++] != bg_high); -} - -///////////////////// -// Dominance Moves // -///////////////////// - -// Returns a dominance move if one is available -optional game_state::get_dominance_move() const { -#ifndef NO_AUTO_FOUNDATIONS - // If there are 2 decks or no foundations, return - if (!rules.foundations || rules.two_decks) - return none; - - // Cycles through the piles and sees if any cards can be automatically moved - // to the foundations - for (pile_ref pr = 0; pr < piles.size(); pr++) { - // Don't move foundation cards, hole or stock cards to the foundations - if ((pr >= foundations.front() && pr <= foundations.back()) - || (rules.hole && pr == hole) - || (rules.stock_size > 0 && pr == stock) - || (piles[pr].empty())) { - continue; - } - - card c = piles[pr].top_card(); - pile_ref target_foundation = foundations[c.get_suit()]; - - // If the card is the right rank and the auto-move boolean is true, then - // returns the move - card::rank_t target_rank = piles[target_foundation].empty() - ? card::rank_t(1) : - piles[target_foundation].top_card().get_rank() - + card::rank_t(1); - if (target_rank == c.get_rank() && - auto_foundation_moves[c.get_suit()]) { - return move(pr, target_foundation, move::dominance_flag); - } - } -#endif - - return none; -} - -bool game_state::is_ordered_pile(pile_ref pr) const { - if (piles[pr].size() != rules.max_rank) return false; - - card::suit_t s = piles[pr][0].get_suit(); - for (card::rank_t r = 0; r < rules.max_rank; r++) { - if (piles[pr][r] != card(s, card::rank_t(r + 1))) return false; - } - return true; -} - -// For games where the foundations can be removed from, this dominance blocks -// the foundations being removed from if the card that were to be removed would -// go 'automatically' up -bool game_state::dominance_blocks_foundation_move(pile_ref target_pile) { - assert(!piles[target_pile].empty()); - - card target_card = piles[target_pile].top_card(); - piles[target_pile].take(); - - bool blocked = is_valid_auto_foundation_move(target_pile); - piles[target_pile].place(target_card); - - return blocked; -} - -bool operator==(const game_state::move& a, const game_state::move& b) { - return (a.from == b.from ) - && (a.to == b.to ) - && (a.count == b.count); -} diff --git a/src/main/game/global_cache.cpp b/src/main/game/global_cache.cpp index f2320ef..3620ddb 100644 --- a/src/main/game/global_cache.cpp +++ b/src/main/game/global_cache.cpp @@ -26,7 +26,7 @@ cached_game_state::cached_game_state(const game_state& gs) { add_card(gs.piles[gs.hole].top_card(), gs); } - for (game_state::pile_ref pr : gs.cells) { + for (pile::ref pr : gs.cells) { add_pile(pr, gs); } if (gs.rules.cells > 0) { @@ -43,21 +43,21 @@ cached_game_state::cached_game_state(const game_state& gs) { } } - for (game_state::pile_ref pr : gs.reserve) { + for (pile::ref pr : gs.reserve) { add_pile(pr, gs); } if (gs.rules.reserve_size > 0) { add_card_divider(); } - for (game_state::pile_ref pr : gs.tableau_piles) { + for (pile::ref pr : gs.tableau_piles) { add_pile(pr, gs); add_card_divider(); } } -void cached_game_state::add_pile(game_state::pile_ref pr, const game_state& gs) { +void cached_game_state::add_pile(pile::ref pr, const game_state& gs) { for (card c : gs.piles[pr].pile_vec) { add_card(c, gs); } diff --git a/src/main/game/global_cache.h b/src/main/game/global_cache.h index b3164ea..9541100 100644 --- a/src/main/game/global_cache.h +++ b/src/main/game/global_cache.h @@ -11,14 +11,14 @@ #include #include "sol_rules.h" -#include "game_state.h" +#include "search-state/game_state.h" struct cached_game_state { typedef std::vector state_data; typedef state_data::size_type size_type; explicit cached_game_state(const game_state&); - void add_pile(game_state::pile_ref, const game_state&); + void add_pile(pile::ref, const game_state&); void add_card(card, const game_state&); void add_card_divider(); diff --git a/src/main/game/move.cpp b/src/main/game/move.cpp new file mode 100644 index 0000000..053b3ba --- /dev/null +++ b/src/main/game/move.cpp @@ -0,0 +1,22 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#include "move.h" + +const pile::size_type move::dominance_flag = pile::max_size_type; + +move::move(pile::ref f, pile::ref t, pile::size_type i) : from(f), to(t), count(i) { + assert(i >= 1); +} + +// Returns true is the move has been flagged as a special 'dominance' move +bool move::is_dominance() const { + return count == dominance_flag; +} + +bool operator==(const move& a, const move& b) { + return (a.from == b.from ) + && (a.to == b.to ) + && (a.count == b.count); +} \ No newline at end of file diff --git a/src/main/game/move.h b/src/main/game/move.h new file mode 100644 index 0000000..81a6116 --- /dev/null +++ b/src/main/game/move.h @@ -0,0 +1,20 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#ifndef SOLVITAIRE_MOVE_H +#define SOLVITAIRE_MOVE_H + +#include "pile.h" + +struct move { + move(pile::ref , pile::ref, pile::size_type = 1); + bool is_dominance() const; + friend bool operator==(const move&, const move&); + + const static pile::size_type dominance_flag; + pile::ref from; pile::ref to; pile::size_type count; +}; + + +#endif //SOLVITAIRE_MOVE_H diff --git a/src/main/game/pile.h b/src/main/game/pile.h index d86ea37..5ab2404 100644 --- a/src/main/game/pile.h +++ b/src/main/game/pile.h @@ -18,6 +18,7 @@ class pile { public: typedef uint8_t size_type; const static size_type max_size_type; + typedef uint8_t ref; pile() = default; pile(std::vector); diff --git a/src/main/game/search-state/game_state.cpp b/src/main/game/search-state/game_state.cpp new file mode 100644 index 0000000..bd533f1 --- /dev/null +++ b/src/main/game/search-state/game_state.cpp @@ -0,0 +1,558 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#include +#include +#include +#include +#include + +#include +#include + +#include "game_state.h" +#include "document.h" +#include "../../input-output/input/json-parsing/deal_parser.h" +#include "../../input-output/output/state_printer.h" +#include "../../input-output/output/log_helper.h" +#include "../move.h" + +using namespace rapidjson; +using std::vector; +using std::list; +using std::find; +using std::begin; +using std::end; +using std::rbegin; +using std::rend; +using std::runtime_error; +using std::default_random_engine; +using std::max; +using std::ostream; + +typedef sol_rules::build_policy pol; +typedef sol_rules::stock_deal_type sdt; + +////////////////// +// CONSTRUCTORS // +////////////////// + +// A private constructor used by both of the public ones. Initializes all of the +// piles and pile refs specified by the rules +game_state::game_state(const sol_rules& s_rules) : rules(s_rules), + stock(255), + waste(255), + hole(255) { + // If there is a hole, creates pile + if (rules.hole) { + piles.emplace_back(); + hole = static_cast(piles.size() - 1); + } + + // If there are foundation piles, creates the relevant pile vectors + if (rules.foundations) { + for (uint8_t i = 0; i < 4*(rules.two_decks ? 2:1); i++) { + piles.emplace_back(); + foundations.push_back(static_cast(piles.size() - 1)); + auto_foundation_moves.push_back(true); + } + } + + // If there are cell piles, creates the relevant cell vectors + if (rules.cells > 0) { + for (uint8_t i = 0; i < rules.cells; i++) { + piles.emplace_back(); + cells.push_back(static_cast(piles.size() - 1)); + original_cells.push_back(static_cast(piles.size() - 1)); + } + } + + // If there is a stock, creates a pile + if (rules.stock_size > 0) { + piles.emplace_back(); + stock = static_cast(piles.size() - 1); + + // If the stock deals to a waste, create the waste + if (rules.stock_deal_t == sdt::WASTE) { + piles.emplace_back(); + waste = static_cast(piles.size() - 1); + } + } + + // If there is a reserve, creates piles + if (rules.reserve_size > 0) { + uint8_t pile_count = rules.reserve_stacked ? + uint8_t(1) : rules.reserve_size; + for (uint8_t i = 0; i < pile_count; i++) { + piles.emplace_back(); + reserve.push_back(static_cast(piles.size() - 1)); + original_reserve.push_back(static_cast(piles.size() - 1)); + } + } + + // Creates the tableau piles + for (uint8_t i = 0; i < rules.tableau_pile_count; i++) { + piles.emplace_back(); + tableau_piles.push_back(static_cast(piles.size() - 1)); + original_tableau_piles.push_back(static_cast(piles.size() - 1)); + } +} + +// Constructs an initial game state from a JSON doc +game_state::game_state(const sol_rules& s_rules, const Document& doc) + : game_state(s_rules) { + deal_parser::parse(*this, doc); +} + +// Constructs an initial game state from a seed +game_state::game_state(const sol_rules& s_rules, int seed) + : game_state(s_rules) { + vector deck = gen_shuffled_deck(seed, rules.max_rank, rules.two_decks); + + // If there is a hole, moves the ace of spades to it + if (rules.hole) { + deck.erase(find(begin(deck), end(deck), card("AS"))); + place_card(hole, card("AS")); + } + + // If the foundations begin filled, then fills them + if (rules.foundations_init_card) { + for (uint8_t f_idx = 0; f_idx < 4*(rules.two_decks ? 2:1); f_idx++) { + card c = card(f_idx % uint8_t(4), 1); + + deck.erase(find(begin(deck), end(deck), c)); + place_card(foundations[f_idx], c); + } + } + + // If there is a stock, deals to it and set up a waste pile too + if (rules.stock_size > 0) { + for (unsigned int i = 0; i < rules.stock_size; i++) { + place_card(stock, deck.back()); + deck.pop_back(); + } + } + + // If there is a reserve, deals to it. + // We treat a regular reserve like multiple single-card piles, + // but a stacked reserve as a single multiple-card pile. + if (rules.reserve_size > 0) { + for (unsigned int i = 0; i < rules.reserve_size; i++) { + int idx = rules.reserve_stacked ? 0 : i; + place_card(original_reserve[idx], deck.back()); + deck.pop_back(); + } + } + + // This only occurs during testing + if (rules.tableau_pile_count == 0) return; + + // Deals to the tableau piles (row-by-row) + for (int t = 0; !deck.empty(); t++) { + card c = deck.back(); + + // Add the randomly generated card to the tableau piles + auto p = t % original_tableau_piles.size(); + + // If we are doing a diagonal deal, each row should have one fewer card. + // Leftover cards are dealt normally in full rows. + auto row_idx = t / original_tableau_piles.size(); + if (rules.diagonal_deal && row_idx < original_tableau_piles.size()) { + p = original_tableau_piles.size()-p-1; + pile::ref tableau_pile = original_tableau_piles[p]; + + if (p >= row_idx) { + place_card(tableau_pile, c); + deck.pop_back(); + } + } else { + pile::ref tableau_pile = original_tableau_piles[p]; + place_card(tableau_pile, c); + deck.pop_back(); + } + } + + // The size of all piles must equal the deck size + int piles_sz = 0; + for (auto& p : piles) piles_sz += p.size(); + if (piles_sz != rules.max_rank * (rules.two_decks ? 8:4)) { + throw runtime_error("Error: incorrect number of cards in starting piles"); + } +} + +game_state::game_state(const sol_rules& s_rules, + std::initializer_list il) + : game_state(s_rules) { + pile::ref pr = 0; + for (const pile& p : il) { + for (const card c : p.pile_vec) { + place_card(pr, c); + } + pr++; + } +} + +// Generates a randomly ordered vector of cards +vector game_state::gen_shuffled_deck(int seed, card::rank_t max_rank, + bool two_decks) { + vector values; + vector v_ptrs; + for (int i = 0; i < max_rank * 4; i++) { + values.emplace_back(i); + if (two_decks) values.emplace_back(i); + } + for (auto& v : values) { + v_ptrs.emplace_back(&v); + } + + // Randomly shuffle the pointers + auto rng = default_random_engine(seed+1); + shuffle(begin(v_ptrs), end(v_ptrs), rng); + + vector deck; + for (uint8_t *i : v_ptrs) { + auto r = static_cast(((*i) % max_rank) + 1); + card::suit_t s = (*i) / max_rank; + deck.emplace_back(card(s, r)); + } + + assert(deck.size() == pile::size_type(max_rank * (two_decks ? 8 : 4))); + return deck; +} + + +///////////////////////// +// MODIFYING FUNCTIONS // +///////////////////////// + +void game_state::make_move(const move m) { + // Handles stock moves + if (m.from == stock) { + // Handles special stock-to-tableau-piles move + if (rules.stock_deal_t == sdt::TABLEAU_PILES) { + assert(m.from == stock); + assert(m.to == 255); + + for (pile::ref tab_pr = original_tableau_piles.front(); + tab_pr < pile::ref(original_tableau_piles.front() + m.count); + tab_pr++) { + place_card(tab_pr, take_card(stock)); + } + } + // Handles stock-to-waste moves + else { + if (piles[stock].empty()) { + // Re-deal waste back to stock + while (!piles[waste].empty()) { + place_card(stock, take_card(waste)); + } + } else { + assert(m.to == waste); + for (int i = 0; i < m.count; i++) { + place_card(waste, take_card(stock)); + } + } + } + } + + // If this is not a built-pile move + else if (m.count == 1 || m.is_dominance()) { + assert(m.from < piles.size()); + assert(m.to < piles.size()); + + place_card(m.to, take_card(m.from)); +#ifndef NO_AUTO_FOUNDATIONS + update_auto_foundation_moves(m.to); +#endif + } + + // If this is a built-pile move + else { + assert(m.from < piles.size() ); + assert(m.to < piles.size() ); + assert(m.count <= rules.max_rank); + + // Adds the cards to the 'to' pile + for (auto pile_idx = m.count; pile_idx-- > 0;) { + place_card(m.to, piles[m.from][pile_idx]); + } + + // Removes the cards from the 'from' pile + for (uint8_t rem_count = 0; rem_count < m.count; rem_count++) { + take_card(m.from); + } + } +} + +void game_state::undo_move(const move m) { + assert(m.from < piles.size()); + + // Handles stock moves + if (m.from == stock) { + // Handles special stock-to-tableau-piles move + if (rules.stock_deal_t == sdt::TABLEAU_PILES) { + for (pile::ref tab_pr = original_tableau_piles.front() + m.count; + tab_pr-- > original_tableau_piles.front(); + ) { + place_card(stock, take_card(tab_pr)); + } + } + // Handles stock-to-waste moves + else { + if (piles[waste].empty()) { + // Re-deal waste back to stock + while (!piles[stock].empty()) { + place_card(waste, take_card(stock)); + } + } else { + for (int i = 0; i < m.count; i++) { + place_card(stock, take_card(waste)); + } + } + } + } + + // If this is not a built-pile move + else if (m.count == 1 || m.is_dominance()) { + assert(m.to < piles.size()); + place_card(m.from, take_card(m.to)); +#ifndef NO_AUTO_FOUNDATIONS + update_auto_foundation_moves(m.from); +#endif + } + + // If this is a built-pile move + else { + assert(m.to < piles.size()); + assert(m.count <= rules.max_rank); + // Adds the cards to the 'from' pile + for (auto pile_idx = m.count; pile_idx-- > 0;) { + place_card(m.from, piles[m.to][pile_idx]); + } + + // Removes the cards from the 'to' pile + for (uint8_t rem_count = 0; rem_count < m.count; rem_count++) { + take_card(m.to); + } + } +} + +// Places a card on a pile and if it is on a tableau, cell or reserve pile, +// reorders the pile refs so that the largest pile is first +void game_state::place_card(pile::ref pr, card c) { + piles[pr].place(c); +#ifndef NO_PILE_SYMMETRY + // If the stock deals to the tableau piles, there is no pile symmetry + if (rules.stock_size == 0 || rules.stock_deal_t != sdt::TABLEAU_PILES) { + eval_pile_order(pr, true); + } +#endif +} + +// Same as above but for taking cards +card game_state::take_card(pile::ref pr) { + card c = piles[pr].take(); +#ifndef NO_PILE_SYMMETRY + // If the stock deals to the tableau piles, there is no pile symmetry + if (rules.stock_size == 0 || rules.stock_deal_t != sdt::TABLEAU_PILES) { + eval_pile_order(pr, false); + } +#endif + return c; +} + +// Assesses whether the pile ref that was modified was a tableau, cell or +// reserve pile, and if so makes the relevant function call +void game_state::eval_pile_order(pile::ref pr, bool is_place) { + if (!original_tableau_piles.empty() + && pr >= original_tableau_piles[0] + && pr < original_tableau_piles[0] + original_tableau_piles.size()) { + + eval_pile_order(tableau_piles, pr, is_place); + } else if (!original_cells.empty() + && pr >= original_cells[0] + && pr < original_cells[0] + original_cells.size()) { + + eval_pile_order(cells, pr, is_place); + } else if (!original_reserve.empty() + && pr >= original_reserve[0] + && pr < original_reserve[0] + original_reserve.size()) { + + eval_pile_order(reserve, pr, is_place); + } +} + +// Finds the pile ref in the list and evaluates whether it should be moved to +// maintain the "pile order" +void game_state::eval_pile_order(list& pile_lst, pile::ref changed_pr, + bool is_place) { + // Finds the first pile that is larger/smaller than the ref pile + // (the comp pile). + // If the card has been placed, search for the ref from the right hand side + // and if not from the lhs + if (is_place) { + auto changed_ref_iter = find(rbegin(pile_lst), rend(pile_lst), changed_pr); + auto comp_iter = changed_ref_iter; + + while (++comp_iter != rend(pile_lst) + && piles[*comp_iter] < piles[*changed_ref_iter]); + + if (comp_iter != ++changed_ref_iter) { + // Places the ref pile before the comp pile + pile_lst.insert(comp_iter.base(), changed_pr); + pile_lst.erase(changed_ref_iter.base()); + } + } else { + auto changed_ref_iter = find(begin(pile_lst), end(pile_lst), changed_pr); + auto comp_iter = changed_ref_iter; + + while (++comp_iter != end(pile_lst) + && piles[*comp_iter] > piles[*changed_ref_iter]); + + if (comp_iter != ++changed_ref_iter) { + // Places the ref pile before the comp pile + pile_lst.insert(comp_iter, changed_pr); + pile_lst.erase(--changed_ref_iter); + } + } + +#ifndef NDEBUG + // Makes sure the piles are in order + if (pile_lst.size() > 1) { + auto prev = begin(pile_lst); + auto cur = begin(pile_lst); + cur++; + + while (cur != end(pile_lst)) { + assert(piles[*prev] >= piles[*cur]); + prev++; cur++; + } + } +#endif +} + +// Decides which 'auto foundation' booleans should be 'true' currently +void game_state::update_auto_foundation_moves(pile::ref target_pile) { + // If there are no foundations, or this is not a foundation move, do nothing + if (!rules.foundations + || target_pile < foundations.front() + || target_pile > foundations.back()) { + return; + } + + // Turns the 'auto' boolean for the target foundation false + + for (pile::ref pr : foundations) { + auto_foundation_moves[pr] = is_valid_auto_foundation_move(pr); + } +} + +bool game_state::is_valid_auto_foundation_move(pile::ref target_pile) const { +#ifndef AUTO_FOUNDATIONS_STREAMLINER + if (rules.build_pol == pol::NO_BUILD || rules.build_pol == pol::SAME_SUIT) +#endif + return true; + + card::suit_t target_suit(target_pile - foundations.front()); + card::rank_t target_rank = piles[target_pile].empty() + ? card::rank_t(0) + : piles[target_pile].top_card().get_rank(); + // The card to be moved up + card move_up_card(target_suit, card::rank_t(target_rank + 1)); + + // The max difference between the 'move up' card and the foundations of the + // same colour and the other colour + int same_rank_diff = 0; + int other_rank_diff = 0; + for (pile::ref pr : foundations) { + if (pr == target_pile) continue; + + card::suit_t s(pr - foundations.front()); + card::rank_t r = piles[pr].empty() ? card::rank_t(0) + : piles[pr].top_card().get_rank(); + card c(s, r); + + auto rank_diff = int(move_up_card.get_rank() - r); + if (move_up_card.get_suit() == c.get_suit() + || (rules.build_pol == pol::RED_BLACK + && move_up_card.get_colour() == c.get_colour())) { + same_rank_diff = rank_diff; + } else { + other_rank_diff = max(other_rank_diff, rank_diff); + } + } + + bool other_within_1 = other_rank_diff <= 1; + bool other_within_2 = other_rank_diff <= 2; + bool same_within_3 = same_rank_diff <= 3; + + if (rules.build_pol == pol::RED_BLACK) { + return other_within_1 || (other_within_2 && same_within_3); + } else { + assert(rules.build_pol == pol::ANY_SUIT); + return other_within_2; + } +} + + +//////////////////////// +// INSPECT GAME STATE // +//////////////////////// + +bool game_state::is_solved() const { + bool solved = true; + if (rules.hole) { + solved = piles[hole].size() + == rules.max_rank * 4 * (rules.two_decks ? 2 : 1); + } else { + assert(rules.foundations); + for (auto f : foundations) { + if (piles[f].size() != rules.max_rank) { + solved = false; + } + } + } + + // Runs some alternative checks in debug mode to make sure the game state + // is consistent +#ifndef NDEBUG + bool rest_empty = true; + for (pile::ref pr = 0; pr < piles.size(); pr++) { + // All piles other than the hole must be empty + if (rules.hole) { + if (pr != hole && !piles[pr].empty()) { + rest_empty = false; + break; + } + } + // All piles other than the foundations must be empty + else { + bool non_foundation_ref = + pr < foundations.front() + || pr >= foundations.front() + foundations.size(); + if (non_foundation_ref && !piles[pr].empty()) { + rest_empty = false; + break; + } + } + } + assert(solved == rest_empty); +#endif + + return solved; +} + +const std::vector& game_state::get_data() const { + return piles; +} + + +/////////// +// PRINT // +/////////// + +ostream& operator<< (ostream& str, const game_state& gs) { + return state_printer::print(str, gs); +} + diff --git a/src/main/game/search-state/game_state.h b/src/main/game/search-state/game_state.h new file mode 100644 index 0000000..c46f25b --- /dev/null +++ b/src/main/game/search-state/game_state.h @@ -0,0 +1,119 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#ifndef SOLVITAIRE_GAME_STATE_H +#define SOLVITAIRE_GAME_STATE_H + +#include +#include +#include + +#include +#include + +#include "document.h" +#include "../card.h" +#include "../pile.h" +#include "../sol_rules.h" +#include "../move.h" + +class game_state { + friend class hasher; + friend class global_cache; + friend class cached_game_state; + friend class deal_parser; + friend class state_printer; +public: + /* Constructors */ + + // Creates a game state representation from a JSON doc + game_state(const sol_rules&, const rapidjson::Document&); + // Does the same from a seed + game_state(const sol_rules&, int seed); + // Does the same but with an initialiser list (useful for testing) + game_state(const sol_rules&, std::initializer_list); + + /* Altering state */ + + void make_move(move); + void undo_move(move); + void place_card(pile::ref, card); + card take_card(pile::ref); + + /* Legal move generation */ + + std::vector get_legal_moves(move = move(255, 255, 255)); + boost::optional get_dominance_move() const; + + /* State inspection */ + + bool is_solved() const; + const std::vector& get_data() const; + + /* Printing */ + + friend std::ostream& operator<< (std::ostream&, const game_state&); + +private: + /* Constructors (& helper function) */ + + explicit game_state(const sol_rules&); + static std::vector gen_shuffled_deck(int, card::rank_t, bool); + + /* Pile order logic */ + + void eval_pile_order(pile::ref, bool); + void eval_pile_order(std::list&, pile::ref, bool); + + /* Legal move generation */ + + move get_stock_tableau_move() const; + bool is_valid_tableau_move(pile::ref, pile::ref) const; + bool is_valid_foundations_move(pile::ref, pile::ref) const; + bool is_valid_hole_move(pile::ref) const; + void get_built_group_moves(std::vector&) const; + pile::size_type get_built_group_height(pile::ref) const; + bool valid_built_group_move(card, card, card) const; + void add_built_group_move(std::vector&, pile::ref, pile::ref) const; + void add_empty_built_group_moves(std::vector&, pile::ref, pile::ref, + card) const; + bool dominance_blocks_foundation_move(pile::ref); + bool is_ordered_pile(pile::ref) const; + + /* Auto-foundation moves */ + + void update_auto_foundation_moves(pile::ref); + bool is_valid_auto_foundation_move(pile::ref) const; + + + /* Game rules */ + + const sol_rules rules; + + /* Pile references */ + + std::list tableau_piles; + std::list cells; + pile::ref stock; + pile::ref waste; + std::list reserve; + std::vector foundations; + pile::ref hole; + + /* Pile references of starting/original layout */ + + std::vector original_tableau_piles; + std::vector original_cells; + std::vector original_reserve; + + /* Auto-foundation moves state */ + + std::vector auto_foundation_moves; + + /* Core piles */ + + std::vector piles; +}; + +#endif //SOLVITAIRE_GAME_STATE_H diff --git a/src/main/game/search-state/game_state.legal_moves.cpp b/src/main/game/search-state/game_state.legal_moves.cpp new file mode 100644 index 0000000..85b9382 --- /dev/null +++ b/src/main/game/search-state/game_state.legal_moves.cpp @@ -0,0 +1,406 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#include "game_state.h" + +#include + +using std::vector; +using std::min; +using namespace rapidjson; + +typedef sol_rules::build_policy pol; +typedef sol_rules::spaces_policy s_pol; +typedef sol_rules::stock_deal_type sdt; + + +vector game_state::get_legal_moves(move parent_move) { +// The next legal moves + vector moves; + +// If we have a stock that can deal to the tableau piles, adds this move + if (rules.stock_size > 0 + && rules.stock_deal_t == sdt::TABLEAU_PILES + && !piles[stock].empty()) { + + moves.emplace_back(get_stock_tableau_move()); + } + +// If the stock is empty and we are allowed to re-deal, move the waste +// back onto the stock + if (rules.stock_size > 0 + && rules.stock_redeal + && rules.stock_deal_t == sdt::WASTE + && piles[stock].empty() + && !piles[waste].empty()) { + moves.emplace_back(stock, waste); + } + +// Cycles through each pile which we may be able to remove a card from + for (pile::ref rem_ref = 0; rem_ref < piles.size(); rem_ref++) { +// Never removes a card from the hole, an empty pile, or the pile we +// just moved a card to + if ((rules.hole && rem_ref == hole) + || piles[rem_ref].empty() + || (rem_ref == parent_move.to + && parent_move.count <= 1 + && parent_move.from != stock) + ) continue; + +// If we have a foundations card as the rem_ref + if (rules.foundations + && rem_ref >= foundations.front() + && rem_ref <= foundations.back()) { + +// If the foundations are removable, checks to see if a dominance +// prevents us from removing from it. Otherwise, skips the pile ref + if (!rules.foundations_removable + #ifndef NO_AUTO_FOUNDATIONS + || dominance_blocks_foundation_move(rem_ref) +#endif + ) { + continue; + } + } + +// Stock cards can only be moved to the waste (assuming there is a waste) + if (rules.stock_size > 0 && rem_ref == stock) { + if (rules.stock_deal_t == sdt::WASTE) { + uint8_t cards_to_move = + min(rules.stock_deal_count, piles[stock].size()); + moves.emplace_back(stock, waste, cards_to_move); + } + continue; + } + +// For each tableau pile, check if moving from the rem pile is a valid +// tableau move according to the rules + for (auto add_ref : tableau_piles) { + if (is_valid_tableau_move(rem_ref, add_ref)) { + moves.emplace_back(rem_ref, add_ref); + } + } + +// Any card can be moved to a cell, so long as the cell isn't full + for (auto add_ref : cells) { + if (add_ref != rem_ref && piles[add_ref].empty()) { + moves.emplace_back(rem_ref, add_ref); + } + } + +// For each foundation pile, check if moving from the rem pile is a valid +// move according to the rules + for (auto add_ref : foundations) { + if (is_valid_foundations_move(rem_ref, add_ref)) { + moves.emplace_back(rem_ref, add_ref); + } + } + +// Does the same for the hole + if (rules.hole && is_valid_hole_move(rem_ref)) { + moves.emplace_back(rem_ref, hole); + } + +// Note that the stock and the reserve aren't mentioned here, as +// they cannot be added to + } + + if (rules.move_built_group) { + get_built_group_moves(moves); + } + +// If only complete built piles can be moved to the foundations, + if (rules.foundations_comp_piles) { + for (pile::ref tab_pr : tableau_piles) { + if (is_ordered_pile(tab_pr)) { + + for (pile::ref found_pr : foundations) { + if (piles[found_pr].empty()) { + moves.emplace_back(tab_pr, found_pr, rules.max_rank); + break; + } + } + } + } + } + + + return moves; +} + +// This is a special kind of move which the solver handles differently. Hence +// the arbitrary second param. We must supply the number of stock cards +// that we will deal, so that the move can be undone in backtracking +move game_state::get_stock_tableau_move() const { + pile::size_type stock_moves = + piles[stock].size() >= tableau_piles.size() + ? pile::size_type(tableau_piles.size()) + : piles[stock].size(); + + assert(stock_moves > 0 && stock_moves <= piles[stock].size()); + return {stock, 255, stock_moves}; +} + +// If a tableau pile is empty and the space policy is +// no-build, do not add. Otherwise any card with the right +// suit/rank can be moved to a tableau +bool game_state::is_valid_tableau_move(const pile::ref rem_ref, + const pile::ref add_ref) const { + if (rem_ref == add_ref) { + return false; + } else if (rules.build_pol == pol::NO_BUILD) { + return false; + } else if (piles[add_ref].empty()) { + switch(rules.spaces_pol) { + case sol_rules::spaces_policy::NO_BUILD: + return false; + case sol_rules::spaces_policy::KINGS: + return piles[rem_ref].top_card().get_rank() == 13; + case sol_rules::spaces_policy::ANY: + return true; + } + } + + card rem_c = piles[rem_ref].top_card(); + card add_c = piles[add_ref].top_card(); + + // Checks violation of same suit policy + if (rules.build_pol == pol::SAME_SUIT + && rem_c.get_suit() != add_c.get_suit()) { + return false; + } + + // Checks violation of red-black suit policy + else if (rules.build_pol == pol::RED_BLACK + && rem_c.get_colour() == add_c.get_colour()) { + return false; + } + + // Checks rank + else if (rem_c.get_rank() + 1 != add_c.get_rank()) { + return false; + } else { + return true; + } +} + +bool game_state::is_valid_foundations_move(const pile::ref rem_ref, + const pile::ref add_ref) const { + if (rules.foundations_comp_piles || rem_ref == add_ref) return false; + + card rem_c = piles[rem_ref].top_card(); + + // Checks violation of same suit policy + uint8_t suit_idx = (add_ref - foundations.front()) % uint8_t(4); + if (rem_c.get_suit() != suit_idx) { + return false; + } + + // Checks rank + else { + card::rank_t add_rank = piles[add_ref].empty() + ? card::rank_t(0) + : piles[add_ref].top_card().get_rank(); + return rem_c.get_rank() - 1 == add_rank; + } +} + +bool game_state::is_valid_hole_move(const pile::ref rem_ref) const { + if (rem_ref == hole) return false; + card::rank_t rank = piles[rem_ref].top_card().get_rank(); + card::rank_t hole_rank = piles[hole].top_card().get_rank(); + return rank + 1 == hole_rank + || rank - 1 == hole_rank + || (rank == rules.max_rank && hole_rank == 1) + || (rank == 1 && hole_rank == rules.max_rank); +} + + +/////////////////////// +// BUILT-GROUP MOVES // +/////////////////////// + +void game_state::get_built_group_moves(vector& moves) const { + assert(rules.built_group_pol != pol::NO_BUILD); + + // Cycles through each pile to see if it contains a built group of size > 1 + for (auto rem_ref : tableau_piles) { + if (piles[rem_ref].size() < 2) continue; + + auto built_group_height = get_built_group_height(rem_ref); + if (built_group_height == 1) continue; + + // We have found a built group, so cycles through each pile to see if + // this group can be added to it + for (auto add_ref : tableau_piles) { + if (add_ref == rem_ref) continue; + + card bg_low = piles[rem_ref].top_card(); + card bg_high = piles[rem_ref][built_group_height - 1]; + + // If the pile is empty, and we can move to empty piles, does so + if (piles[add_ref].empty()) { + if (rules.spaces_pol == s_pol::ANY || + (rules.spaces_pol == s_pol::KINGS + && bg_high.get_rank() == 13)) { + add_empty_built_group_moves(moves, rem_ref, add_ref, bg_high); + } + } + // Otherwise, checks to see if it is a valid move + else { + card add_card = piles[add_ref].top_card(); + + // Adds the move to the list of moves, as a special built group move + if (valid_built_group_move(bg_low, bg_high, add_card)) { + add_built_group_move(moves, rem_ref, add_ref); + } + } + } + } +} + +// Finds the size of the built group at the top of a pile +pile::size_type game_state::get_built_group_height(pile::ref ref) const { + + // The index of the currently examined card, the current card, previous card + // and whether we currently have a valid built group. + pile::size_type group_card_idx = 0; + bool built_group = true; + + do { + card prev_c = piles[ref][group_card_idx++]; + card c = piles[ref][group_card_idx]; + + // If the build policy is same suit, makes sure group has same suit + if (rules.built_group_pol == pol::SAME_SUIT + && c.get_suit() != prev_c.get_suit()) { + built_group = false; + } + // If the build policy is red black, makes sure group alternates + // in correct phase + else if (rules.built_group_pol == pol::RED_BLACK + && c.get_colour() == prev_c.get_colour()) { + built_group = false; + } + + // Makes sure the rank of the cards is sequential + built_group = built_group + && c.get_rank() == prev_c.get_rank()+1; + + } + // Continues until group_card_idx points to a card outside the built + // Group + while (built_group && group_card_idx < piles[ref].size()); + + return group_card_idx; +} + +bool game_state::valid_built_group_move(card bg_low, card bg_high, card add_card) +const { + // The rank of the card we're moving the built group to must be greater than + // the second-from-top card of the built group, and less than or equal to the + // card that would come next at the top of the built pile + if (add_card.get_rank() <= bg_low.get_rank() + 1 + || add_card.get_rank() > bg_high.get_rank() + 1) { + return false; + } + + // Checks to see if the suits are correct + switch (rules.built_group_pol) { + case pol::SAME_SUIT: + return bg_low.get_suit() == add_card.get_suit(); + + case pol::RED_BLACK: { + bool same_suit = bg_low.get_suit() == add_card.get_suit(); + bool even_diff = (add_card.get_rank() - bg_low.get_rank()) % 2 == 0; + return (same_suit && even_diff) || (!same_suit && !even_diff); + } + default: return true; + } +} + +void game_state::add_built_group_move(vector& moves, pile::ref rem_ref, + pile::ref add_ref) const { + moves.emplace_back(rem_ref, add_ref, 2); +} + +void game_state::add_empty_built_group_moves(vector& moves, + pile::ref rem_ref, + pile::ref add_ref, + card bg_high) const { + // Loops through each possible built group move to an empty pile and adds it + // to the list + pile::size_type card_idx = 1; + do { + moves.emplace_back( + rem_ref, add_ref, static_cast(card_idx + 1) + ); + } while (piles[rem_ref][card_idx++] != bg_high); +} + +///////////////////// +// Dominance Moves // +///////////////////// + +// Returns a dominance move if one is available +boost::optional game_state::get_dominance_move() const { +#ifndef NO_AUTO_FOUNDATIONS + // If there are 2 decks or no foundations, return + if (!rules.foundations || rules.two_decks) + return boost::none; + + // Cycles through the piles and sees if any cards can be automatically moved + // to the foundations + for (pile::ref pr = 0; pr < piles.size(); pr++) { + // Don't move foundation cards, hole or stock cards to the foundations + if ((pr >= foundations.front() && pr <= foundations.back()) + || (rules.hole && pr == hole) + || (rules.stock_size > 0 && pr == stock) + || (piles[pr].empty())) { + continue; + } + + card c = piles[pr].top_card(); + pile::ref target_foundation = foundations[c.get_suit()]; + + // If the card is the right rank and the auto-move boolean is true, then + // returns the move + card::rank_t target_rank = piles[target_foundation].empty() + ? card::rank_t(1) : + piles[target_foundation].top_card().get_rank() + + card::rank_t(1); + if (target_rank == c.get_rank() && + auto_foundation_moves[c.get_suit()]) { + return move(pr, target_foundation, move::dominance_flag); + } + } +#endif + + return boost::none; +} + +bool game_state::is_ordered_pile(pile::ref pr) const { + if (piles[pr].size() != rules.max_rank) return false; + + card::suit_t s = piles[pr][0].get_suit(); + for (card::rank_t r = 0; r < rules.max_rank; r++) { + if (piles[pr][r] != card(s, card::rank_t(r + 1))) return false; + } + return true; +} + +// For games where the foundations can be removed from, this dominance blocks +// the foundations being removed from if the card that were to be removed would +// go 'automatically' up +bool game_state::dominance_blocks_foundation_move(pile::ref target_pile) { + assert(!piles[target_pile].empty()); + + card target_card = piles[target_pile].top_card(); + piles[target_pile].take(); + + bool blocked = is_valid_auto_foundation_move(target_pile); + piles[target_pile].place(target_card); + + return blocked; +} diff --git a/src/main/input-output/input/json-parsing/deal_parser.cpp b/src/main/input-output/input/json-parsing/deal_parser.cpp index f841c8d..29ac3b1 100644 --- a/src/main/input-output/input/json-parsing/deal_parser.cpp +++ b/src/main/input-output/input/json-parsing/deal_parser.cpp @@ -3,7 +3,7 @@ // #include "deal_parser.h" -#include "../../../game/game_state.h" +#include "../../../game/search-state/game_state.h" #include "json_helper.h" using namespace std; @@ -166,9 +166,9 @@ void deal_parser::parse_reserve(game_state &gs, const Document& doc) { json_helper::json_parse_err("Incorrect reserve size"); } - for (game_state::pile_ref i = 0; i < json_card_arr.Size(); i++) { + for (pile::ref i = 0; i < json_card_arr.Size(); i++) { assert(json_card_arr[i].IsString()); - game_state::pile_ref pr = gs.original_reserve[0]; + pile::ref pr = gs.original_reserve[0]; if (!gs.rules.reserve_stacked) pr += i; gs.place_card(pr, card(json_card_arr[i].GetString())); } diff --git a/src/main/input-output/output/state_printer.cpp b/src/main/input-output/output/state_printer.cpp index 0fdacae..9d13129 100644 --- a/src/main/input-output/output/state_printer.cpp +++ b/src/main/input-output/output/state_printer.cpp @@ -55,7 +55,7 @@ void state_printer::print_header(ostream& stream, const char* header) { } void state_printer::print_piles(ostream& stream, - const vector& pile_rs, + const vector& pile_rs, const game_state& gs) { bool empty_row = false; pile::size_type row_idx = 0; @@ -65,7 +65,7 @@ void state_printer::print_piles(ostream& stream, while (!empty_row) { // Loops through the current row to determine if it is empty empty_row = true; - for (const game_state::pile_ref pile_r : pile_rs) { + for (const pile::ref pile_r : pile_rs) { if (gs.piles[pile_r].size() > row_idx) { empty_row = false; break; @@ -73,7 +73,7 @@ void state_printer::print_piles(ostream& stream, } if (!empty_row || row_idx == 0) { // Loops through the current (non-empty) row, and outputs the values - for (const game_state::pile_ref pile_r : pile_rs) { + for (const pile::ref pile_r : pile_rs) { const pile& p = gs.piles[pile_r]; if (p.size() > row_idx) { print_card(stream, p[p.size() - 1 - row_idx]); @@ -90,11 +90,11 @@ void state_printer::print_piles(ostream& stream, } void state_printer::print_top_of_piles(ostream& stream, - const vector& vp, + const vector& vp, const game_state& gs) { - vector top(vp); + vector top(vp); - for (game_state::pile_ref p : top) { + for (pile::ref p : top) { if (gs.piles[p].empty()) { stream << "[]"; } else { @@ -106,7 +106,7 @@ void state_printer::print_top_of_piles(ostream& stream, } void state_printer::print_top_of_pile(ostream& stream, - const game_state::pile_ref pile_r, + const pile::ref pile_r, const game_state& gs) { print_top_of_piles(stream, {pile_r}, gs); } diff --git a/src/main/input-output/output/state_printer.h b/src/main/input-output/output/state_printer.h index ae63182..2b2090b 100644 --- a/src/main/input-output/output/state_printer.h +++ b/src/main/input-output/output/state_printer.h @@ -7,7 +7,7 @@ #include -#include "../../game/game_state.h" +#include "../../game/search-state/game_state.h" class state_printer { public: @@ -16,12 +16,12 @@ public: private: static void print_header(std::ostream&, const char*); static void print_piles(std::ostream&, - const std::vector&, + const std::vector&, const game_state&); static void print_top_of_piles(std::ostream&, - const std::vector&, + const std::vector&, const game_state&); - static void print_top_of_pile(std::ostream&, game_state::pile_ref, + static void print_top_of_pile(std::ostream&, pile::ref, const game_state&); static void print_card(std::ostream&, card); }; diff --git a/src/main/solver/solver.cpp b/src/main/solver/solver.cpp index 51cb574..b104da3 100644 --- a/src/main/solver/solver.cpp +++ b/src/main/solver/solver.cpp @@ -9,10 +9,13 @@ #include #include "solver.h" +#include "../game/move.h" #include "../input-output/output/log_helper.h" -using namespace std; -using namespace boost; +using std::atomic; +using std::vector; +using std::cout; +using std::clog; solver::solver(const game_state& gs) : cache(gs) @@ -23,7 +26,7 @@ solver::solver(const game_state& gs) , backtracks(0) , dominance_moves(0) , depth(0) - , root(nullptr, game_state::move(255, 255, 255)) + , root(nullptr, move(255, 255, 255)) , current_node(&root) { } @@ -36,11 +39,11 @@ solver::~solver() { } } -solver::node::node(node* p, const game_state::move m) - : parent(p), move(m), children() { +solver::node::node(node* p, const move m) + : parent(p), mv(m), children() { } -solver::sol_state solver::run(optional &> terminate_solver) { +solver::sol_state solver::run(boost::optional &> terminate_solver) { bool states_exhausted = false; while(!(state.is_solved() || states_exhausted)) { @@ -50,7 +53,7 @@ solver::sol_state solver::run(optional &> terminate_solver) { } #ifndef NDEBUG - if (current_node->move.is_dominance()) { + if (current_node->mv.is_dominance()) { LOG_DEBUG("(dominance move)"); } LOG_DEBUG(state); @@ -58,7 +61,7 @@ solver::sol_state solver::run(optional &> terminate_solver) { // If there is a dominance move available, adds it to the search tree // and repeats. Doesn't cache the state. - optional dominance_move = state.get_dominance_move(); + boost::optional dominance_move = state.get_dominance_move(); if (dominance_move) { // Adds the dominance move as a child of the current search node add_child(*dominance_move); @@ -67,7 +70,7 @@ solver::sol_state solver::run(optional &> terminate_solver) { bool is_new_state = cache.insert(state); if (is_new_state) { // Gets the legal moves in the current state - vector next_moves = get_next_moves(); + vector next_moves = get_next_moves(); // If there are none, reverts to the last node with children if (next_moves.empty()) { @@ -87,9 +90,9 @@ solver::sol_state solver::run(optional &> terminate_solver) { assert(states_exhausted == current_node->children.empty()); if (!states_exhausted) { current_node = ¤t_node->children.back(); - state.make_move(current_node->move); + state.make_move(current_node->mv); depth++; - if (current_node->move.is_dominance()) dominance_moves++; + if (current_node->mv.is_dominance()) dominance_moves++; } states_searched++; @@ -104,19 +107,19 @@ solver::sol_state solver::run(optional &> terminate_solver) { } } -void solver::add_children(std::vector& moves) { +void solver::add_children(std::vector& moves) { current_node->children.reserve(moves.size()); for (auto move : moves) { add_child(move); } } -vector solver::get_next_moves() { - return state.get_legal_moves(current_node->move); +vector solver::get_next_moves() { + return state.get_legal_moves(current_node->mv); } -void solver::add_child(game_state::move move) { - current_node->children.emplace_back(current_node, move); +void solver::add_child(move m) { + current_node->children.emplace_back(current_node, m); } // Called when the current node's children have been exhausted. Travels back up @@ -126,7 +129,7 @@ bool solver::revert_to_last_node_with_children() { if (!current_node->parent) return true; - state.undo_move(current_node->move); + state.undo_move(current_node->mv); depth--; backtracks++; @@ -134,7 +137,7 @@ bool solver::revert_to_last_node_with_children() { // Checks that the state after the undo is in the cache // (as long as the move wasn't a dominance move) - if (!current_node->move.is_dominance()) { + if (!current_node->mv.is_dominance()) { assert(cache.contains(state)); LOG_DEBUG("(undo move)"); } else { @@ -167,7 +170,7 @@ void solver::print_solution() const { if (states_searched > 1) { while (!n->children.empty()) { - state_copy.make_move(n->move); + state_copy.make_move(n->mv); cout << state_copy << "\n"; n = &n->children.back(); } diff --git a/src/main/solver/solver.h b/src/main/solver/solver.h index 77e8bde..21b8d6e 100644 --- a/src/main/solver/solver.h +++ b/src/main/solver/solver.h @@ -18,9 +18,9 @@ public: global_cache cache; struct node { - node(node*, game_state::move); + node(node*, move); node* parent; - const game_state::move move; + const move mv; std::vector children; }; @@ -36,9 +36,9 @@ public: private: bool revert_to_last_node_with_children(); - void add_children(std::vector&); - void add_child(game_state::move); - std::vector get_next_moves(); + void add_children(std::vector&); + void add_child(move); + std::vector get_next_moves(); const game_state init_state; game_state state; diff --git a/src/test/test_helper.cpp b/src/test/test_helper.cpp index 9d928c6..6f2a68d 100644 --- a/src/test/test_helper.cpp +++ b/src/test/test_helper.cpp @@ -5,7 +5,7 @@ #include #include "test_helper.h" -#include "../main/game/game_state.h" +#include "../main/game/search-state/game_state.h" #include "../main/solver/solver.h" #include "../main/input-output/input/json-parsing/json_helper.h" #include "../main/input-output/input/json-parsing/rules_parser.h" @@ -50,10 +50,10 @@ void test_helper::run_foundations_dominance_test(sol_rules::build_policy policy, solver::node const *n = &sol.get_search_tree(); for (card c : cards) { n = &n->children.back(); - ASSERT_TRUE(n->move.is_dominance()); - ASSERT_TRUE(gs.get_data()[n->move.from].top_card() == c); - ASSERT_TRUE(n->move.to >= 0 && n->move.to <= 4); - gs.make_move(n->move); + ASSERT_TRUE(n->mv.is_dominance()); + ASSERT_TRUE(gs.get_data()[n->mv.from].top_card() == c); + ASSERT_TRUE(n->mv.to >= 0 && n->mv.to <= 4); + gs.make_move(n->mv); } ASSERT_TRUE(n->children.empty()); } diff --git a/src/test/unit_tests/foundations_dominance_test.cpp b/src/test/unit_tests/foundations_dominance_test.cpp index 4a7d2aa..8fdc285 100644 --- a/src/test/unit_tests/foundations_dominance_test.cpp +++ b/src/test/unit_tests/foundations_dominance_test.cpp @@ -5,7 +5,7 @@ #include #include "../test_helper.h" -#include "../../main/game/game_state.h" +#include "../../main/game/search-state/game_state.h" #include "../../main/game/global_cache.h" typedef sol_rules::build_policy pol; diff --git a/src/test/unit_tests/global_cache_test.cpp b/src/test/unit_tests/global_cache_test.cpp index 97490ba..6b0accd 100644 --- a/src/test/unit_tests/global_cache_test.cpp +++ b/src/test/unit_tests/global_cache_test.cpp @@ -5,7 +5,7 @@ #include #include "../test_helper.h" -#include "../../main/game/game_state.h" +#include "../../main/game/search-state/game_state.h" #include "../../main/game/global_cache.h" typedef sol_rules::build_policy pol; diff --git a/src/test/unit_tests/legal_move_gen_test.cpp b/src/test/unit_tests/legal_move_gen_test.cpp index 4f4b7ef..84755f6 100644 --- a/src/test/unit_tests/legal_move_gen_test.cpp +++ b/src/test/unit_tests/legal_move_gen_test.cpp @@ -5,19 +5,20 @@ #include #include "../test_helper.h" -#include "../../main/game/game_state.h" +#include "../../main/game/search-state/game_state.h" #include "../../main/game/sol_rules.h" typedef sol_rules::build_policy pol; typedef sol_rules::spaces_policy s_pol; typedef sol_rules::stock_deal_type sdt; -typedef game_state::move mv; -using namespace std; +using std::vector; +using std::ostream; +using std::initializer_list; -bool moves_eq(vector&, vector&); -ostream& operator <<(ostream&, const mv&); -ostream& operator <<(ostream&, const vector&); +bool moves_eq(vector&, vector&); +ostream& operator <<(ostream&, const move&); +ostream& operator <<(ostream&, const vector&); TEST(LegalMoveGen, BuildPolAnySuit) { sol_rules sr; @@ -31,13 +32,13 @@ TEST(LegalMoveGen, BuildPolAnySuit) { {"2S"}, {"AC"} }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(4,0), - mv(4,1), - mv(4,2), - mv(4,3) + vector exp_moves = { + move(4,0), + move(4,1), + move(4,2), + move(4,3) }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -55,11 +56,11 @@ TEST(LegalMoveGen, BuildPolRedBlack) { {"2D"}, {"AC"} }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(4,1), - mv(4,3) + vector exp_moves = { + move(4,1), + move(4,3) }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -77,10 +78,10 @@ TEST(LegalMoveGen, BuildPolSameSuit) { {"2D"}, {"AC"} }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(4,0) + vector exp_moves = { + move(4,0) }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -98,9 +99,9 @@ TEST(LegalMoveGen, BuildPolNoBuild) { {"2D"}, {"AC"} }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { + vector exp_moves = { }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -115,10 +116,10 @@ TEST(LegalMoveGen, SpacesPolAny) { {}, {"AC"} }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(1, 0) + vector exp_moves = { + move(1, 0) }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -134,10 +135,10 @@ TEST(LegalMoveGen, SpacesPolKings) { {"AC"}, {"KD"} }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(2, 0) + vector exp_moves = { + move(2, 0) }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -152,9 +153,9 @@ TEST(LegalMoveGen, SpacesPolNoBuild) { {}, {"AC"} }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { + vector exp_moves = { }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -169,11 +170,11 @@ TEST(LegalMoveGen, MoveBuiltGroupTrue) { {}, {"2C", "AC"} }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(1, 0, 1), - mv(1, 0, 2) + vector exp_moves = { + move(1, 0, 1), + move(1, 0, 2) }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -188,10 +189,10 @@ TEST(LegalMoveGen, MoveBuiltGroupFalse) { {}, {"AC", "2C"} }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(1, 0, 1) + vector exp_moves = { + move(1, 0, 1) }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -209,13 +210,13 @@ TEST(LegalMoveGen, Foundations) { {"AS"}, {"AD"}, }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(4, 0), - mv(5, 1), - mv(6, 2), - mv(7, 3) + vector exp_moves = { + move(4, 0), + move(5, 1), + move(6, 2), + move(7, 3) }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -234,10 +235,10 @@ TEST(LegalMoveGen, FoundationsRemovable) { {}, {} }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(0, 4) + vector exp_moves = { + move(0, 4) }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -252,12 +253,12 @@ TEST(LegalMoveGen, Cells) { {"3D"}, {}, // The cells {"4H"} }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(0, 1), - mv(0, 2), - mv(2, 1) + vector exp_moves = { + move(0, 1), + move(0, 2), + move(2, 1) }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -276,10 +277,10 @@ TEST(LegalMoveGen, StockDealToWaste) { {}, // The waste {}, {}, {} // The tableau piles }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(4, 5) + vector exp_moves = { + move(4, 5) }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -297,10 +298,10 @@ TEST(LegalMoveGen, StockDealToTableau) { {"AC", "AD"}, // The stock {"3H"}, {"5D"}, {"7C"} // The tableau piles }); - vector actual_moves = gs.get_legal_moves(); + vector actual_moves = gs.get_legal_moves(); - vector exp_moves = { - mv(4, 255, 2) // Special stock-to-tableau syntax + vector exp_moves = { + move(4, 255, 2) // Special stock-to-tableau syntax }; ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; @@ -308,10 +309,10 @@ TEST(LegalMoveGen, StockDealToTableau) { -bool moves_eq(vector& exp_moves, vector& actual_moves) { +bool moves_eq(vector& exp_moves, vector& actual_moves) { if (exp_moves.size() != actual_moves.size()) return false; - for (mv m : actual_moves) { + for (move m : actual_moves) { auto it = find(begin(exp_moves), end(exp_moves), m); bool found = it != end(exp_moves); @@ -322,15 +323,15 @@ bool moves_eq(vector& exp_moves, vector& actual_moves) { return true; } -ostream& operator <<(ostream& os, const mv& m) { +ostream& operator <<(ostream& os, const move& m) { return os << "move:(" << int(m.from) << "," << int(m.to) << "," << int(m.count) << ")"; } -ostream& operator <<(ostream& os, const vector& moves) { - for (const mv m : moves) { +ostream& operator <<(ostream& os, const vector& moves) { + for (const move m : moves) { os << m << ",\n"; } return os; -- cgit v1.2.1