diff options
| author | Charlie Blake | 2018-06-10 00:30:55 +0100 |
|---|---|---|
| committer | GitHub | 2018-06-10 00:30:55 +0100 |
| commit | d82642305dbcf53262ff41705a41c6e7c1591161 (patch) | |
| tree | b2bbe8c0aadaec16280f020e55eb55955be43d3f /src/main | |
| parent | Merge pull request #58 from thecharlesblake/fin (diff) | |
| parent | Finish refactoring game state class (diff) | |
| download | metasol-d82642305dbcf53262ff41705a41c6e7c1591161.tar.gz metasol-d82642305dbcf53262ff41705a41c6e7c1591161.zip | |
Merge pull request #59 from thecharlesblake/paper-tidy-up
Paper tidy up
Diffstat (limited to 'src/main')
25 files changed, 1264 insertions, 1295 deletions
diff --git a/src/main/evaluation/benchmark.cpp b/src/main/evaluation/benchmark.cpp index b8866ff..42fff9d 100644 --- a/src/main/evaluation/benchmark.cpp +++ b/src/main/evaluation/benchmark.cpp @@ -7,7 +7,7 @@ #include <numeric> #include "benchmark.h" -#include "../game/game_state.h" +#include "../game/search-state/game_state.h" #include "../solver/solver.h" using namespace std; @@ -47,7 +47,7 @@ void benchmark::run(const sol_rules &rules) { case solver::sol_state::unsolvable: total_unsolvable++; break; - case solver::sol_state::cutoff: + case solver::sol_state::timed_out: assert(false); break; } diff --git a/src/main/game/card.cpp b/src/main/game/card.cpp index a19760b..cfb94a9 100644 --- a/src/main/game/card.cpp +++ b/src/main/game/card.cpp @@ -22,9 +22,9 @@ const card::colour_t card::colour::Red = 1; // A card can either be created using two int values (rank & suit), or // using a string (e.g. "AS") -card::card(suit_t s, rank_t r) : card_suit(s), card_rank(r) {} +card::card(suit_t s, rank_t r) : card_rank(r), card_suit(s) {} -card::card(const char* c) : card_suit(suit_from_str(c)), card_rank(rank_from_str(c)) {} +card::card(const char* c) : card_rank(rank_from_str(c)), card_suit(suit_from_str(c)) {} card::card() : card(0, 0) {} diff --git a/src/main/game/card.h b/src/main/game/card.h index 8d88df8..a4c6b1e 100644 --- a/src/main/game/card.h +++ b/src/main/game/card.h @@ -45,8 +45,8 @@ private: static suit_t suit_from_str(const char* c); static rank_t rank_from_str(const char* c); - suit_t card_suit : 4; rank_t card_rank : 4; + suit_t card_suit : 4; }; bool operator==(const card&, const card&); 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 <vector> -#include <ostream> -#include <random> -#include <algorithm> -#include <functional> - -#include <boost/functional/hash.hpp> - -#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<pile_ref>(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<pile_ref>(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<pile_ref>(piles.size() - 1)); - original_cells.push_back(static_cast<pile_ref>(piles.size() - 1)); - } - } - - // If there is a stock, creates a pile - if (rules.stock_size > 0) { - piles.emplace_back(); - stock = static_cast<pile_ref>(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<pile_ref>(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<pile_ref>(piles.size() - 1)); - original_reserve.push_back(static_cast<pile_ref>(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<pile_ref>(piles.size() - 1)); - original_tableau_piles.push_back(static_cast<pile_ref>(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<card> 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<pile> 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<card> game_state::gen_shuffled_deck(int seed, card::rank_t max_rank, - bool two_decks) { - vector<uint8_t> values; - vector<uint8_t*> 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<card> deck; - for (uint8_t *i : v_ptrs) { - auto r = static_cast<card::rank_t>(((*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_ref>& 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<pile>& 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 <vector> -#include <list> -#include <string> - -#include <boost/functional/hash.hpp> -#include <boost/optional/optional.hpp> - -#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<pile>); - - // Alters state - void make_move(move); - void undo_move(move); - void place_card(pile_ref, card); - card take_card(pile_ref); - - std::vector<move> get_legal_moves(move = move(255, 255, 255)); - - // Inspects state - bool is_solved() const; - const std::vector<pile>& get_data() const; - boost::optional<move> get_dominance_move() const; - - friend std::ostream& operator<< (std::ostream&, const game_state&); - -private: - static std::vector<card> 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>&, 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<move>&) 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<move>&, pile_ref, pile_ref) const; - void add_empty_built_group_moves(std::vector<move>&, 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<pile_ref> tableau_piles; - std::list<pile_ref> cells; - pile_ref stock; - pile_ref waste; - std::list<pile_ref> reserve; - std::vector<pile_ref> 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<pile_ref> original_tableau_piles; - std::vector<pile_ref> original_cells; - std::vector<pile_ref> original_reserve; - - std::vector<bool> auto_foundation_moves; - - // The core piles - std::vector<pile> 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 <boost/optional.hpp> - -#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::move> game_state::get_legal_moves(move parent_move) { - // The next legal moves - vector<move> 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<move>& 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<move>& 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<move>& 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<pile_ref>(card_idx + 1) - ); - } while (piles[rem_ref][card_idx++] != bg_high); -} - -///////////////////// -// Dominance Moves // -///////////////////// - -// Returns a dominance move if one is available -optional<game_state::move> 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 44d4bb7..3620ddb 100644 --- a/src/main/game/global_cache.cpp +++ b/src/main/game/global_cache.cpp @@ -23,21 +23,10 @@ cached_game_state::cached_game_state(const game_state& gs) { data.reserve(52+18); // Enough for each card and up to 18 piles if (gs.rules.hole) { -#ifdef NO_REDUCED_STATE - add_pile(gs.hole, gs); -#else add_card(gs.piles[gs.hole].top_card(), gs); -#endif } - // No need to add foundations for reduced state, as they are implicit in the - // other piles -#ifdef NO_REDUCED_STATE - for (game_state::pile_ref pr : gs.foundations) - add_pile(pr, gs); -#endif - - for (game_state::pile_ref pr : gs.cells) { + for (pile::ref pr : gs.cells) { add_pile(pr, gs); } if (gs.rules.cells > 0) { @@ -54,36 +43,28 @@ 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) { -#ifdef NO_REDUCED_STATE - data.emplace_back(pile()); -#endif +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); } } void cached_game_state::add_card(card c, const game_state& gs) { - -#ifdef NO_REDUCED_STATE - auto& target = data.back().pile_vec; -#else auto& target = data; -#endif // If the game is a 'hole-based' game, or suit-reduction is on, reduces // the cached suit of the card where possible @@ -114,9 +95,7 @@ void cached_game_state::add_card(card c, const game_state& gs) { } void cached_game_state::add_card_divider() { -#ifndef NO_REDUCED_STATE data.emplace_back(0, 0); -#endif } bool operator==(const cached_game_state& a, const cached_game_state& b) { @@ -135,27 +114,12 @@ hasher::hasher(const game_state& gs) : init_gs(gs) { size_t hasher::operator()(const cached_game_state& cgs) const { size_t seed = 0; -#ifdef NO_REDUCED_STATE - for (const pile& d : cgs.data) { -#else for (card d : cgs.data) { -#endif combine(seed, hash_value(d)); } return seed; } -#ifdef NO_REDUCED_STATE -size_t hasher::hash_value(pile const& p) const { - std::size_t seed = 0; - - for(auto first = begin(p.pile_vec); first != end(p.pile_vec); ++first) { - combine(seed, hash_value(*first)); - } - return seed; -} -#endif - std::size_t hasher::combine(std::size_t& seed, std::size_t value) const { return seed ^= value + 0x9e3779b9 + (seed<<6) + (seed>>2); } diff --git a/src/main/game/global_cache.h b/src/main/game/global_cache.h index 4658e52..9541100 100644 --- a/src/main/game/global_cache.h +++ b/src/main/game/global_cache.h @@ -11,20 +11,14 @@ #include <boost/pool/pool_alloc.hpp> #include "sol_rules.h" -#include "game_state.h" +#include "search-state/game_state.h" struct cached_game_state { - typedef std::vector< -#ifdef NO_REDUCED_STATE - pile -#else - card -#endif - > state_data; + typedef std::vector<card> 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(); @@ -37,9 +31,6 @@ struct hasher { std::size_t operator() (const cached_game_state&) const; std::size_t hash_value(const card&) const; -#ifdef NO_REDUCED_STATE - std::size_t hash_value(const pile&) const; -#endif std::size_t combine(std::size_t&, std::size_t) const; const game_state& init_gs; diff --git a/src/main/game/move.cpp b/src/main/game/move.cpp new file mode 100644 index 0000000..ff8269c --- /dev/null +++ b/src/main/game/move.cpp @@ -0,0 +1,19 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#include "move.h" + +move::move(mtype ty, pile::ref f, pile::ref t, pile::size_type i) : type(ty), from(f), to(t), count(i) { +#ifndef NDEBUG + if (ty == mtype::regular) assert(i == 1); + else assert(i >= 1); +#endif +} + +bool operator==(const move& a, const move& b) { + return (a.from == b.from ) + && (a.to == b.to ) + && (a.count == b.count) + && (a.type == b.type ); +} diff --git a/src/main/game/move.h b/src/main/game/move.h new file mode 100644 index 0000000..b852811 --- /dev/null +++ b/src/main/game/move.h @@ -0,0 +1,23 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#ifndef SOLVITAIRE_MOVE_H +#define SOLVITAIRE_MOVE_H + +#include "pile.h" + +struct move { + enum class mtype {regular, dominance, built_group, stock_to_waste, stock_to_tableau, redeal, null}; + + explicit move(mtype, pile::ref = 255 , pile::ref = 255, pile::size_type = 1); + friend bool operator==(const move&, const move&); + + mtype type; + 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<card>); diff --git a/src/main/game/search-state/game_state.auto_foundation_moves.cpp b/src/main/game/search-state/game_state.auto_foundation_moves.cpp new file mode 100644 index 0000000..0b62af4 --- /dev/null +++ b/src/main/game/search-state/game_state.auto_foundation_moves.cpp @@ -0,0 +1,136 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#include "game_state.h" + + +typedef sol_rules::build_policy pol; + +using std::max; + + +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; + } +} + +// Returns a dominance move if one is available +boost::optional<move> 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(move::mtype::dominance, pr, target_foundation); + } + } +#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; +} + +// 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); + } +} 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..0a20f60 --- /dev/null +++ b/src/main/game/search-state/game_state.cpp @@ -0,0 +1,469 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#include <vector> +#include <ostream> +#include <random> +#include <algorithm> +#include <functional> + +#include <boost/functional/hash.hpp> +#include <boost/optional.hpp> + +#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<pile::ref>(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<pile::ref>(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<pile::ref>(piles.size() - 1)); + original_cells.push_back(static_cast<pile::ref>(piles.size() - 1)); + } + } + + // If there is a stock, creates a pile + if (rules.stock_size > 0) { + piles.emplace_back(); + stock = static_cast<pile::ref>(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<pile::ref>(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<pile::ref>(piles.size() - 1)); + original_reserve.push_back(static_cast<pile::ref>(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<pile::ref>(piles.size() - 1)); + original_tableau_piles.push_back(static_cast<pile::ref>(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<card> 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<pile> 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<card> game_state::gen_shuffled_deck(int seed, card::rank_t max_rank, + bool two_decks) { + vector<uint8_t> values; + vector<uint8_t*> 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<card> deck; + for (uint8_t *i : v_ptrs) { + auto r = static_cast<card::rank_t>(((*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; +} + + +//////////////////// +// ALTERING STATE // +//////////////////// + +void game_state::make_move(const move m) { + switch (m.type) { + case move::mtype::regular: + case move::mtype::dominance: + make_regular_move(m); + break; + case move::mtype::built_group: + make_built_group_move(m); + break; + case move::mtype::stock_to_waste: + make_stock_to_waste_move(m); + break; + case move::mtype::stock_to_tableau: + make_stock_to_tableau_move(m); + break; + case move::mtype::redeal: + make_redeal_move(); + break; + case move::mtype::null: + assert(false); + break; + } +} + +void game_state::undo_move(const move m) { + switch (m.type) { + case move::mtype::regular: + case move::mtype::dominance: + undo_regular_move(m); + break; + case move::mtype::built_group: + undo_built_group_move(m); + break; + case move::mtype::stock_to_waste: + undo_stock_to_waste_move(m); + break; + case move::mtype::stock_to_tableau: + undo_stock_to_tableau_move(m); + break; + case move::mtype::redeal: + undo_redeal_move(); + break; + case move::mtype::null: + assert(false); + break; + } +} + +void game_state::make_regular_move(const move m) { + 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 +} + +void game_state::undo_regular_move(const move m) { + assert(m.to < piles.size()); + + place_card(m.from, take_card(m.to)); + +#ifndef NO_AUTO_FOUNDATIONS + update_auto_foundation_moves(m.from); +#endif +} + +void game_state::make_built_group_move(move m) { + assert(rules.move_built_group); + 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_built_group_move(move m) { + assert(rules.move_built_group); + 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); + } +} + +void game_state::make_stock_to_waste_move(const move m) { + assert(rules.stock_deal_t == sdt::WASTE); + + for (int i = 0; i < m.count; i++) { + place_card(waste, take_card(stock)); + } +} + +void game_state::undo_stock_to_waste_move(const move m) { + assert(rules.stock_deal_t == sdt::WASTE); + + for (int i = 0; i < m.count; i++) { + place_card(stock, take_card(waste)); + } +} + +void game_state::make_stock_to_tableau_move(const move m) { + assert(rules.stock_deal_t == sdt::TABLEAU_PILES); + + 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)); + } +} + +void game_state::undo_stock_to_tableau_move(const move m) { + assert(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)); + } +} + +void game_state::make_redeal_move() { + assert(piles[stock].empty()); + + // Re-deal waste back to stock + while (!piles[waste].empty()) { + place_card(stock, take_card(waste)); + } +} + +void game_state::undo_redeal_move() { + assert(piles[waste].empty()); + + while (!piles[stock].empty()) { + place_card(waste, take_card(stock)); + } +} + +// 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; +} + + +//////////////////////// +// 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<pile>& 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..7c0f9ca --- /dev/null +++ b/src/main/game/search-state/game_state.h @@ -0,0 +1,145 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#ifndef SOLVITAIRE_GAME_STATE_H +#define SOLVITAIRE_GAME_STATE_H + +#include <vector> +#include <list> +#include <string> + +#include <boost/functional/hash.hpp> +#include <boost/optional/optional.hpp> + +#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<pile>); + + /* 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<move> get_legal_moves(move = move(move::mtype::regular)); + boost::optional<move> get_dominance_move() const; + + /* State inspection */ + + bool is_solved() const; + const std::vector<pile>& 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<card> 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>&, pile::ref, bool); + + /* Altering state */ + + void make_regular_move(move move); + void undo_regular_move(move move); + void make_built_group_move(move move); + void undo_built_group_move(move move); + void make_stock_to_waste_move(move move); + void undo_stock_to_waste_move(move move); + void make_stock_to_tableau_move(move move); + void undo_stock_to_tableau_move(move move); + void make_redeal_move(); + void undo_redeal_move(); + + /* Legal move generation */ + + bool stock_can_deal_tableau() const; + move get_stock_tableau_move() const; + bool stock_can_redeal() const; + bool undoes_prev_move(pile::ref, move) const; + bool is_foundation(pile::ref) const; + + void add_stock_to_waste_move(std::vector<move>&) const; + void add_tableau_moves(std::vector<move>&, pile::ref) const; + void add_cell_moves(std::vector<move>&, pile::ref) const; + void add_foundation_moves(std::vector<move>&, pile::ref) const; + void add_built_group_moves(std::vector<move> &) const; + void add_foundation_complete_piles_moves(std::vector<move> &) const; + + bool is_valid_tableau_move(pile::ref, pile::ref) const; + bool is_next_tableau_card(card, card) const; + bool is_valid_foundations_move(pile::ref, pile::ref) const; + bool is_valid_hole_move(pile::ref) const; + + pile::size_type get_built_group_height(pile::ref) const; + void add_empty_built_group_moves(std::vector<move>&, pile::ref, pile::ref, + card) const; + bool is_next_built_group_card(card, card) const; + + bool is_next_legal_card(sol_rules::build_policy, card, card) const; + + /* Auto-foundation moves */ + + bool is_valid_auto_foundation_move(pile::ref) const; + bool is_ordered_pile(pile::ref) const; + bool dominance_blocks_foundation_move(pile::ref); + void update_auto_foundation_moves(pile::ref); + + /* Game rules */ + + const sol_rules rules; + + /* Pile references */ + + std::list<pile::ref> tableau_piles; + std::list<pile::ref> cells; + pile::ref stock; + pile::ref waste; + std::list<pile::ref> reserve; + std::vector<pile::ref> foundations; + pile::ref hole; + + /* Pile references of starting/original layout */ + + std::vector<pile::ref> original_tableau_piles; + std::vector<pile::ref> original_cells; + std::vector<pile::ref> original_reserve; + + /* Auto-foundation moves state */ + + std::vector<bool> auto_foundation_moves; + + /* Core piles */ + + std::vector<pile> 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..2acfba6 --- /dev/null +++ b/src/main/game/search-state/game_state.legal_moves.cpp @@ -0,0 +1,276 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#include "game_state.h" + +#include <boost/optional/optional.hpp> + +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; + + +//////////////////////////////// +// MAIN LEGAL MOVE GEN CYCLE /// +//////////////////////////////// + +// Note that the moves added last here, are tried first +vector<move> game_state::get_legal_moves(move parent_move) { + vector<move> moves; + + // Attempts stock tableau deal and redeal + if (rules.stock_size > 0) { + if (stock_can_deal_tableau()) + moves.emplace_back(get_stock_tableau_move()); + else if (stock_can_redeal()) + moves.emplace_back(move::mtype::redeal); + } + + // Cycles through all of the piles from which we want to remove cards + for (pile::ref rem_ref = 0; rem_ref < piles.size(); rem_ref++) { + if ((rules.hole && rem_ref == hole) || piles[rem_ref].empty()) + continue; + if (undoes_prev_move(rem_ref, parent_move)) + continue; + + if (rules.foundations && is_foundation(rem_ref)) { + if (!rules.foundations_removable) continue; + else if (dominance_blocks_foundation_move(rem_ref)) continue; + } + + if (rules.stock_size > 0 && rem_ref == stock) { + if (rules.stock_deal_t == sdt::WASTE) + add_stock_to_waste_move(moves); + continue; + } + + if (rules.tableau_pile_count > 0) + add_tableau_moves(moves, rem_ref); + if (rules.cells > 0) + add_cell_moves(moves, rem_ref); + if (rules.foundations) + add_foundation_moves(moves, rem_ref); + if (rules.hole && is_valid_hole_move(rem_ref)) + moves.emplace_back(move::mtype::regular, rem_ref, hole); + } + + if (rules.move_built_group) + add_built_group_moves(moves); + + if (rules.foundations_comp_piles) // I.E. Spider-type winning condition + add_foundation_complete_piles_moves(moves); + + return moves; +} + + +//////////////////////////////// +// REGULAR MOVE GEN FUNCTIONS // +//////////////////////////////// + +bool game_state::stock_can_deal_tableau() const { + return rules.stock_deal_t == sdt::TABLEAU_PILES + && !piles[stock].empty(); +} + +// This is a special kind of move which the solver handles differently. +// 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 move(move::mtype::stock_to_tableau, 0, 0, stock_moves); +} + +bool game_state::stock_can_redeal() const { + return rules.stock_redeal + && rules.stock_deal_t == sdt::WASTE + && piles[stock].empty() + && !piles[waste].empty(); +} + +bool game_state::undoes_prev_move(pile::ref rem_ref, move parent_move) const { + return rem_ref == parent_move.to + && parent_move.count == 1 + && parent_move.from != stock; +} + +bool game_state::is_foundation(pile::ref ref) const { + return ref >= foundations.front() && ref <= foundations.back(); +} + +void game_state::add_stock_to_waste_move(std::vector<move>& moves) const { + uint8_t cards_to_move = min(rules.stock_deal_count, piles[stock].size()); + moves.emplace_back(move::mtype::stock_to_waste, stock, waste, cards_to_move); +} + +void game_state::add_tableau_moves(std::vector<move>& moves, pile::ref rem_ref) const { + for (auto add_ref : tableau_piles) { + if (is_valid_tableau_move(rem_ref, add_ref)) { + moves.emplace_back(move::mtype::regular, rem_ref, add_ref); + } + } +} + +void game_state::add_cell_moves(std::vector<move>& moves, pile::ref rem_ref) const { + for (auto add_ref : cells) { + if (add_ref != rem_ref && piles[add_ref].empty()) { + moves.emplace_back(move::mtype::regular, rem_ref, add_ref); + } + } +} + +void game_state::add_foundation_moves(std::vector<move>& moves, pile::ref rem_ref) const { + for (auto add_ref : foundations) { + if (is_valid_foundations_move(rem_ref, add_ref)) { + moves.emplace_back(move::mtype::regular, rem_ref, add_ref); + } + } +} + +void game_state::add_foundation_complete_piles_moves(std::vector<move>& moves) const { + 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(move::mtype::built_group, tab_pr, found_pr, rules.max_rank); + break; + } + } + } + } +} + +bool game_state::is_valid_tableau_move(const pile::ref rem_ref, + const pile::ref add_ref) const { + if (rem_ref == add_ref || rules.build_pol == pol::NO_BUILD) + return false; + + 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; + default: + return true; + } + } else { + card rem_c = piles[rem_ref].top_card(); + card add_c = piles[add_ref].top_card(); + + return is_next_tableau_card(add_c, rem_c); + } +} + +bool game_state::is_next_tableau_card(card a, card b) const { + return is_next_legal_card(rules.build_pol, a, b); +} + +bool game_state::is_valid_foundations_move(const pile::ref rem_ref, + const pile::ref add_ref) const { + if (rem_ref == add_ref || rules.foundations_comp_piles) return false; + + card rem_c = piles[rem_ref].top_card(); + + // Checks 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 + if (piles[add_ref].empty()) + return rem_c.get_rank() == 1; + else + return rem_c.get_rank() == piles[add_ref].top_card().get_rank() + 1; +} + +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 MOVE GEN FUNCTIONS // +//////////////////////////////////// + +void game_state::add_built_group_moves(vector<move> &moves) const { + assert(rules.built_group_pol != pol::NO_BUILD); + + // Cycles through each pile to see if it contains a built group + 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. Cycles through each pile to see if it can be added + for (auto add_ref : tableau_piles) { + if (add_ref == rem_ref) continue; + + card bg_high = piles[rem_ref][built_group_height - 1]; + + 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); + } else { + if (is_next_built_group_card(piles[add_ref].top_card(), bg_high)) + moves.emplace_back(move::mtype::built_group, rem_ref, add_ref, built_group_height); + } + } + } +} + +// 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 { + pile::size_type i = 1; + while (is_next_built_group_card(piles[ref][i], piles[ref][i-1]) && i < piles[ref].size()) + i++; + return i; +} + +// Loops through each possible built group move to an empty pile and adds it to the list +void game_state::add_empty_built_group_moves(vector<move>& moves, pile::ref rem_ref, pile::ref add_ref, + card bg_high) const { + pile::size_type card_idx = 1; + do { + moves.emplace_back(move::mtype::built_group, rem_ref, add_ref, static_cast<pile::size_type>(card_idx + 1)); + } while (piles[rem_ref][card_idx++] != bg_high); +} + +bool game_state::is_next_built_group_card(card a, card b) const { + return is_next_legal_card(rules.built_group_pol, a, b); +} + +bool game_state::is_next_legal_card(pol p, card a, card b) const { + // Checks build pol violations + switch(p) { + case sol_rules::build_policy::SAME_SUIT: + if (b.get_suit() != a.get_suit()) return false; + break; + case sol_rules::build_policy::RED_BLACK: + if (b.get_colour() == a.get_colour()) return false; + break; + default:; + } + // Checks rank + return b.get_rank() + 1 == a.get_rank(); +} diff --git a/src/main/game/search-state/game_state.pile_order.cpp b/src/main/game/search-state/game_state.pile_order.cpp new file mode 100644 index 0000000..736cc89 --- /dev/null +++ b/src/main/game/search-state/game_state.pile_order.cpp @@ -0,0 +1,80 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#include "game_state.h" + +using std::list; +using std::find; +using std::rbegin; +using std::rend; + +// 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::ref>& 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 +} diff --git a/src/main/input-output/input/command_line_helper.cpp b/src/main/input-output/input/command_line_helper.cpp index 92fef21..4b0942a 100644 --- a/src/main/input-output/input/command_line_helper.cpp +++ b/src/main/input-output/input/command_line_helper.cpp @@ -38,8 +38,6 @@ command_line_helper::command_line_helper() "'solvability', 'benchmark' or list of deals to be solved.") ("classify", "outputs a simple 'solvable/not solvable' " "classification") - ("shortest-sols", "for each instance returns the shortest possible " - "solution. cannot be supplied alongside '--solvability'") ("solvability", "calculates the solvability " "percentage of the supplied solitaire game. Must supply " "either 'random', 'benchmark', 'solvability' or list of deals to be " @@ -108,8 +106,6 @@ bool command_line_helper::parse(int argc, const char* argv[]) { benchmark = (vm.count("benchmark") != 0); - shortest_sols = (vm.count("shortest-sols") != 0); - // Handle logic error scenarios return assess_errors(); } @@ -141,11 +137,6 @@ bool command_line_helper::assess_errors() { return false; } - if (shortest_sols && solvability) { - print_shortest_sols_error(); - return false; - } - if (!solitaire_type.empty()) { return assess_sol_type(); } else { @@ -188,11 +179,6 @@ void command_line_helper::print_too_many_opts_error() { print_help(); } -void command_line_helper::print_shortest_sols_error() { - LOG_ERROR ("Error: User cannot supply '--shortest-sols' and '--solvability'"); - print_help(); -} - const vector<string> command_line_helper::get_input_files() { return input_files; } @@ -209,10 +195,6 @@ int command_line_helper::get_random_deal() { return random_deal; } -bool command_line_helper::get_help() { - return help; -} - bool command_line_helper::get_classify() { return classify; } @@ -229,10 +211,6 @@ string command_line_helper::get_describe_game_rules() { return describe_game_rules; } -bool command_line_helper::get_short_sols() { - return shortest_sols; -} - bool command_line_helper::get_benchmark() { return benchmark; } diff --git a/src/main/input-output/input/command_line_helper.h b/src/main/input-output/input/command_line_helper.h index e436f13..911cd5a 100644 --- a/src/main/input-output/input/command_line_helper.h +++ b/src/main/input-output/input/command_line_helper.h @@ -16,10 +16,8 @@ public: const std::string get_solitaire_type(); const std::string get_rules_file(); int get_random_deal(); - bool get_help(); bool get_classify(); bool get_solvability(); - bool get_short_sols(); bool get_available_game_types(); bool get_benchmark(); std::string get_describe_game_rules(); @@ -31,7 +29,6 @@ private: void print_sol_type_rules_error(); void print_no_opts_error(); void print_too_many_opts_error(); - void print_shortest_sols_error(); boost::program_options::options_description cmdline_options; boost::program_options::options_description main_options; @@ -45,7 +42,6 @@ private: bool help; bool classify; bool solvability; - bool shortest_sols; bool available_game_types; bool benchmark; }; 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/input/sol_preset_types.cpp b/src/main/input-output/input/sol_preset_types.cpp index 07c824b..53141a8 100644 --- a/src/main/input-output/input/sol_preset_types.cpp +++ b/src/main/input-output/input/sol_preset_types.cpp @@ -312,7 +312,7 @@ map<string, string> sol_preset_types::mp = { "build policy": "same-suit", "move built group": true }, - "max rank": 5, + "max rank": 6, "foundations initial card": true } )" 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<game_state::pile_ref>& pile_rs, + const vector<pile::ref>& 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<game_state::pile_ref>& vp, + const vector<pile::ref>& vp, const game_state& gs) { - vector<game_state::pile_ref> top(vp); + vector<pile::ref> 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 <ostream> -#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<game_state::pile_ref>&, + const std::vector<pile::ref>&, const game_state&); static void print_top_of_piles(std::ostream&, - const std::vector<game_state::pile_ref>&, + const std::vector<pile::ref>&, 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/main.cpp b/src/main/main.cpp index 6d06f5d..d71db6c 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -19,10 +19,11 @@ using namespace boost; namespace po = boost::program_options; const optional<sol_rules> gen_rules(command_line_helper&); -void solve_random_game(int, const sol_rules&, bool, bool); -void solve_input_files(vector<string>, const sol_rules&, bool, bool); -void solve_game(const game_state&, bool, bool); +void solve_random_game(int, const sol_rules&, bool); +void solve_input_files(vector<string>, const sol_rules&, bool); +void solve_game(const game_state&, bool); +// Decides what to do given supplied command-line options int main(int argc, const char* argv[]) { // Parses the command-line options @@ -36,6 +37,7 @@ int main(int argc, const char* argv[]) { sol_preset_types::print_available_games(); return EXIT_SUCCESS; } + string game_rule_str = clh.get_describe_game_rules(); if (!game_rule_str.empty()) { sol_preset_types::describe_game_rules(game_rule_str); @@ -53,8 +55,7 @@ int main(int argc, const char* argv[]) { } // If a random deal seed has been supplied, solves it else if (clh.get_random_deal() != -1) { - solve_random_game(clh.get_random_deal(), *rules, clh.get_short_sols(), - clh.get_classify()); + solve_random_game(clh.get_random_deal(), *rules, clh.get_classify()); } // If the benchmark option has been supplied, generates it else if (clh.get_benchmark()) { @@ -67,13 +68,13 @@ int main(int argc, const char* argv[]) { // If there are no input files, solve a random deal based on the // supplied seed assert (!input_files.empty()); - solve_input_files(input_files, *rules, clh.get_short_sols(), - clh.get_classify()); + solve_input_files(input_files, *rules, clh.get_classify()); } return EXIT_SUCCESS; } +// Generates the game rules given the command line options const optional<sol_rules> gen_rules(command_line_helper& clh) { try { if (!clh.get_solitaire_type().empty()) { @@ -89,15 +90,13 @@ const optional<sol_rules> gen_rules(command_line_helper& clh) { } } -void solve_random_game(int seed, const sol_rules& rules, bool short_sol, - bool classify) { +void solve_random_game(int seed, const sol_rules& rules, bool classify) { LOG_INFO ("Attempting to solve with seed: " << seed << "..."); game_state gs(rules, seed); - solve_game(gs, short_sol, classify); + solve_game(gs, classify); } -void solve_input_files(const vector<string> input_files, const sol_rules& rules, - bool short_sol, bool classify) { +void solve_input_files(const vector<string> input_files, const sol_rules& rules, bool classify) { for (const string& input_file : input_files) { try { // Reads in the input file to a json doc @@ -107,7 +106,7 @@ void solve_input_files(const vector<string> input_files, const sol_rules& rules, game_state gs(rules, in_doc); LOG_INFO ("Attempting to solve " << input_file << "..."); - solve_game(gs, short_sol, classify); + solve_game(gs, classify); } catch (const runtime_error& error) { string errmsg = "Error parsing deal file: "; @@ -117,44 +116,18 @@ void solve_input_files(const vector<string> input_files, const sol_rules& rules, } } -void solve_game(const game_state& gs, bool short_sol, bool classify) { - solver s(gs); - solver* solv = &s; - if (short_sol) { - uint bound = 1; - solver::sol_state ss; - bool solution = false; - do { - LOG_INFO("Depth: " << bound); - solver s_(gs); - solv = &s_; - ss = s_.run_with_cutoff(none, bound++); - - if (ss == solver::sol_state::solved) { - if (!classify) solv->print_solution(); - cout << "Solved\n"; - solution = true; - } - } while (ss == solver::sol_state::cutoff); - - if (!solution) { - if (!classify) cout << "Deal:\n" << gs << "\n"; - cout << "No Possible Solution\n"; - } +void solve_game(const game_state& gs, bool classify) { + solver solv(gs); - } else { - bool solution = solv->run() == solver::sol_state::solved; + bool solution = solv.run() == solver::sol_state::solved; - if (solution) { - if (!classify) solv->print_solution(); - cout << "Solved\n"; - } else { - if (!classify) cout << "Deal:\n" << gs << "\n"; - cout << "No Possible Solution\n"; - } + if (solution) { + if (!classify) solv.print_solution(); + cout << "Solved\n"; + } else { + if (!classify) cout << "Deal:\n" << gs << "\n"; + cout << "No Possible Solution\n"; } - cout << "States Searched: " << solv->get_states_searched() << "\n"; - cout << "Backtracks: " << solv->get_backtrack_count() << "\n"; - cout << "Final Depth: " << solv->get_final_depth() << "\n"; + solv.print_solution_info(); } diff --git a/src/main/solver/solver.cpp b/src/main/solver/solver.cpp index 884b2e5..7d490be 100644 --- a/src/main/solver/solver.cpp +++ b/src/main/solver/solver.cpp @@ -9,19 +9,24 @@ #include <list> #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) , init_state(gs) , state(gs) , states_searched(1) + , unique_states_searched(1) , backtracks(0) + , dominance_moves(0) , depth(0) - , root(nullptr, game_state::move(255, 255, 255)) + , root(nullptr, move(move::mtype::null)) , current_node(&root) { } @@ -34,95 +39,87 @@ 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<atomic<bool> &> terminate_solver) { - return run_with_cutoff(terminate_solver, none); -} - -solver::sol_state solver::run_with_cutoff( - boost::optional<std::atomic<bool> &> terminate_solver, - boost::optional<uint> cutoff_depth) { - bool cutoff_triggered = false; +solver::sol_state solver::run(boost::optional<atomic<bool> &> terminate_solver) { bool states_exhausted = false; + while(!(state.is_solved() || states_exhausted)) { // If the terminate flag was supplied and has been set to true, return if (terminate_solver && *terminate_solver) { - return sol_state::cutoff; + return sol_state::timed_out; } #ifndef NDEBUG - if (current_node->move.is_dominance()) { + if (current_node->mv.type == move::mtype::dominance) { LOG_DEBUG("(dominance move)"); } LOG_DEBUG(state); #endif - if (cutoff_depth && depth >= *cutoff_depth) { - cutoff_triggered = true; - states_exhausted = revert_to_last_node_with_children(); + // If there is a dominance move available, adds it to the search tree + // and repeats. Doesn't cache the state. + boost::optional<move> 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); } else { - // If there is a dominance move available, adds it to the search tree - // and repeats. Doesn't cache the state. - optional<game_state::move> 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); - } else { - // Caches the current state - bool is_new_state = cache.insert(state); - if (is_new_state) { - // Gets the legal moves in the current state - vector<game_state::move> next_moves = get_next_moves(); - - // If there are none, reverts to the last node with children - if (next_moves.empty()) { - states_exhausted = revert_to_last_node_with_children(); - } else { - add_children(next_moves); - } - } - // If the state is not a new one, reverts to the last node with children - else { + // Caches the current state + bool is_new_state = cache.insert(state); + if (is_new_state) { + // Gets the legal moves in the current state + vector<move> next_moves = get_next_moves(); + + // If there are none, reverts to the last node with children + if (next_moves.empty()) { states_exhausted = revert_to_last_node_with_children(); + } else { + add_children(next_moves); } } + // If the state is not a new one, reverts to the last node with children + else { + unique_states_searched--; + states_exhausted = revert_to_last_node_with_children(); + } } // Sets the current node to one of its children 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->mv.type == move::mtype::dominance) dominance_moves++; } states_searched++; + unique_states_searched++; } if (state.is_solved()) { return sol_state::solved; } else { assert(states_exhausted); - return cutoff_triggered ? sol_state::cutoff : sol_state::unsolvable; + return sol_state::unsolvable; } } -void solver::add_children(std::vector<game_state::move>& moves) { +void solver::add_children(std::vector<move>& moves) { current_node->children.reserve(moves.size()); for (auto move : moves) { add_child(move); } } -vector<game_state::move> solver::get_next_moves() { - return state.get_legal_moves(current_node->move); +vector<move> 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 @@ -132,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++; @@ -140,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.type != move::mtype::dominance) { assert(cache.contains(state)); LOG_DEBUG("(undo move)"); } else { @@ -173,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(); } @@ -181,18 +178,18 @@ void solver::print_solution() const { cout << "\n"; } -int solver::get_states_searched() const { - return states_searched; -} - -int solver::get_final_depth() const { - return depth; +void solver::print_solution_info() const { + cout << "States Searched: " << states_searched << "\n" + << "Unique States Searched: " << unique_states_searched << "\n" + << "Backtracks: " << backtracks << "\n" + << "Dominance Moves: " << dominance_moves << "\n" + << "Final Search Depth: " << depth << "\n"; } const solver::node& solver::get_search_tree() const { return root; } -int solver::get_backtrack_count() { - return backtracks; +int solver::get_states_searched() const { + return states_searched; } diff --git a/src/main/solver/solver.h b/src/main/solver/solver.h index 5eda894..21b8d6e 100644 --- a/src/main/solver/solver.h +++ b/src/main/solver/solver.h @@ -14,13 +14,13 @@ class solver { public: - enum class sol_state {solved, unsolvable, cutoff}; + enum class sol_state {solved, unsolvable, timed_out}; 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<node> children; }; @@ -28,26 +28,26 @@ public: ~solver(); sol_state run(boost::optional<std::atomic<bool> &> = boost::none); - sol_state run_with_cutoff(boost::optional<std::atomic<bool> &>, - boost::optional<uint> = boost::none); void print_solution() const; + void print_solution_info() const; int get_states_searched() const; - int get_final_depth() const; const node& get_search_tree() const; - int get_backtrack_count(); private: bool revert_to_last_node_with_children(); - void add_children(std::vector<game_state::move>&); - void add_child(game_state::move); - std::vector<game_state::move> get_next_moves(); + void add_children(std::vector<move>&); + void add_child(move); + std::vector<move> get_next_moves(); const game_state init_state; game_state state; + int states_searched; + int unique_states_searched; int backtracks; - uint depth; + int dominance_moves; + int depth; node root; node* current_node; |
