aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorCharlie Blake2017-12-31 11:53:50 +0000
committerGitHub2017-12-31 11:53:50 +0000
commit22e8b69a830d3e61be83762b9f1e6ce97bd3ec1e (patch)
treefaa726d97fcde3ea236f46e0c2b2d77a68f4cd9f /src
parentMerge pull request #26 from thecharlesblake/deal-description-and-test (diff)
parentRemove need for default switch in compile flags (diff)
downloadmetasol-22e8b69a830d3e61be83762b9f1e6ce97bd3ec1e.tar.gz
metasol-22e8b69a830d3e61be83762b9f1e6ce97bd3ec1e.zip

Merge pull request #27 from thecharlesblake/efficient-implementation

Efficient implementation

Diffstat (limited to 'src')
-rw-r--r--src/main/game/card.cpp111
-rw-r--r--src/main/game/card.h19
-rw-r--r--src/main/game/game_state.cpp260
-rw-r--r--src/main/game/game_state.h45
-rw-r--r--src/main/game/pile.cpp66
-rw-r--r--src/main/game/pile.h26
-rw-r--r--src/main/game/sol_rules.cpp30
-rw-r--r--src/main/game/sol_rules.h24
-rw-r--r--src/main/input-output/deal_parser.cpp6
-rw-r--r--src/main/input-output/sol_preset_types.cpp4
-rw-r--r--src/main/main.cpp9
-rw-r--r--src/main/solver/solver.cpp115
-rw-r--r--src/main/solver/solver.h41
-rw-r--r--src/test/resources/black_hole/ComplexUnsolvable.json8
-rw-r--r--src/test/resources/free_cell/ComplexSolvable.json9
-rw-r--r--src/test/resources/free_cell/ComplexUnsolvable.json9
-rw-r--r--src/test/resources/free_cell/SimpleSolvable.json7
-rw-r--r--src/test/resources/free_cell/SimpleUnsolvable.json7
18 files changed, 412 insertions, 384 deletions
diff --git a/src/main/game/card.cpp b/src/main/game/card.cpp
index f5e9acb..4ea9991 100644
--- a/src/main/game/card.cpp
+++ b/src/main/game/card.cpp
@@ -14,90 +14,73 @@ 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<char>(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)) {}
+
+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;
+ 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();
+card::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<rank_t>(stoi(c));
+ }
}
-int card::get_rank() const {
- return rank;
+card::suit_t card::get_suit() const {
+ return suit;
}
-char card::get_suit() const {
+card::colour_t card::get_colour() const {
switch (suit) {
- case 0: return 'C';
- case 1: return 'D';
- case 2: return 'H';
- case 3: return 'S';
- default: return 'X';
+ case card::suit_t::Spades :
+ case card::suit_t::Clubs : return card::colour_t::Black;
+ default : return card::colour_t::Red;
}
}
-int card::get_suit_val() const {
- return suit;
+card::rank_t card::get_rank() const {
+ return rank;
+}
+
+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.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.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;
}
-
- s << c.get_suit();
return s;
}
size_t hash_value(card const& c) {
boost::hash<unsigned char> hasher;
- unsigned char raw_val = static_cast<unsigned char>(
- c.get_suit_val() * 13 + c.get_rank());
+ auto raw_val = static_cast<unsigned char>(
+ static_cast<std::underlying_type_t<card::suit_t>>(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..cc5a993 100644
--- a/src/main/game/card.h
+++ b/src/main/game/card.h
@@ -10,18 +10,25 @@
class card {
public:
+ 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
// 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;
+ colour_t get_colour() 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;
+ rank_t rank : 4;
};
std::ostream & operator<<(std::ostream &, card const &);
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<pile_ref>(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<pile_ref>(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<pile_ref>(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<pile_ref>(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<pile_ref>(piles.size() - 1);
+ piles.push_back(pile::waste_factory());
+ waste = static_cast<pile_ref>(piles.size() - 1);
+ }
+
+ if (rules.hole) {
+ piles.push_back(pile::hole_factory(s_rules.max_rank));
+ hole = static_cast<pile_ref>(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<card> deck = shuffled_deck(seed, rules.max_rank);
+ vector<card> 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<card> game_state::shuffled_deck(int seed, int max_rank = 13) {
+// Generates a randomly ordered vector of cards
+vector<card> game_state::gen_shuffled_deck(int seed, int max_rank = 13) {
vector<int> values;
vector<int*> 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<card> game_state::shuffled_deck(int seed, int max_rank = 13) {
vector<card> deck;
for (int *i : v_ptrs) {
- int r = ((*i) % max_rank) + 1;
- int s = (*i) / max_rank;
+ auto r = static_cast<card::rank_t>(((*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> 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<pile*> can_remove;
- vector<pile*> 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::move> game_state::get_legal_moves() const {
// The next legal states
- vector<game_state> next;
-
- // Moving from and to the 'can remove' and 'can add' piles
- for (pile* rem_pile : can_remove) {
- if (rem_pile->empty()) continue;
+ vector<move> 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<pile*> game_state::get_regular_pile_refs() {
- vector<pile*> 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<pile>& 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>& pile_vec) const {
+void game_state::print_piles(ostream& stream, const vector<pile_ref>& pile_rs) const {
bool empty_row = false;
vector<card>::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<pile>& vp) const {
- vector<pile> 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<pile_ref>& vp) const {
+ vector<pile_ref> 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 <vector>
#include <ostream>
#include <string>
#include <rapidjson/document.h>
+#include <boost/functional/hash.hpp>
#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<pile_ref, pile_ref> 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<game_state> get_next_legal_states() const;
+ void make_move(move);
+ void undo_move(move);
+ std::vector<move> get_legal_moves() const;
bool is_solved() const;
+ const std::vector<pile>& get_data() const;
std::ostream& print(std::ostream&) const;
@@ -36,27 +45,29 @@ public:
friend std::size_t hash_value(std::vector<pile> const&);
private:
- explicit game_state(const sol_rules&);
+ static std::vector<card> gen_shuffled_deck(int, int);
- static std::vector<card> shuffled_deck(int, int);
-
- const game_state move(game_state&, pile*, pile*) const;
- std::vector<pile*> 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<pile>&) const;
- void print_pile(std::ostream&, const pile&) const;
- void print_top_of_piles(std::ostream&, const std::vector<pile>&) const;
- void print_top_of_pile(std::ostream&, const pile&) const;
+ void print_piles(std::ostream&, const std::vector<pile_ref>&) const;
+ void print_pile(std::ostream&, pile_ref) const;
+ void print_top_of_piles(std::ostream&, const std::vector<pile_ref>&) const;
+ void print_top_of_pile(std::ostream&, pile_ref) const;
sol_rules rules;
- std::vector<pile> foundations;
- std::vector<pile> cells;
- std::vector<pile> tableau_piles;
- pile reserve;
- pile stock;
- pile waste;
- pile hole;
+ std::vector<pile_ref> foundations;
+ std::vector<pile_ref> cells;
+ std::vector<pile_ref> tableau_piles;
+ pile_ref reserve;
+ pile_ref stock;
+ pile_ref waste;
+ pile_ref hole;
+
+ std::vector<pile_ref> addable_piles;
+ std::vector<pile_ref> removable_piles;
+
+ std::vector<pile> piles;
};
diff --git a/src/main/game/pile.cpp b/src/main/game/pile.cpp
index 1ce7c01..641174e 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;
@@ -71,13 +73,17 @@ 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()) {
+ // 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;
}
- if (sol_rules::is_suit(build_policy) && c.get_suit_val()
- != sol_rules::suit_val(build_policy)) {
+ // Checks violation of red-black suit policy
+ if (build_policy == pol::RED_BLACK && c.get_colour() == top_c.get_colour()) {
return false;
}
@@ -106,15 +112,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<uint8_t>(pile_vec.size());
}
ord pile::get_build_order() const {
@@ -129,8 +135,8 @@ card pile::operator[] (vector<card>::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..978e32e 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<card>::size_type);
card operator[] (std::vector<card>::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 removable;
const bool build_order_loops;
const int max_rank;
+ // Underlying vector
std::vector<card> pile_vec;
};
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<uint8_t>(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<card::rank_t>(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<uint8_t>(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<uint8_t>(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<uint8_t>(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 <boost/optional.hpp>
#include <rapidjson/document.h>
+#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();
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());
}
}
}
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<string, string> 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/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<string> 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<solver::node> 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";
}
}
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 <ostream>
#include <iostream>
#include <algorithm>
+#include <utility>
#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<game_state::move> &&uc)
+ : move(m), unsearched_children(std::move(uc)) {
}
-const optional<solver::node> solver::run() {
- // Iteratively run a depth-first search. Nodes in the frontier are yet to
- // be explored
- vector<node> 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<game_state> 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(&current, *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 <string>
#include <vector>
-
-#include <boost/optional.hpp>
-#include <boost/multi_index/hashed_index.hpp>
-#include <boost/multi_index_container.hpp>
-#include <boost/multi_index/identity.hpp>
-#include <boost/multi_index/sequenced_index.hpp>
+#include <unordered_set>
#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<boost::multi_index::identity<game_state>>
- >
- > node_history;
+ std::unordered_set<
+ std::vector<pile>,
+ boost::hash<std::vector<pile>>
+ > 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<game_state::move>&&);
+ const game_state::move move;
+ std::vector<game_state::move> 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<node> 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<node> frontier;
int states_searched;
};
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"
}
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"]
]
}