From 5e3ced28cee6fd5c42be0d7ce05fff846e5ec057 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Thu, 28 Dec 2017 18:10:35 +0000 Subject: Make card representation efficient --- src/main/game/card.cpp | 103 +++++++++++++++++++------------------------------ src/main/game/card.h | 17 +++++--- 2 files changed, 50 insertions(+), 70 deletions(-) (limited to 'src') diff --git a/src/main/game/card.cpp b/src/main/game/card.cpp index f5e9acb..c0e98e8 100644 --- a/src/main/game/card.cpp +++ b/src/main/game/card.cpp @@ -14,90 +14,65 @@ using namespace boost; // A card can either be created using two int values (rank & suit), or // using a string (e.g. "AS") -card::card(int r, int s) : rank(r), suit(s) {} - -card::card(const char* c) : rank(-1), suit(-1) { - bool letter = false; - switch(tolower(c[0])) { - case 'a': rank = 1; - letter = true; - break; - case 'j': rank = 11; - letter = true; - break; - case 'q': rank = 12; - letter = true; - break; - case 'k': rank = 13; - letter = true; - break; - default: rank = stoi(c); - } - - char s; - if (rank >= 10 && !letter) { - s = c[2]; - } else { - s = c[1]; - } - - s = static_cast(tolower(s)); - - if (s == 'c') { - suit = 0; - } else if (s == 'd') { - suit = 1; - } else if (s == 'h') { - suit = 2; - } else if (s == 's') { - suit = 3; +card::card(suit_t s, rank_t r) : suit(s), rank(r) {} + +card::card(const char* c) : suit(suit_from_str(c)), rank(rank_from_str(c)) {} + +suit_t card::suit_from_str(const char* c) { + switch(tolower(c[strlen(c) - 1])) { + case 'c': return suit_t::Clubs; + case 'd': return suit_t::Diamonds; + case 'h': return suit_t::Hearts; + case 's': return suit_t::Spades; + default: assert(false); + return suit_t::Clubs; } } -bool operator==(const card& l, const card& r) { - return l.get_rank() == r.get_rank() && l.get_suit() == r.get_suit(); +rank_t card::rank_from_str(const char* c) { + switch(tolower(c[0])) { + case 'a': return 1; + case 'j': return 11; + case 'q': return 12; + case 'k': return 13; + default: return static_cast(stoi(c)); + } } -int card::get_rank() const { +rank_t card::get_rank() const { return rank; } -char card::get_suit() const { - switch (suit) { - case 0: return 'C'; - case 1: return 'D'; - case 2: return 'H'; - case 3: return 'S'; - default: return 'X'; - } +suit_t card::get_suit() const { + return suit; } -int card::get_suit_val() const { - return suit; +bool operator==(const card& l, const card& r) { + return l.get_rank() == r.get_rank() && l.get_suit() == r.get_suit(); } std::ostream & operator<<(std::ostream & s, card const & c) { - std::string r; - if (c.get_rank() == 1) { - s << "A"; - } else if (c.get_rank() <= 10) { - s << c.get_rank(); - } else if (c.get_rank() == 11) { - s << "J"; - } else if (c.get_rank() == 12) { - s << "Q"; - } else if (c.get_rank() == 13) { - s << "K"; + switch(c.rank) { + case 1 : s << "A"; + case 11: s << "J"; + case 12: s << "Q"; + case 13: s << "K"; + default: s << c.rank; + } + switch(c.suit) { + case suit_t::Spades : s << "S"; + case suit_t::Hearts : s << "H"; + case suit_t::Clubs : s << "C"; + case suit_t::Diamonds: s << "D"; } - - s << c.get_suit(); return s; } size_t hash_value(card const& c) { boost::hash hasher; unsigned char raw_val = static_cast( - c.get_suit_val() * 13 + c.get_rank()); + static_cast>(c.get_suit()) + * 13 + c.get_rank()); return hasher(raw_val); } \ No newline at end of file diff --git a/src/main/game/card.h b/src/main/game/card.h index b518485..fdb0b12 100644 --- a/src/main/game/card.h +++ b/src/main/game/card.h @@ -10,18 +10,23 @@ class card { public: + enum class suit_t : uint8_t {Clubs, Diamonds, Hearts, Spades}; + typedef uint8_t rank_t; + // A card can either be created using two int values (rank & suit), or // using a string (e.g. "AS") - card(int, int); + card(suit_t, rank_t); card(const char*); - int get_rank() const; - char get_suit() const; - int get_suit_val() const; + suit_t get_suit() const; + rank_t get_rank() const; private: - int rank; - int suit; + static suit_t suit_from_str(const char* c); + static rank_t rank_from_str(const char* c); + + suit_t suit : 4; + rank_t rank : 4; }; std::ostream & operator<<(std::ostream &, card const &); -- cgit v1.2.1 From 8e03459171278f31f6aa7b7f227c5760c3f4788f Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Fri, 29 Dec 2017 17:21:50 +0000 Subject: Make rules representation efficient --- src/main/game/sol_rules.cpp | 30 ++++++++++++++++++------------ src/main/game/sol_rules.h | 24 ++++++++++++++---------- 2 files changed, 32 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/main/game/sol_rules.cpp b/src/main/game/sol_rules.cpp index 91b00c1..353c8db 100644 --- a/src/main/game/sol_rules.cpp +++ b/src/main/game/sol_rules.cpp @@ -23,15 +23,21 @@ using namespace rapidjson; typedef sol_rules::build_policy pol; bool sol_rules::is_suit(pol bp) { - return suit_val(bp) != -1; + switch (bp) { + case pol::CLUBS : + case pol::DIAMONDS : + case pol::HEARTS : + case pol::SPADES : return true; + default : return false; + } } -int sol_rules::suit_val(pol bp) { +card::suit_t sol_rules::suit_val(pol bp) { switch (bp) { - case pol::CLUBS: return 0; - case pol::DIAMONDS: return 1; - case pol::HEARTS: return 2; - case pol::SPADES: return 3; - default: return -1; + case pol::CLUBS : return card::suit_t::Clubs; + case pol::DIAMONDS : return card::suit_t::Diamonds; + case pol::HEARTS : return card::suit_t::Hearts; + case pol::SPADES : return card::suit_t::Spades; + default: assert(false); return card::suit_t::Spades; } } @@ -80,7 +86,7 @@ void sol_rules::modify_sol_rules(sol_rules& sr, Document& d) { if (d["tableau piles"].HasMember("count")) { if (d["tableau piles"]["count"].IsInt()) { - sr.tableau_pile_count = d["tableau piles"]["count"].GetInt(); + sr.tableau_pile_count = static_cast(d["tableau piles"]["count"].GetInt()); } else { util::json_parse_err("[tableau piles][count] must be an integer"); } @@ -127,7 +133,7 @@ void sol_rules::modify_sol_rules(sol_rules& sr, Document& d) { if (d.HasMember("max rank")) { if (d["max rank"].IsInt()) { - sr.max_rank = d["max rank"].GetInt(); + sr.max_rank = static_cast(d["max rank"].GetInt()); } else { util::json_parse_err("[max rank] must be an integer"); } @@ -151,7 +157,7 @@ void sol_rules::modify_sol_rules(sol_rules& sr, Document& d) { if (d.HasMember("cells")) { if (d["cells"].IsInt()) { - sr.cells = d["cells"].GetInt(); + sr.cells = static_cast(d["cells"].GetInt()); } else { util::json_parse_err("[cells] must be an integer"); } @@ -159,7 +165,7 @@ void sol_rules::modify_sol_rules(sol_rules& sr, Document& d) { if (d.HasMember("reserve size")) { if (d["reserve size"].IsInt()) { - sr.reserve_size = d["reserve size"].GetInt(); + sr.reserve_size = static_cast(d["reserve size"].GetInt()); } else { util::json_parse_err("[reserve size] must be an integer"); } @@ -167,7 +173,7 @@ void sol_rules::modify_sol_rules(sol_rules& sr, Document& d) { if (d.HasMember("stock size")) { if (d["stock size"].IsInt()) { - sr.stock_size = d["stock size"].GetInt(); + sr.stock_size = static_cast(d["stock size"].GetInt()); } else { util::json_parse_err("[stock size] must be an integer"); } diff --git a/src/main/game/sol_rules.h b/src/main/game/sol_rules.h index 17dd74a..a2f8fe9 100644 --- a/src/main/game/sol_rules.h +++ b/src/main/game/sol_rules.h @@ -11,6 +11,8 @@ #include #include +#include "card.h" + class sol_rules { public: enum class valid_sol { @@ -28,7 +30,8 @@ public: DESCENDING, ASCENDING, BOTH, - SINGLE_CARD + SINGLE_CARD, + ANY }; enum class build_policy { CLUBS, @@ -37,24 +40,25 @@ public: SPADES, ANY_SUIT, SAME_SUIT, - RED_BLACK + RED_BLACK, + N_A }; + static bool is_suit(build_policy); + static card::suit_t suit_val(build_policy); + static const sol_rules from_preset(const std::string); static const sol_rules from_file(const std::string); - static bool is_suit(build_policy); - static int suit_val(build_policy); - - unsigned int tableau_pile_count; + uint8_t tableau_pile_count; build_order build_ord; build_policy build_pol; - unsigned int max_rank; + card::rank_t max_rank; bool hole; bool foundations; - unsigned int cells; - unsigned int reserve_size; - unsigned int stock_size; + uint8_t cells; + uint8_t reserve_size; + uint8_t stock_size; private: static sol_rules get_default(); -- cgit v1.2.1 From 83d041e8676ed9f20711211004f87e43193a3e35 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Fri, 29 Dec 2017 17:22:06 +0000 Subject: Make pile representation efficient --- src/main/game/pile.cpp | 59 +++++++++++++++++++++++++------------------------- src/main/game/pile.h | 28 ++++++++++++++++-------- 2 files changed, 49 insertions(+), 38 deletions(-) (limited to 'src') diff --git a/src/main/game/pile.cpp b/src/main/game/pile.cpp index 1ce7c01..28eb0a8 100644 --- a/src/main/game/pile.cpp +++ b/src/main/game/pile.cpp @@ -19,42 +19,44 @@ typedef sol_rules::build_policy pol; // Static // //////////// -pile pile::foundation_factory(pol p) { - return pile(true, ord::ASCENDING, p, false); +pile pile::tableau_factory(ord o, pol p) { + return pile(o, p); } pile pile::cell_factory() { - return pile(true, ord::SINGLE_CARD, pol::ANY_SUIT, false); -} -pile pile::tableau_factory(ord o) { - return pile(true, o, pol::ANY_SUIT, false); + return pile(ord::SINGLE_CARD, pol::N_A); } pile pile::reserve_factory() { - return pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); + return pile(ord::NO_BUILD, pol::N_A); } pile pile::stock_factory() { - return pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); + return pile(ord::NO_BUILD, pol::N_A); } pile pile::waste_factory() { - return pile(true, ord::NO_BUILD, pol::ANY_SUIT, false); + return pile(ord::NO_BUILD, pol::N_A); +} +pile pile::foundation_factory(pol p) { + return pile(ord::ASCENDING, p); } pile pile::hole_factory(int max_rank) { - return pile(false, ord::BOTH, pol::ANY_SUIT, true, max_rank); + return pile(ord::BOTH, pol::ANY_SUIT, false, true, max_rank); } //////////////// // Non-static // //////////////// -pile::pile(bool r, ord bo, pol bp, bool l, int mr) : - remove(r), - build_order(bo), - build_policy(bp), - build_order_loops(l), - max_rank(mr) {} - -bool pile::can_place(const card& c) const { +pile::pile(ord bo, pol bp, bool r, bool l, int mr) : + build_order(bo), + build_policy(bp), + removable(r), + build_order_loops(l), + max_rank(mr) { +} - if (build_order == ord::NO_BUILD) { +bool pile::can_place(const card c) const { + if (build_order == ord::ANY) { + return true; + } else if (build_order == ord::NO_BUILD) { return false; } else if (build_order == ord::SINGLE_CARD) { return empty(); @@ -62,7 +64,7 @@ bool pile::can_place(const card& c) const { if (empty()) { if (sol_rules::is_suit(build_policy)) { - return c.get_suit_val() == sol_rules::suit_val(build_policy) + return c.get_suit() == sol_rules::suit_val(build_policy) && c.get_rank() == 1; } else { return true; @@ -72,12 +74,11 @@ bool pile::can_place(const card& c) const { card top_c = top_card(); // Check suit - if (build_policy == pol::SAME_SUIT && c.get_suit_val() - != top_c.get_suit_val()) { + if (build_policy == pol::SAME_SUIT && c.get_suit() != top_c.get_suit()) { return false; } - if (sol_rules::is_suit(build_policy) && c.get_suit_val() - != sol_rules::suit_val(build_policy)) { + if (sol_rules::is_suit(build_policy) && c.get_suit() + != sol_rules::suit_val(build_policy)) { return false; } @@ -106,15 +107,15 @@ card pile::top_card() const { } bool pile::can_remove() const { - return remove; + return removable; } bool pile::empty() const { return pile_vec.empty(); } -unsigned long pile::size() const { - return pile_vec.size(); +uint8_t pile::size() const { + return static_cast(pile_vec.size()); } ord pile::get_build_order() const { @@ -129,8 +130,8 @@ card pile::operator[] (vector::size_type i) const { } -void pile::place(const card& c) { - pile_vec.push_back(c); +void pile::place(const card c) { + pile_vec.emplace_back(c); } card pile::take() { diff --git a/src/main/game/pile.h b/src/main/game/pile.h index 1922c73..853caf3 100644 --- a/src/main/game/pile.h +++ b/src/main/game/pile.h @@ -12,28 +12,36 @@ class pile { public: - static pile foundation_factory(sol_rules::build_policy); + // Factory methods + static pile tableau_factory(sol_rules::build_order, sol_rules::build_policy); static pile cell_factory(); - static pile tableau_factory(sol_rules::build_order); static pile reserve_factory(); static pile stock_factory(); static pile waste_factory(); - static pile hole_factory(int max_rank = 13); + static pile foundation_factory(sol_rules::build_policy); + static pile hole_factory(int); - pile(bool, sol_rules::build_order, sol_rules::build_policy, bool, + // Constructors + pile(sol_rules::build_order bo = sol_rules::build_order::DESCENDING, + sol_rules::build_policy bp = sol_rules::build_policy::ANY_SUIT, + bool removable = true, + bool loops = false, int max_rank = 13); - bool can_place(const card&) const; + // Inspect + bool can_place(const card) const; bool can_remove() const; card top_card() const; bool empty() const; - unsigned long size() const; + uint8_t size() const; sol_rules::build_order get_build_order() const; - void place(const card&); + // Modify + void place(const card); card take(); void clear(); + // Index like array card& operator[] (std::vector::size_type); card operator[] (std::vector::size_type) const; @@ -43,12 +51,14 @@ public: private: bool one_lt(int, int) const; - const bool remove; + // const pile properties const sol_rules::build_order build_order; const sol_rules::build_policy build_policy; - const bool build_order_loops; + const bool removable; const int max_rank; + const bool build_order_loops; + // Underlying vector std::vector pile_vec; }; -- cgit v1.2.1 From 32a3c20c01266fc71a880a67d9693e5e1ded66c6 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Fri, 29 Dec 2017 21:49:21 +0000 Subject: Make game state representation efficient --- src/main/game/game_state.cpp | 260 ++++++++++++++++++++++--------------------- src/main/game/game_state.h | 45 +++++--- 2 files changed, 161 insertions(+), 144 deletions(-) (limited to 'src') diff --git a/src/main/game/game_state.cpp b/src/main/game/game_state.cpp index b851f2a..caabb18 100644 --- a/src/main/game/game_state.cpp +++ b/src/main/game/game_state.cpp @@ -21,88 +21,118 @@ using namespace boost; typedef sol_rules::build_order ord; typedef sol_rules::build_policy pol; -// Construct an initial game state from a JSON doc +// 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), - reserve(pile::reserve_factory()), - stock(pile::stock_factory()), - waste(pile::waste_factory()), - hole(pile::hole_factory(s_rules.max_rank)) { + rules(s_rules) { // Creates the tableau piles - for (unsigned int i = 0; i < rules.tableau_pile_count; i++) { - tableau_piles.push_back(pile::tableau_factory(rules.build_ord)); + for (uint8_t i = 0; i < rules.tableau_pile_count; i++) { + piles.push_back(pile::tableau_factory(rules.build_ord, rules.build_pol)); + tableau_piles.push_back(static_cast(piles.size() - 1)); } - // If there are foundation piles, create the relevant pile vectors + // If there are foundation piles, creates the relevant pile vectors if (rules.foundations) { - for (int i = 0; i < 4; i++) { - foundations.push_back(pile::foundation_factory(pol(i))); + for (uint8_t i = 0; i < 4; i++) { + piles.push_back(pile::foundation_factory(pol(i))); + foundations.push_back(static_cast(piles.size() - 1)); } } - // If there are cell piles, create the relevant cell vectors + // If there are cell piles, creates the relevant cell vectors if (rules.cells > 0) { - for (unsigned int i = 0; i < rules.cells; i++) { - cells.push_back(pile::cell_factory()); + for (uint8_t i = 0; i < rules.cells; i++) { + piles.push_back(pile::cell_factory()); + cells.push_back(static_cast(piles.size() - 1)); + } + } + + // If there is a reserve, creates a reserve pile + if (rules.reserve_size > 0) { + piles.push_back(pile::reserve_factory()); + reserve = static_cast(piles.size() - 1); + } + + // If there is a stock & waste, creates piles + if (rules.stock_size > 0) { + piles.push_back(pile::stock_factory()); + stock = static_cast(piles.size() - 1); + piles.push_back(pile::waste_factory()); + waste = static_cast(piles.size() - 1); + } + + if (rules.hole) { + piles.push_back(pile::hole_factory(s_rules.max_rank)); + hole = static_cast(piles.size() - 1); + } + + for (pile_ref pr = 0; pr < piles.size(); pr++) { + if (rules.stock_size > 0 && pr == waste) continue; + + if (piles[pr].can_remove()) { + removable_piles.emplace_back(pr); + } + if (piles[pr].get_build_order() != ord::NO_BUILD) { + addable_piles.emplace_back(pr); } } } -// Construct an initial game state from a JSON doc +// 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); } -// Construct an initial game state from a seed +// 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 = shuffled_deck(seed, rules.max_rank); + vector deck = gen_shuffled_deck(seed, rules.max_rank); - // If there is a hole, move the ace of spades to it + // If there is a hole, moves the ace of spades to it if (rules.hole) { deck.erase(find(begin(deck), end(deck), card("AS"))); - hole.place("AS"); + piles[hole].place(card("AS")); } - // If there is a stock, deal to it and set up a waste pile too + // 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++) { - stock.place(deck.back()); + piles[stock].place(deck.back()); deck.pop_back(); } } - // If there is a reserve, deal to it + // If there is a reserve, deals to it if (rules.reserve_size > 0) { for (unsigned int i = 0; i < rules.reserve_size; i++) { - reserve.place(deck.back()); + piles[reserve].place(deck.back()); deck.pop_back(); } } - // Deal to the tableau piles (row-by-row) - unsigned int t = 0; - while (!deck.empty()) { + // Deals to the tableau piles (row-by-row) + for (int t = 0; !deck.empty(); t++) { card c = deck.back(); deck.pop_back(); // Add the randomly generated card to the tableau piles - tableau_piles[t++ % rules.tableau_pile_count].place(c); + pile_ref tableau_pile = tableau_piles[t % tableau_piles.size()]; + piles[tableau_pile].place(c); } } -// Generate a randomly ordered vector of cards -vector game_state::shuffled_deck(int seed, int max_rank = 13) { +// Generates a randomly ordered vector of cards +vector game_state::gen_shuffled_deck(int seed, int max_rank = 13) { vector values; vector v_ptrs; for (int i = 0; i < max_rank * 4; i++) { - values.push_back(i); + values.emplace_back(i); } for (int i = 0; i < max_rank * 4; i++) { - v_ptrs.push_back(&values[i]); + v_ptrs.emplace_back(&values[i]); } // Randomly shuffle the pointers @@ -111,100 +141,74 @@ vector game_state::shuffled_deck(int seed, int max_rank = 13) { vector deck; for (int *i : v_ptrs) { - int r = ((*i) % max_rank) + 1; - int s = (*i) / max_rank; + auto r = static_cast(((*i) % max_rank) + 1); + card::suit_t s; + switch ((*i) / max_rank) { + case 0 : s = card::suit_t::Clubs; + break; + case 1 : s = card::suit_t::Diamonds; + break; + case 2 : s = card::suit_t::Hearts; + break; + case 3 : s = card::suit_t::Spades; + break; + default : assert(false); + s = card::suit_t::Clubs; + break; + } - deck.emplace_back(card(r, s)); + deck.emplace_back(card(s, r)); } return deck; } -const vector game_state::get_next_legal_states() const { - // Generates vectors of references to all the piles from which - // cards can be removed, and to which they can be added - vector can_remove; - vector can_add; - - // A mutable version of the current state, used to create the next legal - // states - game_state mut_state = *this; +void game_state::make_move(const move m) { + piles[m.second].place(piles[m.first].take()); +} - for (pile* p : mut_state.get_regular_pile_refs()) { - if (p->can_remove()) { - can_remove.push_back(p); - } - if (p->get_build_order() != ord::NO_BUILD) { - can_add.push_back(p); - } - } +void game_state::undo_move(const move m) { + piles[m.first].place(piles[m.second].take()); +} +vector game_state::get_legal_moves() const { // The next legal states - vector next; - - // Moving from and to the 'can remove' and 'can add' piles - for (pile* rem_pile : can_remove) { - if (rem_pile->empty()) continue; + vector moves; - for (pile* add_pile : can_add) { - if (&add_pile != &rem_pile - && add_pile->can_place(rem_pile->top_card())) { + // Dealing from the stock to the waste + if (rules.stock_size > 0 && !piles[stock].empty()) { + moves.emplace_back(stock, waste); + } - game_state new_gs = move(mut_state, rem_pile, add_pile); - next.push_back(new_gs); + // Moving from and to the 'can remove' and 'can add' piles + // Note traversal order. Solver evaluates backwards, so we reverse traversal + // order of removable piles, but not addable. This moves from tableau piles + // to foundations first if possible + for (auto rem_it = removable_piles.rbegin(); rem_it != removable_piles.rend(); ++rem_it) { + if (piles[*rem_it].empty()) continue; + + for (const pile_ref add_pile : addable_piles) { + if (add_pile != *rem_it && + piles[add_pile].can_place(piles[*rem_it].top_card())) { + moves.emplace_back(*rem_it, add_pile); } } } - // Dealing from the stock to the waste - if (!stock.empty()) { - game_state new_gs = move(mut_state, &mut_state.stock, &mut_state.waste); - next.push_back(new_gs); - } - - return next; + return moves; } -const game_state game_state::move(game_state& gs, pile* from, pile* to) const { - to->place(from->take()); - const game_state new_gs(gs); - from->place(to->take()); - return new_gs; -} - - bool game_state::is_solved() const { - for (auto p : foundations) { - if (p.size() != rules.max_rank) { + for (auto f : foundations) { + if (piles[f].size() != rules.max_rank) { return false; } } - return !rules.hole || hole.size() == rules.max_rank * 4; + return !rules.hole || piles[hole].size() == rules.max_rank * 4; } -// Not the stock, because cards from it can't be moved to the rest of the piles! -vector game_state::get_regular_pile_refs() { - vector piles; - auto to_ptr = [](pile& p){return &p;}; - - if (rules.foundations) { - transform(begin(foundations), end(foundations), back_inserter(piles), - to_ptr); - } - if (rules.cells) { - transform(begin(cells), end(cells), back_inserter(piles), to_ptr); - } - transform(begin(tableau_piles), end(tableau_piles), back_inserter(piles), to_ptr); - if (rules.reserve_size > 0) { - piles.push_back(&reserve); - } - if (rules.stock_size > 0) { - piles.push_back(&waste); - } - if (rules.hole) { - piles.push_back(&hole); - } +const vector& game_state::get_data() const { return piles; } @@ -238,34 +242,33 @@ ostream& game_state::print(ostream& stream) const { void game_state::print_header(ostream& stream, const char* header) const { stream << "--- " << header << " "; - int pad = 20 - strlen(header); - for (int i = 0; i < pad; i++) { + size_t pad = 20 - strlen(header); + for (size_t i = 0; i < pad; i++) { stream << '-'; } stream << "\n"; } -void game_state::print_piles(ostream& stream, - const vector& pile_vec) const { +void game_state::print_piles(ostream& stream, const vector& pile_rs) const { bool empty_row = false; vector::size_type row_idx = 0; // Loops through the rows in each pile, starting from the bottom, until // one is empty while (!empty_row) { - // Loops throught the current row to determine if it is empty + // Loops through the current row to determine if it is empty empty_row = true; - for (const pile& tableau_pile : pile_vec) { - if (tableau_pile.size() > row_idx) { + for (const pile_ref pile_r : pile_rs) { + if (piles[pile_r].size() > row_idx) { empty_row = false; break; } } if (!empty_row || row_idx == 0) { // Loops through the current (non-empty) row, and outputs the values - for (const pile& tableau_pile : pile_vec) { - if (tableau_pile.size() > row_idx) { - stream << tableau_pile[row_idx]; + for (const pile_ref pile_r : pile_rs) { + if (piles[pile_r].size() > row_idx) { + stream << piles[pile_r][row_idx]; } else if (row_idx == 0) { stream << "[]"; } @@ -278,24 +281,26 @@ void game_state::print_piles(ostream& stream, } } -void game_state::print_pile(ostream& stream, const pile &p) const { - print_piles(stream, {p}); +void game_state::print_pile(ostream& stream, const pile_ref pile_r) const { + print_piles(stream, {pile_r}); } -void game_state::print_top_of_piles(ostream& stream, const vector& vp) const { - vector top(vp); - for (pile& p : top) { - if (!p.empty()) { - card t = p.top_card(); - p.clear(); - p.place(t); +void game_state::print_top_of_piles(ostream& stream, const vector& vp) const { + vector top(vp); + + for (pile_ref p : top) { + if (piles[p].empty()) { + stream << "[]"; + } else { + stream << piles[p].top_card(); } + stream << "\t"; } - print_piles(stream, top); + stream << "\n"; } -void game_state::print_top_of_pile(ostream& stream, const pile& p) const { - print_top_of_piles(stream, {p}); +void game_state::print_top_of_pile(ostream& stream, const pile_ref pile_r) const { + print_top_of_piles(stream, {pile_r}); } bool operator==(const game_state& a, const game_state& b) { @@ -320,15 +325,16 @@ size_t hash_value(game_state const& gs) { if (gs.rules.tableau_pile_count > 0) { hash_combine(seed, gs.tableau_piles); } + if (gs.rules.reserve_size > 0) { - hash_combine(seed, gs.reserve); + hash_combine(seed, gs.piles[gs.reserve]); } if (gs.rules.stock_size > 0) { - hash_combine(seed, gs.stock); - hash_combine(seed, gs.waste); + hash_combine(seed, gs.piles[gs.stock]); + hash_combine(seed, gs.piles[gs.waste]); } if (gs.rules.hole) { - hash_combine(seed, gs.hole); + hash_combine(seed, gs.piles[gs.hole]); } return seed; diff --git a/src/main/game/game_state.h b/src/main/game/game_state.h index 4b96b72..8adc9d6 100644 --- a/src/main/game/game_state.h +++ b/src/main/game/game_state.h @@ -5,11 +5,14 @@ #ifndef SOLVITAIRE_GAME_STATE_H #define SOLVITAIRE_GAME_STATE_H +#define NULL_MOVE (game_state::move(255, 255)) + #include #include #include #include +#include #include "card.h" #include "sol_rules.h" @@ -20,13 +23,19 @@ class deal_parser; class game_state { friend class deal_parser; public: + typedef uint8_t pile_ref; + typedef std::pair move; + // Create a game state representation from a JSON doc game_state(const sol_rules&, const rapidjson::Document&); // Do the same from a 'rules' object game_state(const sol_rules&, int seed); - const std::vector get_next_legal_states() const; + void make_move(move); + void undo_move(move); + std::vector get_legal_moves() const; bool is_solved() const; + const std::vector& get_data() const; std::ostream& print(std::ostream&) const; @@ -36,27 +45,29 @@ public: friend std::size_t hash_value(std::vector const&); private: - explicit game_state(const sol_rules&); + static std::vector gen_shuffled_deck(int, int); - static std::vector shuffled_deck(int, int); - - const game_state move(game_state&, pile*, pile*) const; - std::vector get_regular_pile_refs(); + explicit game_state(const sol_rules&); void print_header(std::ostream&, const char*) const; - void print_piles(std::ostream&, const std::vector&) const; - void print_pile(std::ostream&, const pile&) const; - void print_top_of_piles(std::ostream&, const std::vector&) const; - void print_top_of_pile(std::ostream&, const pile&) const; + void print_piles(std::ostream&, const std::vector&) const; + void print_pile(std::ostream&, pile_ref) const; + void print_top_of_piles(std::ostream&, const std::vector&) const; + void print_top_of_pile(std::ostream&, pile_ref) const; sol_rules rules; - std::vector foundations; - std::vector cells; - std::vector tableau_piles; - pile reserve; - pile stock; - pile waste; - pile hole; + std::vector foundations; + std::vector cells; + std::vector tableau_piles; + pile_ref reserve; + pile_ref stock; + pile_ref waste; + pile_ref hole; + + std::vector addable_piles; + std::vector removable_piles; + + std::vector piles; }; -- cgit v1.2.1 From fce918cfbc3c55eca2f3fa5efb93db99f3673096 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 31 Dec 2017 11:47:13 +0000 Subject: Card efficient implementation fix --- src/main/game/card.cpp | 44 ++++++++++++++++++++++++++------------------ src/main/game/card.h | 6 ++++-- 2 files changed, 30 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/main/game/card.cpp b/src/main/game/card.cpp index c0e98e8..4ea9991 100644 --- a/src/main/game/card.cpp +++ b/src/main/game/card.cpp @@ -18,7 +18,7 @@ card::card(suit_t s, rank_t r) : suit(s), rank(r) {} card::card(const char* c) : suit(suit_from_str(c)), rank(rank_from_str(c)) {} -suit_t card::suit_from_str(const char* c) { +card::suit_t card::suit_from_str(const char* c) { switch(tolower(c[strlen(c) - 1])) { case 'c': return suit_t::Clubs; case 'd': return suit_t::Diamonds; @@ -29,7 +29,7 @@ suit_t card::suit_from_str(const char* c) { } } -rank_t card::rank_from_str(const char* c) { +card::rank_t card::rank_from_str(const char* c) { switch(tolower(c[0])) { case 'a': return 1; case 'j': return 11; @@ -39,12 +39,20 @@ rank_t card::rank_from_str(const char* c) { } } -rank_t card::get_rank() const { - return rank; +card::suit_t card::get_suit() const { + return suit; } -suit_t card::get_suit() const { - return suit; +card::colour_t card::get_colour() const { + switch (suit) { + case card::suit_t::Spades : + case card::suit_t::Clubs : return card::colour_t::Black; + default : return card::colour_t::Red; + } +} + +card::rank_t card::get_rank() const { + return rank; } bool operator==(const card& l, const card& r) { @@ -52,25 +60,25 @@ bool operator==(const card& l, const card& r) { } std::ostream & operator<<(std::ostream & s, card const & c) { - switch(c.rank) { - case 1 : s << "A"; - case 11: s << "J"; - case 12: s << "Q"; - case 13: s << "K"; - default: s << c.rank; + switch(c.get_rank()) { + case 1 : s << "A"; break; + case 11: s << "J"; break; + case 12: s << "Q"; break; + case 13: s << "K"; break; + default: s << int(c.get_rank()); } - switch(c.suit) { - case suit_t::Spades : s << "S"; - case suit_t::Hearts : s << "H"; - case suit_t::Clubs : s << "C"; - case suit_t::Diamonds: s << "D"; + switch(c.get_suit()) { + case card::suit_t::Spades : s << "S"; break; + case card::suit_t::Hearts : s << "H"; break; + case card::suit_t::Clubs : s << "C"; break; + case card::suit_t::Diamonds: s << "D"; break; } return s; } size_t hash_value(card const& c) { boost::hash hasher; - unsigned char raw_val = static_cast( + auto raw_val = static_cast( static_cast>(c.get_suit()) * 13 + c.get_rank()); diff --git a/src/main/game/card.h b/src/main/game/card.h index fdb0b12..cc5a993 100644 --- a/src/main/game/card.h +++ b/src/main/game/card.h @@ -10,7 +10,8 @@ class card { public: - enum class suit_t : uint8_t {Clubs, Diamonds, Hearts, Spades}; + enum class suit_t {Clubs, Diamonds, Hearts, Spades}; + enum class colour_t {Black, Red}; typedef uint8_t rank_t; // A card can either be created using two int values (rank & suit), or @@ -19,13 +20,14 @@ public: card(const char*); suit_t get_suit() const; + colour_t get_colour() const; rank_t get_rank() const; private: static suit_t suit_from_str(const char* c); static rank_t rank_from_str(const char* c); - suit_t suit : 4; + suit_t suit; rank_t rank : 4; }; -- cgit v1.2.1 From ed8dda2ff996a76a5a31ac9e760435071e347834 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 31 Dec 2017 11:47:27 +0000 Subject: Pile efficient implementation fix --- src/main/game/pile.cpp | 7 ++++++- src/main/game/pile.h | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/main/game/pile.cpp b/src/main/game/pile.cpp index 28eb0a8..641174e 100644 --- a/src/main/game/pile.cpp +++ b/src/main/game/pile.cpp @@ -73,14 +73,19 @@ bool pile::can_place(const card c) const { card top_c = top_card(); - // Check suit + // Checks violation of same suit policy if (build_policy == pol::SAME_SUIT && c.get_suit() != top_c.get_suit()) { return false; } + // Checks violation of specific suit policy if (sol_rules::is_suit(build_policy) && c.get_suit() != sol_rules::suit_val(build_policy)) { return false; } + // Checks violation of red-black suit policy + if (build_policy == pol::RED_BLACK && c.get_colour() == top_c.get_colour()) { + return false; + } int tc_r = top_c.get_rank(); int comp_r = c.get_rank(); diff --git a/src/main/game/pile.h b/src/main/game/pile.h index 853caf3..978e32e 100644 --- a/src/main/game/pile.h +++ b/src/main/game/pile.h @@ -55,8 +55,8 @@ private: const sol_rules::build_order build_order; const sol_rules::build_policy build_policy; const bool removable; - const int max_rank; const bool build_order_loops; + const int max_rank; // Underlying vector std::vector pile_vec; -- cgit v1.2.1 From a1bda7d722d4eac4c91affcb52abcbd5138105db Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 31 Dec 2017 11:48:02 +0000 Subject: Make solver representation efficient --- src/main/solver/solver.cpp | 115 ++++++++++++++++++++++++--------------------- src/main/solver/solver.h | 41 +++++----------- 2 files changed, 74 insertions(+), 82 deletions(-) (limited to 'src') diff --git a/src/main/solver/solver.cpp b/src/main/solver/solver.cpp index c487c29..23ed693 100644 --- a/src/main/solver/solver.cpp +++ b/src/main/solver/solver.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include "solver.h" #include "../input-output/log_helper.h" @@ -13,71 +14,77 @@ using namespace std; using namespace boost; -solver::solver(const game_state gs, const sol_rules& sr) - : root(NULL, gs), rules(sr), solution(root), states_searched(0) {} +solver::solver(const game_state& gs, const sol_rules& sr) + : initial_state(gs), rules(sr), states_searched(0) {} -solver::node::node(const node* parent, const game_state& gs) : - history(solver::node::gen_history(parent)), state(gs) {} - -const solver::node_history solver::node::gen_history(const node* parent) { - node_history hist; - if (parent != NULL) { - copy (begin(parent->history.get<0>()), - end(parent->history.get<0>()), - back_inserter(hist.get<0>())); - hist.get<0>().push_back(parent->state); - } - return hist; +solver::node::node(const game_state::move m, + vector &&uc) + : move(m), unsearched_children(std::move(uc)) { } -const optional solver::run() { - // Iteratively run a depth-first search. Nodes in the frontier are yet to - // be explored - vector frontier; - frontier.push_back(root); - - while (!frontier.empty()) { - // Pop the element at the top of the stack - const node current = frontier.back(); - frontier.pop_back(); +bool solver::run() { + game_state state = initial_state; - LOG_DEBUG (current.state); + frontier.emplace_back(NULL_MOVE, state.get_legal_moves()); + states_searched++; - // Create new nodes for each of the children - vector new_children = current.state.get_next_legal_states(); - states_searched++; - - for (auto it = new_children.rbegin(); it != new_children.rend(); it++) { - // If we have seen the state before, ignore it (loop detection)) - if (current.history.get<1>().find(*it) - != current.history.get<1>().end()) { - continue; + while (!frontier.empty()) { + node& current = frontier.back(); + LOG_DEBUG (state); + + // If we have a solution, returns true + if (state.is_solved()) return true; + + // If the current node has no unsearched children + if (current.unsearched_children.empty()) { + // Undoes the move that led to this state + // (unless it's the null first move) + if (frontier.size() > 1) { + state.undo_move(current.move); } - - const node n(¤t, *it); - if (n.state.is_solved()) { - return n; + // Returns to the previous state + frontier.pop_back(); + } else { + // Applies the first possible move in this state + state.make_move(current.unsearched_children.back()); + + // Insert the state into the global cache + bool is_new_state = global_cache.insert(state.get_data()).second; + if (is_new_state) { + // If the state is new, creates a new node in the frontier to + // represent the move just made, and those that are now possible + frontier.emplace_back(current.unsearched_children.back(), + state.get_legal_moves()); + states_searched++; } else { - frontier.push_back(n); + // If we've seen the state before, undo the move + state.undo_move(current.unsearched_children.back()); } + // Removes the move just made from the list of possible moves + current.unsearched_children.pop_back(); } } - return none; + return false; } -const solver::node solver::get_root() const { - return root; -} - -int solver::get_states_searched() const { - return states_searched; -} - -std::ostream& operator<< (std::ostream& stream, const solver::node& solution) { - for (auto state : solution.history.get<0>()) { - stream << state << "\n"; +void solver::print_solution() const { + std::flush(clog); + std::flush(cout); + game_state state = initial_state; + + cout << "Solution:\n"; + cout << state << "\n"; + // Ignores first move which is + bool first = true; + for (auto f_node : frontier) { + if (first) { + first = false; + continue; + } + // TODO print move as well + state.make_move(f_node.move); + cout << state << "\n"; } - stream << solution.state << "\n"; - return stream; -} \ No newline at end of file + cout << "States Searched: " << states_searched << "\n"; +} diff --git a/src/main/solver/solver.h b/src/main/solver/solver.h index bb5f8cf..1ef841d 100644 --- a/src/main/solver/solver.h +++ b/src/main/solver/solver.h @@ -7,48 +7,33 @@ #include #include - -#include -#include -#include -#include -#include +#include #include "../game/game_state.h" #include "../game/sol_rules.h" class solver { public: - typedef boost::multi_index::multi_index_container< - game_state, - boost::multi_index::indexed_by< - boost::multi_index::sequenced<>, - boost::multi_index::hashed_unique> - > - > node_history; + std::unordered_set< + std::vector, + boost::hash> + > global_cache; struct node { - node(const node*, const game_state&); - node_history history; - game_state state; - - static const node_history gen_history(const node* parent); + explicit node(const game_state::move, std::vector&&); + const game_state::move move; + std::vector unsearched_children; }; - solver(const game_state, const sol_rules&); - - const node get_root() const; - int get_states_searched() const; + solver(const game_state&, const sol_rules&); - const boost::optional run(); - - friend std::ostream& operator<< (std::ostream&, const solver::node&); + bool run(); + void print_solution() const; private: - - const node root; + const game_state initial_state; const sol_rules rules; - node solution; + std::vector frontier; int states_searched; }; -- cgit v1.2.1 From 6d1a5cc75ad8e047d265d625d862e61080a69bea Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 31 Dec 2017 11:48:21 +0000 Subject: Update main to work with efficient solver --- src/main/main.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/main/main.cpp b/src/main/main.cpp index 158ca07..e07e566 100644 --- a/src/main/main.cpp +++ b/src/main/main.cpp @@ -89,13 +89,12 @@ void solve_input_files(const vector input_files, const sol_rules& rules) } void solve_game(const game_state& gs, const sol_rules& rules) { - solver sol(gs, rules); + solver solv(gs, rules); + bool solution = solv.run(); - optional solution = sol.run(); if (solution) { - cout << "Solution:\n" << *solution << "States Searched: " - << sol.get_states_searched() << "\n"; + solv.print_solution(); } else { - cout << "Deal:\n" << sol.get_root() << "\nNo Possible Solution\n"; + cout << "Deal:\n" << gs << "\nNo Possible Solution\n"; } } -- cgit v1.2.1 From 052c785a04e10f418cab8eae4f14e34d01d25051 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 31 Dec 2017 11:49:20 +0000 Subject: Update deal parser to handle new game state impl --- src/main/input-output/deal_parser.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/main/input-output/deal_parser.cpp b/src/main/input-output/deal_parser.cpp index 2ff5a02..c876e91 100644 --- a/src/main/input-output/deal_parser.cpp +++ b/src/main/input-output/deal_parser.cpp @@ -44,7 +44,7 @@ void deal_parser::parse_tableau_piles(game_state &gs, const rapidjson::Document& for (auto& json_card : p.first->GetArray()) { assert(json_card.IsString()); - p.second->place(card(json_card.GetString())); + gs.piles[*p.second].place(card(json_card.GetString())); } } } @@ -54,7 +54,7 @@ void deal_parser::parse_hole(game_state &gs, const Document& doc) { const Value &json_hole = doc["hole"]; assert(json_hole.IsString()); - gs.hole.place(card(json_hole.GetString())); + gs.piles[gs.hole].place(card(json_hole.GetString())); } } @@ -76,7 +76,7 @@ void deal_parser::parse_cells(game_state &gs, const Document& doc) { auto json_card = p.first; assert(json_card->IsString()); - p.second->place(json_card->GetString()); + gs.piles[*p.second].place(json_card->GetString()); } } } -- cgit v1.2.1 From 743481e7040c9ab2ae11cacf75b4918c78e547a8 Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 31 Dec 2017 11:50:48 +0000 Subject: Update simple free cell tests to make work --- src/main/input-output/sol_preset_types.cpp | 4 ++-- src/test/resources/free_cell/ComplexSolvable.json | 9 +++++---- src/test/resources/free_cell/ComplexUnsolvable.json | 9 +++++---- src/test/resources/free_cell/SimpleSolvable.json | 7 ++++--- src/test/resources/free_cell/SimpleUnsolvable.json | 7 ++++--- 5 files changed, 20 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/main/input-output/sol_preset_types.cpp b/src/main/input-output/sol_preset_types.cpp index 3c77b05..169a8a5 100644 --- a/src/main/input-output/sol_preset_types.cpp +++ b/src/main/input-output/sol_preset_types.cpp @@ -109,10 +109,10 @@ std::map sol_preset_types::mp = { R"( { "tableau piles": { - "count": 3, + "count": 4, "build policy": "red-black" }, - "max rank": 3, + "max rank": 4, "cells": 1 } )" diff --git a/src/test/resources/free_cell/ComplexSolvable.json b/src/test/resources/free_cell/ComplexSolvable.json index 2c284d9..ca370ff 100644 --- a/src/test/resources/free_cell/ComplexSolvable.json +++ b/src/test/resources/free_cell/ComplexSolvable.json @@ -1,7 +1,8 @@ { "tableau piles": [ - ["AH","AC","2C","3C"], - ["AD","2H","2D","3D"], - ["3H","2S","AS","3S"] + ["AC","2C","4C","3C"], + ["AD","2D","4D","3D"], + ["AH","2H","3H","4H"], + ["AS","2S","3S","4S"] ] -} +} \ No newline at end of file diff --git a/src/test/resources/free_cell/ComplexUnsolvable.json b/src/test/resources/free_cell/ComplexUnsolvable.json index 279c319..48ac428 100644 --- a/src/test/resources/free_cell/ComplexUnsolvable.json +++ b/src/test/resources/free_cell/ComplexUnsolvable.json @@ -1,7 +1,8 @@ { "tableau piles": [ - ["AH","AC","3H","3C"], - ["AD","2H","2D","3D"], - ["2C","2S","AS","3S"] + ["2S","2C","4D","3C"], + ["2H","2D","4C","3D"], + ["AH","AD","3S","4H"], + ["AS","AC","3H","4S"] ] -} +} \ No newline at end of file diff --git a/src/test/resources/free_cell/SimpleSolvable.json b/src/test/resources/free_cell/SimpleSolvable.json index 2ae2f1a..1bebaf2 100644 --- a/src/test/resources/free_cell/SimpleSolvable.json +++ b/src/test/resources/free_cell/SimpleSolvable.json @@ -1,7 +1,8 @@ { "tableau piles": [ - ["3H","2H","AH","AC"], - ["3D","2D","2C","AD"], - ["3S","3C","2S","AS"] + ["4C","3C","2C","AC"], + ["4D","3D","2D","AD"], + ["4H","3H","2H","AH"], + ["4S","3S","2S","AS"] ] } diff --git a/src/test/resources/free_cell/SimpleUnsolvable.json b/src/test/resources/free_cell/SimpleUnsolvable.json index f69312d..8cdcc26 100644 --- a/src/test/resources/free_cell/SimpleUnsolvable.json +++ b/src/test/resources/free_cell/SimpleUnsolvable.json @@ -1,7 +1,8 @@ { "tableau piles": [ - ["AH","AC","3H","3C"], - ["AD","2C","2D","3D"], - ["AS","2S","2H","3S"] + ["AC","2C","3C","4C"], + ["AD","2D","3D","4D"], + ["AH","2H","3H","4H"], + ["AS","2S","3S","4S"] ] } -- cgit v1.2.1 From c6cf210f8d0fe6b68f8ac364a1dd854597fb136f Mon Sep 17 00:00:00 2001 From: thecharlesblake Date: Sun, 31 Dec 2017 11:51:09 +0000 Subject: Fix simple black hole test example bug --- src/test/resources/black_hole/ComplexUnsolvable.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/test/resources/black_hole/ComplexUnsolvable.json b/src/test/resources/black_hole/ComplexUnsolvable.json index 89eb08f..ed4ee99 100644 --- a/src/test/resources/black_hole/ComplexUnsolvable.json +++ b/src/test/resources/black_hole/ComplexUnsolvable.json @@ -1,9 +1,9 @@ { "tableau piles": [ - ["5","3","2","4","A"], - ["5","3","2","4","A"], - ["5","3","3","4","A"], - ["5","2","2","2"] + ["5C","3C","2C","4C","AC"], + ["5D","3D","2D","4D","AD"], + ["5H","3H","4S","4H","AH"], + ["5D","2D","2H","2S"] ], "hole": "AS" } -- cgit v1.2.1