diff options
Diffstat (limited to 'solvitaire/src')
115 files changed, 10310 insertions, 0 deletions
diff --git a/solvitaire/src/main/api.cpp b/solvitaire/src/main/api.cpp new file mode 100644 index 0000000..1cf187c --- /dev/null +++ b/solvitaire/src/main/api.cpp @@ -0,0 +1,24 @@ +#include <cstdint> +#include <vector> +#include <string> + +#include "game/search-state/game_state.h" +#include "solver/solver.h" + +#include "api.h" + +solver::result::type get_moves(std::vector<move>& moves, game_state& gs, + uint64_t cache_capacity, uint64_t timeout) { + moves.clear(); + + solver sol(gs, cache_capacity); + solver::result res = sol.run(std::chrono::milliseconds(timeout)); + if (res.sol_type == solver::result::type::SOLVED) { + std::vector<solver::node> nodes = sol.get_frontier(); + for (auto &it : nodes) { + moves.push_back(it.mv); + } + } + + return res.sol_type; +} diff --git a/solvitaire/src/main/api.h b/solvitaire/src/main/api.h new file mode 100644 index 0000000..09b083d --- /dev/null +++ b/solvitaire/src/main/api.h @@ -0,0 +1,117 @@ +#include <cstdint> +#include <vector> +#include <string> +#include <list> + +#include "game/card.h" +#include "game/move.h" +#include "game/sol_rules.h" + +#ifndef SOLVITAIRE_SOLVER_H +namespace solver { + namespace result { + enum class type { + TIMEOUT, SOLVED, UNSOLVABLE, MEM_LIMIT, TERMINATED + }; + } +} +#endif + +#ifndef SOLVITAIRE_GAME_STATE_H +class game_state { + friend class hasher; + friend class global_cache; + friend class cached_game_state; + friend class deal_parser; + friend class state_printer; + friend class test_helper; + friend class json_helper; +public: + enum class streamliner_options {NONE, AUTO_FOUNDATIONS, SUIT_SYMMETRY, BOTH}; + + /* Constructors */ + + // Creates a game state representation from a JSON doc + game_state(const sol_rules&, const rapidjson::Document&, streamliner_options); + // Does the same from a seed + game_state(const sol_rules&, int seed, streamliner_options); + // Does the same but with an initialiser list (useful for testing) + game_state(const sol_rules&, std::initializer_list<std::initializer_list<std::string>>); + // Does the same but with vectors + game_state(const sol_rules&, std::vector<std::vector<std::string>>); + // Does the same but with lots of vectors + game_state(const sol_rules&, std::vector<std::vector<card::suit_t>>, + std::vector<std::vector<card::rank_t>>, + std::vector<std::vector<bool>>); + + /* 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: + + /* Game rules */ + + const sol_rules rules; + streamliner_options stream_opts; + card::rank_t foundations_base; + + /* 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; + std::vector<pile::ref> sequences; + std::list<pile::ref> accordion; + 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 + +typedef std::vector<std::vector<std::string>> piles; +typedef std::vector<move> movelist; + +/** + * Populate a move list with a bunch of moves that lead to a solution. + * + * Clears the list, then, if a solution is found, populates it with the moves + * required to realise the solution. + * + * Returns true if a solution was found; false otherwise. + */ +solver::result::type get_moves(movelist& moves, game_state& gs, + uint64_t cache_capacity, uint64_t timeout); + diff --git a/solvitaire/src/main/evaluation/benchmark.cpp b/solvitaire/src/main/evaluation/benchmark.cpp new file mode 100644 index 0000000..f66573c --- /dev/null +++ b/solvitaire/src/main/evaluation/benchmark.cpp @@ -0,0 +1,63 @@ +// +// Created by thecharlesblake on 4/5/18. +// + +#include <climits> +#include <iostream> +#include <numeric> + +#include "benchmark.h" +#include "../game/search-state/game_state.h" +#include "../solver/solver.h" + +using namespace std; +typedef chrono::microseconds microsec; + +void benchmark::run(const sol_rules &rules, uint64_t cache_capacity, game_state::streamliner_options streamliners) { + cout << "Seed " + "| Median/Mean Solution Time(μs) " + "| Median/Mean States Searched " + "| Solvable/Unsolvable"; + + multiset<int> sol_times; + multiset<int> states_searched; + int total_time = 0; + int total_states = 0; + int total_solvable = 0; + int total_unsolvable = 0; + + for(int seed = 1; seed <= 1000; seed++) { + game_state gs(rules, seed, streamliners); + solver sol(gs, cache_capacity); + + auto start = chrono::steady_clock::now(); + solver::result result = sol.run(); + auto end = chrono::steady_clock::now(); + microsec elapsed_micros = + chrono::duration_cast<chrono::microseconds>(end - start); + + sol_times.insert(static_cast<int>(elapsed_micros.count())); + total_time += static_cast<int>(elapsed_micros.count()); + states_searched.insert(result.states_searched); + total_states += result.states_searched; + switch (result.sol_type) { + case solver::result::type::SOLVED: + total_solvable++; + break; + case solver::result::type::UNSOLVABLE: + total_unsolvable++; + break; + default: + assert(false); + break; + } + + cout << "\n" << seed + << " | " << *next(begin(sol_times), (sol_times.size())/2) + << "/" << total_time/sol_times.size() + << " | " << *next(begin(states_searched), (states_searched.size())/2) + << "/" << total_states/sol_times.size() + << " | " << total_solvable + << "/" << total_unsolvable; + } +} diff --git a/solvitaire/src/main/evaluation/benchmark.h b/solvitaire/src/main/evaluation/benchmark.h new file mode 100644 index 0000000..b7b9a1d --- /dev/null +++ b/solvitaire/src/main/evaluation/benchmark.h @@ -0,0 +1,19 @@ +// +// Created by thecharlesblake on 4/5/18. +// + +#ifndef SOLVITAIRE_BENCHMARK_H +#define SOLVITAIRE_BENCHMARK_H + +#include <chrono> + +#include "../game/sol_rules.h" +#include "../game/search-state/game_state.h" + +class benchmark { +public: + static void run(const sol_rules &rules, uint64_t, game_state::streamliner_options); +}; + + +#endif //SOLVITAIRE_BENCHMARK_H diff --git a/solvitaire/src/main/evaluation/binomial_ci.cpp b/solvitaire/src/main/evaluation/binomial_ci.cpp new file mode 100644 index 0000000..c381c05 --- /dev/null +++ b/solvitaire/src/main/evaluation/binomial_ci.cpp @@ -0,0 +1,45 @@ +// +// Created by thecharlesblake on 20/06/18. +// + +#include <cmath> +#include <algorithm> +#include "binomial_ci.h" + +using std::pow; +using std::min; +using std::max; +using std::pair; + +pair<double, double> binomial_ci::wilson(int s_, int f_) { + auto s = static_cast<double>(s_); + auto f = static_cast<double>(f_); + double z = 1.96; + double z2 = pow(z, 2); + double n = s + f; + double p = (s + (z2 / 2.0)) / (n + z2); + double half_ci = (z / (n + z2)) * sqrt(((s * f) / n) + (z2 / 4.0)); + return { p - half_ci + , p + half_ci }; +} + +pair<double, double> binomial_ci::wilson(int s, int f, int i) { + pair<double, double> a = wilson(s, f + i); + pair<double, double> b = wilson(s + i, f); + return {a.first, b.second}; +} + +pair<double, double> binomial_ci::agresti_coull(int s, int f) { + double z = 1.96; + double n_ = s + f + pow(z, 2); + double p = (s + pow(z, 2)/2)/n_; + double half_ci = z * sqrt((p - pow(p, 2))/n_); + return { max(0.0, p - half_ci) + , min(1.0, p + half_ci) }; +} + +pair<double, double> binomial_ci::agresti_coull(int s, int f, int i) { + pair<double, double> a = agresti_coull(s, f + i); + pair<double, double> b = agresti_coull(s + i, f); + return {a.first, b.second}; +} diff --git a/solvitaire/src/main/evaluation/binomial_ci.h b/solvitaire/src/main/evaluation/binomial_ci.h new file mode 100644 index 0000000..6e2dceb --- /dev/null +++ b/solvitaire/src/main/evaluation/binomial_ci.h @@ -0,0 +1,19 @@ +// +// Created by thecharlesblake on 20/06/18. +// + +#ifndef SOLVITAIRE_BINOMIAL_CI_H +#define SOLVITAIRE_BINOMIAL_CI_H + + +#include <utility> + +struct binomial_ci { + static std::pair<double, double> wilson(int, int); + static std::pair<double, double> wilson(int, int, int); + static std::pair<double, double> agresti_coull(int, int); + static std::pair<double, double> agresti_coull(int, int, int); +}; + + +#endif //SOLVITAIRE_BINOMIAL_CI_H diff --git a/solvitaire/src/main/evaluation/solvability_calc.cpp b/solvitaire/src/main/evaluation/solvability_calc.cpp new file mode 100644 index 0000000..14219ab --- /dev/null +++ b/solvitaire/src/main/evaluation/solvability_calc.cpp @@ -0,0 +1,186 @@ +// +// Created by thecharlesblake on 3/21/18. +// +#include <future> +#include <iomanip> +#include <iostream> +#include <omp.h> + +#include "solvability_calc.h" +#include "../solver/solver.h" +#include "binomial_ci.h" + +using namespace std; +using boost::optional; + +typedef command_line_helper::streamliner_opt cmd_sos; +typedef game_state::streamliner_options sos; +typedef std::chrono::milliseconds millisec; + +/////////////////// +// SETUP METHODS // +/////////////////// + +solvability_calc::solvability_calc(const sol_rules& r, uint64_t cache_capacity_) : + rules(r), cache_capacity(cache_capacity_) { +} + +////////////////////// +// PRINTING METHODS // +////////////////////// + +void solvability_calc::print_general_info(const seed_results& seed_res) { + pair<double, double> interval = binomial_ci::wilson( + seed_res.solvable, + seed_res.unsolvable, + (seed_res.timed_out + seed_res.mem_limit)); + + cout << interval.first * 100 + << ", " << interval.second * 100 + << ", " << seed_res.solvable + << ", " << seed_res.unsolvable + << ", " << seed_res.timed_out + << ", " << seed_res.mem_limit; +} + +void solvability_calc::print_seed_info(seed_result seed_res) { + auto& res = seed_res.second; + + solver::print_result_csv(res); +} + +void solvability_calc::print_seeds_in_prog(std::set<int>& seeds_in_progress) { + for(auto iter = begin(seeds_in_progress); iter != end(seeds_in_progress); ++iter) { + cout << ", " << *iter; + } + + cout << "\n"; + + std::flush(clog); + std::flush(cout); +} + + +///////////////////// +// SOLVING METHODS // +///////////////////// + +void solvability_calc::calculate_solvability_percentage(uint64_t timeout_, int seed_count_, uint cores, + cmd_sos stream_opt_, const vector<int>& resume) { + resume_seeds = vector<int>(begin(resume) + 3, end(resume)); + sort(begin(resume_seeds), end(resume_seeds)); + + current_seed = resume_seeds.back(); + resume_seeds.pop_back(); + + seed_res.solvable = resume[0]; + seed_res.unsolvable = resume[1]; + seed_res.timed_out = resume[2]; + + timeout = millisec(timeout_); + solver::print_header(timeout.count(), stream_opt_); + seed_count = seed_count_; + stream_opt = stream_opt_; + + vector<std::thread> threads(cores); + + for (uint c = 0; c < cores; c++) + threads[c] = std::thread(solver_thread, this, c); + + for (uint c = 0; c < cores; c++) + threads[c].join(); +} + +void solvability_calc::solver_thread(solvability_calc* sc, uint core) { + int my_seed = sc->resume_seeds.size() > core ? sc->resume_seeds[core] : sc->current_seed++; + + while (my_seed < sc->seed_count) { + sc->results_mutex.lock(); + sc->seeds_in_progress.insert(my_seed); + sc->results_mutex.unlock(); + + optional<seed_result> stream_res, no_stream_res, final_res; + + if (sc->stream_opt == cmd_sos::SMART) { + stream_res = solve_seed(my_seed, (sc->timeout/10), sc->rules, sc->cache_capacity, sos::BOTH); + + switch (stream_res->second.sol_type) { + case solver::result::type::UNSOLVABLE: + case solver::result::type::TIMEOUT: + no_stream_res = solve_seed(my_seed, sc->timeout, sc->rules, sc->cache_capacity, sos::NONE); + final_res = *no_stream_res; + break; + default: + final_res = *stream_res; + break; + } + } else { + no_stream_res = solve_seed(my_seed, sc->timeout, sc->rules, sc->cache_capacity, + command_line_helper::convert_streamliners(sc->stream_opt)); + final_res = *no_stream_res; + } + + sc->results_mutex.lock(); + + sc->seeds_in_progress.erase(my_seed); + sc->seed_res.add_result(final_res->second.sol_type); + + cout << my_seed; + //print_general_info(sc->seed_res); + if (sc->stream_opt == cmd_sos::SMART) { + print_seed_info(*stream_res); + if (no_stream_res) { + print_seed_info(*no_stream_res); + cout << ", " << no_stream_res->second.sol_type; + } else { + solver::print_null_seed_info(); + cout << ", " << stream_res->second.sol_type; + } + } else { + print_seed_info(*no_stream_res); + cout << ", " << no_stream_res->second.sol_type; + } + //print_seeds_in_prog(sc->seeds_in_progress); + cout << "\n"; + + sc->results_mutex.unlock(); + + my_seed = sc->current_seed++; + } +} + +solvability_calc::seed_result solvability_calc::solve_seed(int seed, millisec timeout, const sol_rules& rules, + uint64_t cache_capacity, + game_state::streamliner_options stream_opt) { + game_state gs(rules, seed, stream_opt); + solver sol(gs, cache_capacity); + + return seed_result(seed, sol.run(optional<std::chrono::milliseconds>(timeout))); +} + + +//////////////////////// +// SEED RESULTS CLASS // +//////////////////////// + +solvability_calc::seed_results::seed_results() : solvable(0), unsolvable(0), timed_out(0), mem_limit(0) { +} + +void solvability_calc::seed_results::add_result(solver::result::type t) { + switch (t) { + case solver::result::type::TIMEOUT: + timed_out++; + break; + case solver::result::type::SOLVED: + solvable++; + break; + case solver::result::type::UNSOLVABLE: + unsolvable++; + break; + case solver::result::type ::MEM_LIMIT: + mem_limit++; + break; + case solver::result::type ::TERMINATED: + break; + } +} diff --git a/solvitaire/src/main/evaluation/solvability_calc.h b/solvitaire/src/main/evaluation/solvability_calc.h new file mode 100644 index 0000000..25eb844 --- /dev/null +++ b/solvitaire/src/main/evaluation/solvability_calc.h @@ -0,0 +1,58 @@ +// +// Created by thecharlesblake on 3/21/18. +// + +#ifndef SOLVITAIRE_SOLVABILITY_H +#define SOLVITAIRE_SOLVABILITY_H + +#include <vector> +#include <set> +#include <chrono> +#include <mutex> + +#include "../game/sol_rules.h" +#include "../solver/solver.h" +#include "../input-output/input/command_line_helper.h" + +class solvability_calc { +public: + explicit solvability_calc(const sol_rules&, uint64_t); + + void calculate_solvability_percentage(uint64_t, int, uint, command_line_helper::streamliner_opt, const std::vector<int>&); + +private: + typedef std::pair<int, solver::result> seed_result; + + struct seed_results { + seed_results(); + void add_result(solver::result::type); + + std::atomic<int> solvable; + std::atomic<int> unsolvable; + std::atomic<int> timed_out; + std::atomic<int> mem_limit; + }; + + // Printing methods + static void print_general_info(const seed_results&); + static void print_seed_info(seed_result); + static void print_seeds_in_prog(std::set<int>&); + + // Solving methods + static void solver_thread(solvability_calc*, uint core); + static seed_result solve_seed(int, std::chrono::milliseconds, const sol_rules&, uint64_t, game_state::streamliner_options); + + const sol_rules& rules; + const uint64_t cache_capacity; + std::chrono::milliseconds timeout; + std::mutex results_mutex; + seed_results seed_res; + std::set<int> seeds_in_progress; + std::vector<int> resume_seeds; + std::atomic<int> current_seed; + int seed_count; + command_line_helper::streamliner_opt stream_opt; +}; + + +#endif //SOLVITAIRE_SOLVABILITY_H diff --git a/solvitaire/src/main/game/card.cpp b/solvitaire/src/main/game/card.cpp new file mode 100644 index 0000000..60aaa74 --- /dev/null +++ b/solvitaire/src/main/game/card.cpp @@ -0,0 +1,152 @@ +// +// Created by thecharlesblake on 10/11/17. +// + +#include <sstream> + +#include <boost/functional/hash.hpp> + +#include "card.h" + +using namespace std; +using namespace boost; + +const card::suit_t card::suit::Clubs = 0; +const card::suit_t card::suit::Hearts = 1; +const card::suit_t card::suit::Spades = 2; +const card::suit_t card::suit::Diamonds = 3; + +const card::colour_t card::colour::Black = 0; +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, bool fd) : card_rank(r), card_suit(s), face_down(fd) {} + +card::card(const char* c, bool face_down_possible) : + card_rank(rank_from_str(c)), card_suit(suit_from_str(c)), + face_down(face_down_from_str(c, face_down_possible)) {} + +card::card() : card(0, 0, false) {} + +card::suit_t card::suit_from_str(const char* c) { + switch(tolower(c[strlen(c) - 1])) { + case 'c': return suit::Clubs; + case 'h': return suit::Hearts; + case 's': return suit::Spades; + case 'd': return suit::Diamonds; + default: assert(false); + return suit::Clubs; + } +} + +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: + assert(stoi(c) >= 1 && stoi(c) <= 13); + return static_cast<rank_t>(stoi(c)); + } +} + +bool card::face_down_from_str(const char *c, bool possible) { + if (!possible) return false; + + switch(c[strlen(c) - 1]) { + case 'c': return true; + case 'h': return true; + case 's': return true; + case 'd': return true; + default: return false; + } +} + +card::suit_t card::get_suit() const { + return card_suit; +} + +card::colour_t card::get_colour() const { + switch (card_suit) { + case card::suit::Spades : + case card::suit::Clubs : return card::colour::Black; + default : return card::colour::Red; + } +} + +card::rank_t card::get_rank() const { + return card_rank; +} + +std::string card::to_string() const { + if (face_down) return "##"; + + string s; + switch(card_rank) { + case 1 : s += "A"; break; + case 11: s += "J"; break; + case 12: s += "Q"; break; + case 13: s += "K"; break; + default: s += std::to_string(card_rank); + } + switch(card_suit) { + case card::suit::Spades : s += "S"; break; + case card::suit::Hearts : s += "H"; break; + case card::suit::Clubs : s += "C"; break; + case card::suit::Diamonds: s += "D"; break; + } + return s; +} + +bool card::is_face_down() const { + return face_down; +} + +void card::turn_face_up() { + face_down = false; +} + +void card::turn_face_down() { + face_down = true; +} + +const card card::divider = card(); + +bool operator==(const card& l, const card& r) { + return l.get_rank() == r.get_rank() && l.get_suit() == r.get_suit(); +} + +bool operator!=(const card& l, const card& r) { + return !(l == r); +} + +bool operator<(const card& l, const card& r) { + if (l.get_rank() == r.get_rank()) + return l.get_suit() < r.get_suit(); + else + return l.get_rank() < r.get_rank(); +} + +bool operator>(const card& l, const card& r) { + if (l.get_rank() == r.get_rank()) + return l.get_suit() > r.get_suit(); + else + return l.get_rank() > r.get_rank(); +} + +bool operator<=(const card& l, const card& r) { + if (l.get_rank() == r.get_rank()) + return l.get_suit() <= r.get_suit(); + else + return l.get_rank() <= r.get_rank(); +} + +bool operator>=(const card& l, const card& r) { + if (l.get_rank() == r.get_rank()) + return l.get_suit() >= r.get_suit(); + else + return l.get_rank() >= r.get_rank(); +} diff --git a/solvitaire/src/main/game/card.h b/solvitaire/src/main/game/card.h new file mode 100644 index 0000000..7885d66 --- /dev/null +++ b/solvitaire/src/main/game/card.h @@ -0,0 +1,66 @@ +// +// Created by thecharlesblake on 10/11/17. +// + +#ifndef SOLITAIRE_PIP_CARD_H +#define SOLITAIRE_PIP_CARD_H + +#include <string> +#include <map> + +class card { +public: + // Types & typedefs + typedef uint8_t rank_t; + typedef uint8_t suit_t; + typedef uint8_t colour_t; + + struct suit { + static const suit_t Clubs; + static const suit_t Hearts; + static const suit_t Spades; + static const suit_t Diamonds; + }; + + struct colour { + static const colour_t Black; + static const colour_t Red; + }; + + const static card divider; + + // A card can either be created using two int values (rank & suit), or + // using a string (e.g. "AS") + card(suit_t, rank_t, bool face_down=false); + card(const char*, bool face_down_possible=false); + card(); + + suit_t get_suit() const; + colour_t get_colour() const; + rank_t get_rank() const; + + bool is_face_down() const; + void turn_face_up(); + void turn_face_down(); + + std::string to_string() const; + +private: + static suit_t suit_from_str(const char* c); + static rank_t rank_from_str(const char* c); + bool face_down_from_str(const char *c, bool possible); + + rank_t card_rank : 4; + suit_t card_suit : 2; + bool face_down : 1; +}; + +bool operator==(const card&, const card&); +bool operator!=(const card&, const card&); +bool operator<(const card&, const card&); +bool operator>(const card&, const card&); +bool operator<=(const card&, const card&); +bool operator>=(const card&, const card&); + + +#endif //SOLITAIRE_PIP_CARD_H diff --git a/solvitaire/src/main/game/global_cache.cpp b/solvitaire/src/main/game/global_cache.cpp new file mode 100644 index 0000000..079ed77 --- /dev/null +++ b/solvitaire/src/main/game/global_cache.cpp @@ -0,0 +1,276 @@ +// +// Created by thecharlesblake on 1/10/18. +// + +#include <algorithm> + +#include <boost/functional/hash.hpp> + +#include "global_cache.h" +#include "../input-output/output/log_helper.h" +#include "search-state/game_state.h" + +using namespace std; +using namespace boost; + +typedef sol_rules::build_policy pol; +typedef sol_rules::stock_deal_type sdt; +typedef game_state::streamliner_options sos; + +typedef boost::multi_index::multi_index_container< + cached_game_state, + boost::multi_index::indexed_by< + boost::multi_index::sequenced<>, + boost::multi_index::hashed_unique< + boost::multi_index::identity<cached_game_state>, + hasher + > + > +> item_list; + + +/////////////////////// +// CACHED GAME STATE // +/////////////////////// + +cached_game_state::cached_game_state(const game_state& gs) : live(true) { + data.reserve(52+18); // Enough for each card and up to 18 piles + + if (gs.rules.hole) { + add_card(gs.piles[gs.hole].top_card(), gs); + } + + for (pile::ref pr : gs.cells) { + add_pile(pr, gs); + } + if (gs.rules.cells > 0) { + add_card_divider(); + } + + if (gs.rules.stock_size > 0) { + add_pile(gs.stock, gs); + + if (gs.rules.stock_deal_t == sdt::WASTE) { + bool waste_deal_symmetry = gs.rules.stock_redeal + && gs.piles[gs.waste].size() % gs.rules.stock_deal_count == 0; + + if (waste_deal_symmetry) { + add_pile_in_reverse(gs.waste, gs); + add_card_divider(); + } else { + add_card_divider(); + add_pile_in_reverse(gs.waste, gs); + } + } + + add_card_divider(); + } + + for (pile::ref pr : gs.reserve) { + add_pile(pr, gs); + } + if (gs.rules.reserve_size > 0) { + add_card_divider(); + } + + for (pile::ref pr : gs.tableau_piles) { + add_pile(pr, gs); + add_card_divider(); + } + + for (pile::ref pr : gs.sequences) { + add_pile(pr, gs); + add_card_divider(); + } + + for (pile::ref pr : gs.accordion) { + add_card(gs.piles[pr].top_card(), gs); + } +} + + +void cached_game_state::add_pile(pile::ref pr, const game_state& gs) { + for (card c : gs.piles[pr].pile_vec) { + add_card(c, gs); + } +} + +void cached_game_state::add_pile_in_reverse(pile::ref pr, const game_state& gs) { + for (auto i = gs.piles[pr].pile_vec.size(); i-->0;) { + card c = gs.piles[pr].pile_vec[i]; + add_card(c, gs); + } +} + +void cached_game_state::add_card(card c, const game_state& gs) { + auto& target = data; + + // If the game is a 'hole-based' game, or suit-reduction is on, reduces + // the cached suit of the card where possible + + bool is_suit_symmetry = (gs.rules.foundations_present + && (gs.stream_opts == sos::SUIT_SYMMETRY || gs.stream_opts == sos::BOTH)) + || gs.rules.hole; + + if (is_suit_symmetry) { + switch (gs.rules.build_pol) { + case pol::SAME_SUIT: + target.emplace_back(c); + break; + case pol::RED_BLACK: + target.emplace_back(c.get_colour(), c.get_rank(), c.is_face_down()); + break; + default: + target.emplace_back(0, c.get_rank(), c.is_face_down()); + break; + } + } else { + target.emplace_back(c); + } +} + +void cached_game_state::add_card_divider() { + data.emplace_back(0, 0); +} + +bool operator==(const cached_game_state& a, const cached_game_state& b) { + return a.data == b.data; +} + + + +////////////////// +// STATE HASHER // +////////////////// + +hasher::hasher(const game_state& gs) : init_gs(gs) { +} + +size_t hasher::operator()(const cached_game_state& cgs) const { + size_t seed = 0; + + for (card d : cgs.data) { + combine(seed, hash_value(d)); + } + return seed; +} + +std::size_t hasher::combine(std::size_t& seed, std::size_t value) const { + return seed ^= value + 0x9e3779b9 + (seed<<6) + (seed>>2); +} + +size_t hasher::hash_value(card const& c) const { + boost::hash<uint8_t> boost_hasher; + + // If the game is a 'hole-based' game, or suit-reduction is enabled, hash + // the reduced suit + bool is_suit_symmetry = (init_gs.rules.foundations_present + && (init_gs.stream_opts == sos::SUIT_SYMMETRY || init_gs.stream_opts == sos::BOTH)) + || init_gs.rules.hole; + + uint8_t suit_val; + if (is_suit_symmetry) { + switch (init_gs.rules.build_pol) { + case pol::SAME_SUIT: + suit_val = c.get_suit(); + break; + case pol::RED_BLACK: + suit_val = c.get_colour(); + break; + default: + suit_val = 0; + } + } else { + suit_val = c.get_suit(); + } + + auto raw_val = static_cast<uint8_t>(suit_val * 13 + c.get_rank()); + return boost_hasher(raw_val); +} + + +/////////////// +// LRU CACHE // +/////////////// + +// Based on https://www.boost.org/doc/libs/1_67_0/libs/multi_index/example/serialization.cpp +/* Boost.MultiIndex example of serialization of a MRU list. + * + * Copyright 2003-2008 Joaquin M Lopez Munoz. + * Distributed under the Boost Software License, Version 1.0. + * (See accompanying file LICENSE_1_0.txt or copy at + * http://www.boost.org/LICENSE_1_0.txt) + * + * See http://www.boost.org/libs/multi_index for library home page. + */ + +item_list::ctor_args_list lru_cache::get_init_tuple(const game_state& gs) { + return boost::make_tuple( + item_list::nth_index<0>::type::ctor_args(), + boost::make_tuple( + size_t(0), + multi_index::identity<cached_game_state>(), + hasher(gs), + equal_to<cached_game_state>() + ) + ); +} + +lru_cache::lru_cache(const game_state& gs, uint64_t max_num_items_) + : max_num_items(max_num_items_), cache(get_init_tuple(gs)), states_removed_from_cache(0) { +} + +pair<item_list::iterator, bool> lru_cache::insert(const game_state& gs) { + pair<item_list::iterator, bool> p = cache.push_front(cached_game_state(gs)); + + if(!p.second){ /* duplicate item */ + cache.relocate(cache.begin(), p.first); /* put in front */ + } else if(cache.size() > max_num_items){ /* keep the length <= max_num_items */ + + // If the least recently used node is 'live' (i.e. a parent), relocates + // it to the head of the list until this is no longer the case + for (uint64_t i = 0; prev(cache.end())->live; i++) { + cache.relocate(cache.begin(), prev(cache.end())); + + if (i == max_num_items) { +#ifndef NDEBUG + LOG_ERROR("All items in cache are live and cache is full"); +#endif + throw runtime_error("All items in cache are live and cache is full"); + } + } + cache.pop_back(); + states_removed_from_cache++; + } + return p; +} + +bool lru_cache::contains(const game_state& gs) const { + return cache.get<1>().count(cached_game_state(gs)) > 0; +} + +void lru_cache::clear() { + cache.clear(); +} + +item_list::size_type lru_cache::size() const { + return cache.size(); +} + +item_list::size_type lru_cache::bucket_count() const { + return cache.get<1>().bucket_count(); +} + +void lru_cache::set_non_live(item_list::iterator state_iter) { +#ifndef NDEBUG + bool succ = +#endif + cache.modify(state_iter, [](auto& v){ v.live = false; }); +#ifndef NDEBUG + assert(succ); +#endif +} + +uint64_t lru_cache::get_states_removed_from_cache() const { + return states_removed_from_cache; +} diff --git a/solvitaire/src/main/game/global_cache.h b/solvitaire/src/main/game/global_cache.h new file mode 100644 index 0000000..e9bb412 --- /dev/null +++ b/solvitaire/src/main/game/global_cache.h @@ -0,0 +1,76 @@ +// +// Created by thecharlesblake on 1/10/18. +// + +#ifndef SOLVITAIRE_GLOBAL_CACHE_H +#define SOLVITAIRE_GLOBAL_CACHE_H + +#include <vector> +#include <unordered_set> +#include <boost/pool/pool.hpp> +#include <boost/pool/pool_alloc.hpp> +#include <boost/multi_index_container.hpp> +#include <boost/multi_index/sequenced_index.hpp> +#include <boost/multi_index/identity.hpp> +#include <boost/multi_index/hashed_index.hpp> + +#include "sol_rules.h" +#include "search-state/game_state.h" + +struct cached_game_state { + typedef std::vector<card> state_data; + typedef state_data::size_type size_type; + + explicit cached_game_state(const game_state&); + void add_pile(pile::ref, const game_state&); + void add_pile_in_reverse(pile::ref, const game_state&); + void add_card(card, const game_state&); + void add_card_divider(); + + state_data data; + bool live; // Is a parent in the current search tree +}; + +bool operator==(const cached_game_state&, const cached_game_state&); + +struct hasher { + explicit hasher(const game_state&); + std::size_t operator() (const cached_game_state&) const; + + std::size_t hash_value(const card&) const; + std::size_t combine(std::size_t&, std::size_t) const; + + const game_state& init_gs; +}; + +class lru_cache { +public: + typedef boost::multi_index::multi_index_container< + cached_game_state, + boost::multi_index::indexed_by< + boost::multi_index::sequenced<>, + boost::multi_index::hashed_unique< + boost::multi_index::identity<cached_game_state>, + hasher + > + > + > item_list; + + explicit lru_cache(const game_state&, uint64_t); + std::pair<item_list::iterator, bool> insert(const game_state&); + bool contains(const game_state&) const; + void clear(); + item_list::size_type size() const; + item_list::size_type bucket_count() const; + void set_non_live(item_list::iterator); + uint64_t get_states_removed_from_cache() const; + +private: + static item_list::ctor_args_list get_init_tuple(const game_state&); + + uint64_t max_num_items; + item_list cache; + uint64_t states_removed_from_cache; +}; + +#endif //SOLVITAIRE_GLOBAL_CACHE_H diff --git a/solvitaire/src/main/game/move.cpp b/solvitaire/src/main/game/move.cpp new file mode 100644 index 0000000..b349ddd --- /dev/null +++ b/solvitaire/src/main/game/move.cpp @@ -0,0 +1,25 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#include "move.h" + +move::move(mtype ty, pile::ref f, pile::ref t, int8_t count_, bool reveal_move_, bool flip_waste_) : + type(ty), from(f), to(t), count(count_), reveal_move(reveal_move_), flip_waste(flip_waste_) { +#ifndef NDEBUG + if (ty == mtype::regular) assert(count == 1); + if (ty == mtype::stock_k_plus) assert(!reveal_move_); +#endif +} + +void move::make_reveal_move() { + reveal_move = true; +} + +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 ) + && (a.reveal_move == b.reveal_move); +} diff --git a/solvitaire/src/main/game/move.h b/solvitaire/src/main/game/move.h new file mode 100644 index 0000000..8250609 --- /dev/null +++ b/solvitaire/src/main/game/move.h @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#ifndef SOLVITAIRE_MOVE_H +#define SOLVITAIRE_MOVE_H + +#include "pile.h" + +struct move { + enum class mtype : uint8_t {regular, dominance, built_group, stock_k_plus, stock_to_all_tableau, sequence, accordion, null}; + + explicit move(mtype, pile::ref = 255 , pile::ref = 255, int8_t = 1, bool reveal_move_ = false, bool flip_waste_ = false); + friend bool operator==(const move&, const move&); + + void make_reveal_move(); + + mtype type; + pile::ref from; + pile::ref to; + // For built piles the size of the pile, or for stock k-plus moves, + // the number of cards to be moved from the stock to the waste before the waste card is played on the foundations + int8_t count; + bool reveal_move; + bool flip_waste; +}; + +#endif //SOLVITAIRE_MOVE_H diff --git a/solvitaire/src/main/game/pile.cpp b/solvitaire/src/main/game/pile.cpp new file mode 100644 index 0000000..23a02af --- /dev/null +++ b/solvitaire/src/main/game/pile.cpp @@ -0,0 +1,92 @@ +// +// Created by thecharlesblake on 10/28/17. +// + +#include <vector> +#include <ostream> + +#include "pile.h" + +using namespace std; + +const pile::size_type pile::max_size_type = 255; + +pile::pile(std::vector<card> pv) : pile_vec(pv) { +} + +pile::pile(std::initializer_list<card> il) : pile_vec(il) { +} + +card pile::top_card() const { + assert(!empty()); + return pile_vec.back(); +} + +bool pile::empty() const { + return pile_vec.empty(); +} + +pile::size_type pile::size() const { + return static_cast<uint8_t>(pile_vec.size()); +} + +card& pile::operator[] (size_type i) { + return pile_vec[pile_vec.size() - 1 - i]; +} + +card pile::operator[] (size_type i) const { + vector<card>::size_type s = pile_vec.size() - 1 - i; + assert(s < pile_vec.size()); + return pile_vec[s]; +} + +void pile::place(const card c) { + pile_vec.emplace_back(c); +} + +card pile::take() { + assert(!empty()); + card c = top_card(); + pile_vec.pop_back(); + return c; +} + +bool operator==(const pile& a, const pile& b) { + return a.pile_vec == b.pile_vec; +} + +bool operator!=(const pile& a, const pile& b) { + return a.pile_vec != b.pile_vec; +} + +bool operator<(const pile& a, const pile& b) { + if (a.size() == b.size()) { + return a.pile_vec < b.pile_vec; + } else { + return a.size() < b.size(); + } +} + +bool operator>(const pile& a, const pile& b) { + if (a.size() == b.size()) { + return a.pile_vec > b.pile_vec; + } else { + return a.size() > b.size(); + } +} + +bool operator<=(const pile& a, const pile& b) { + if (a.size() == b.size()) { + return a.pile_vec <= b.pile_vec; + } else { + return a.size() <= b.size(); + } +} + +bool operator>=(const pile& a, const pile& b) { + if (a.size() == b.size()) { + return a.pile_vec >= b.pile_vec; + } else { + return a.size() >= b.size(); + } +} diff --git a/solvitaire/src/main/game/pile.h b/solvitaire/src/main/game/pile.h new file mode 100644 index 0000000..5ab2404 --- /dev/null +++ b/solvitaire/src/main/game/pile.h @@ -0,0 +1,53 @@ +// +// Created by thecharlesblake on 10/28/17. +// + +#ifndef SOLVITAIRE_PILE_H +#define SOLVITAIRE_PILE_H + +#include <vector> +#include <iterator> + +#include "sol_rules.h" +#include "card.h" + +class pile { + friend class hasher; + friend class game_state; + friend class cached_game_state; +public: + typedef uint8_t size_type; + const static size_type max_size_type; + typedef uint8_t ref; + + pile() = default; + pile(std::vector<card>); + pile(std::initializer_list<card>); + + // Inspect + card top_card() const; + bool empty() const; + size_type size() const; + + // Indexes the vector, with the top card as index 0 + card& operator[] (size_type); + card operator[] (size_type) const; + + friend bool operator==(const pile&, const pile&); + friend bool operator!=(const pile&, const pile&); + friend bool operator<(const pile&, const pile&); + friend bool operator>(const pile&, const pile&); + friend bool operator<=(const pile&, const pile&); + friend bool operator>=(const pile&, const pile&); + + // Modify + void place(card); + card take(); + +private: + // Underlying vector + std::vector<card> pile_vec; +}; + + +#endif //SOLVITAIRE_PILE_H diff --git a/solvitaire/src/main/game/search-state/game_state.cpp b/solvitaire/src/main/game/search-state/game_state.cpp new file mode 100644 index 0000000..6ea550c --- /dev/null +++ b/solvitaire/src/main/game/search-state/game_state.cpp @@ -0,0 +1,764 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#include <vector> +#include <ostream> +#include <algorithm> +#include <functional> + +#include <boost/functional/hash.hpp> +#include <boost/optional.hpp> +#include <boost/random.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" +#include "../sol_rules.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::max; +using std::ostream; +using std::mt19937; +using std::string; + +typedef sol_rules::build_policy pol; +typedef sol_rules::stock_deal_type sdt; +typedef sol_rules::face_up_policy fu; +typedef game_state::streamliner_options sos; +typedef sol_rules::foundations_init_type fit; + +////////////////// +// 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, streamliner_options stream_opts_) + : rules(s_rules) + , stream_opts(stream_opts_) + , foundations_base(card::rank_t(1)) + , 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_present) { + 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)); + } + } + + // If there is a reserve, creates piles + if (rules.accordion_size > 0) { + uint8_t pile_count = rules.accordion_size; + for (uint8_t i = 0; i < pile_count; i++) { + piles.emplace_back(); + accordion.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)); + } + + // Creates the sequence piles + for (uint8_t i = 0; i < rules.sequence_count; i++) { + piles.emplace_back(); + sequences.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, streamliner_options s_opts) + : game_state(s_rules, s_opts) { + deal_parser::parse(*this, doc); +} + +// Constructs an initial game state from a seed +game_state::game_state(const sol_rules& s_rules, int seed, streamliner_options s_opts) + : game_state(s_rules, s_opts) { + auto rng = mt19937(seed); + vector<card> deck = gen_shuffled_deck(rules.max_rank, rules.two_decks, rng); + + // 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 foundation base is random, selects a random rank and suit + card::suit_t rand_suit = 0; + if (!rules.foundations_base) { + boost::random::uniform_int_distribution<card::rank_t> distr_rank(1, rules.max_rank); + foundations_base = distr_rank(rng); + boost::random::uniform_int_distribution<card::suit_t> distr_suit(0, 3); + rand_suit = distr_suit(rng); + } + + // If the foundations begin filled, then fills them + uint8_t founds_to_fill = 0; + switch (rules.foundations_init_cards) { + case sol_rules::foundations_init_type::NONE: + break; + case sol_rules::foundations_init_type::ONE: + founds_to_fill = 1; break; + case sol_rules::foundations_init_type::ALL: + founds_to_fill = static_cast<uint8_t>(4 * (rules.two_decks ? 2 : 1)); break; + } + for (uint8_t f_idx = 0; f_idx < founds_to_fill; f_idx++) { + card c = card((f_idx + rand_suit) % uint8_t(4), foundations_base); + + deck.erase(find(begin(deck), end(deck), c)); + place_card(foundations[(f_idx + rand_suit)], c); + } + + // If there are pre-filled cells, deals to them + auto it = begin(original_cells); + for (uint8_t i = 0; i < rules.cells_pre_filled; i++) { + pile::ref r = *it; + place_card(r, deck.back()); + deck.pop_back(); + it++; + } + + // 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(); + } + } + + // Deals to the sequence piles + if (rules.sequence_count > 0) { + for (int t = 0; !deck.empty(); t++) { + // Adds the randomly generated card to the tableau piles + auto s = t % sequences.size(); + + card c = deck.back(); + if (c.get_rank() == 1) c = "AS"; // The dummy "gap" placeholder + + pile::ref seq_pile = sequences[s]; + place_card(seq_pile, c); + deck.pop_back(); + } + } + + // Deals to the accordion + if (rules.accordion_size > 0) { + for (auto pr : accordion) { + place_card(pr, 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(); + + // If only the top cards are face up, initially deals all face down + if (rules.face_up == fu::TOP_CARDS) c.turn_face_down(); + + // Adds 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(); + } + } + + // Now if necessary, turns the top cards face up + if (rules.face_up == fu::TOP_CARDS) + for (auto& p : piles) + if (!p.empty()) + p[0].turn_face_up(); + + // 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<std::initializer_list<string>> il) + : game_state(s_rules, sos::NONE) {pile::ref pr = 0; + for (auto& p_il : il) { + for (const string& card_str : p_il) { + card c(card_str.c_str(), s_rules.face_up == fu::TOP_CARDS); + place_card(pr, c); + } + pr++; + } + + // Sets foundations base appropriately + if (rules.foundations_present && rules.foundations_base == boost::none) { + for (auto f : foundations) { + if (!piles[f].empty()) { + foundations_base = piles[f].top_card().get_rank(); + return; + } + } + } +} + +game_state::game_state(const sol_rules& s_rules, + std::vector<std::vector<string>> vec) + : game_state(s_rules, sos::NONE) {pile::ref pr = 0; + for (auto& p_vec : vec) { + for (const string& card_str : p_vec) { + card c(card_str.c_str(), s_rules.face_up == fu::TOP_CARDS); + place_card(pr, c); + } + pr++; + } + + // Sets foundations base appropriately + if (rules.foundations_present && rules.foundations_base == boost::none) { + for (auto f : foundations) { + if (!piles[f].empty()) { + foundations_base = piles[f].top_card().get_rank(); + return; + } + } + } +} + +game_state::game_state(const sol_rules& s_rules, + std::vector<std::vector<card::suit_t>> suits, + std::vector<std::vector<card::rank_t>> ranks, + std::vector<std::vector<bool>> face_down) + : game_state(s_rules, sos::NONE) {pile::ref pr = 0; + assert(suits.size() == ranks.size()); + assert(ranks.size() == face_down.size()); + for (std::vector<std::vector<card::suit_t>>::size_type i = 0; + i < suits.size(); ++i) { + assert(suits[i].size() == ranks[i].size()); + assert(ranks[i].size() == face_down[i].size()); + for (std::vector<card::suit_t>::size_type j = 0; j < suits[i].size(); + ++j) { + card c(suits[i][j], ranks[i][j], face_down[i][j]); + place_card(pr, c); + } + pr++; + } + + // Sets foundations base appropriately + if (rules.foundations_present && rules.foundations_base == boost::none) { + for (auto f : foundations) { + if (!piles[f].empty()) { + foundations_base = piles[f].top_card().get_rank(); + return; + } + } + } +} + +// Generates a randomly ordered vector of cards +vector<card> game_state::gen_shuffled_deck(card::rank_t max_rank, + bool two_decks, mt19937 rng) { + vector<card> deck; + + for (int deck_count = 1; deck_count <= (two_decks ? 2 : 1); deck_count++) { + for (card::rank_t rank = 1; rank <= max_rank; rank++) { + for (card::suit_t suit = 0 ; suit < 4; suit++) { + deck.emplace_back(suit, rank); + } + } + } + + assert(deck.size() == pile::size_type(max_rank * (two_decks ? 8 : 4))); + + game_state::shuffle(begin(deck), end(deck), rng); + return deck; +} + +template<class RandomIt, class URBG> +void game_state::shuffle(RandomIt first, RandomIt last, URBG&& g) { + typedef typename std::iterator_traits<RandomIt>::difference_type diff_t; + typedef boost::random::uniform_int_distribution<diff_t> distr_t; + typedef typename distr_t::param_type param_t; + + distr_t D; + diff_t n = last - first; + for (diff_t i = n-1; i > 0; --i) { + using std::swap; + swap(first[i], first[D(g, param_t(0, i))]); + } +} + + + +//////////////////// +// 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_k_plus: + make_stock_k_plus_move(m); + break; + case move::mtype::stock_to_all_tableau: + make_stock_to_all_tableau_move(m); + break; + case move::mtype::sequence: + make_sequence_move(m); + break; + case move::mtype::accordion: + make_accordion_move(m); + break; + case move::mtype::null: + assert(false); + break; + } + +#ifndef NDEBUG + check_face_down_consistent(); +#endif +} + +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_k_plus: + undo_stock_k_plus_move(m); + break; + case move::mtype::stock_to_all_tableau: + undo_stock_to_all_tableau_move(m); + break; + case move::mtype::sequence: + undo_sequence_move(m); + break; + case move::mtype::accordion: + undo_accordion_move(m); + break; + case move::mtype::null: + assert(false); + break; + } + +#ifndef NDEBUG + check_face_down_consistent(); +#endif +} + +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)); + + if (m.reveal_move) { + assert(!piles[m.from].empty()); + assert(piles[m.from][0].is_face_down()); + piles[m.from][0].turn_face_up(); + } + +#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()); + + if (m.reveal_move) { + assert(!piles[m.from].empty()); + assert(!piles[m.from][0].is_face_down()); + piles[m.from][0].turn_face_down(); + } + + 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(m.from < piles.size() ); + assert(m.to < piles.size() ); + + // 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); + } + + if (m.reveal_move) { + assert(!piles[m.from].empty()); + assert(piles[m.from][0].is_face_down()); + piles[m.from][0].turn_face_up(); + } +} + +void game_state::undo_built_group_move(move m) { + assert(m.to < piles.size()); + + if (m.reveal_move) { + assert(!piles[m.from].empty()); + assert(!piles[m.from][0].is_face_down()); + piles[m.from][0].turn_face_down(); + } + + // 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_k_plus_move(const move m) { +#ifndef NDEBUG + assert(rules.stock_deal_t == sdt::WASTE); + assert(m.from == stock); + if (rules.stock_redeal) assert(m.count <= piles[stock].size() && m.count > -piles[waste].size()); + assert(!rules.stock_redeal || m.to != waste); + auto sz_before = piles[stock].size() + piles[waste].size(); +#endif + + // Transfers count cards from the stock to the waste + if (m.count > 0) { + for (int i = 0; i < m.count; i++) { + place_card(waste, take_card(stock)); + } + } else { + for (int i = 0; i > m.count; i--) { + place_card(stock, take_card(waste)); + } + } + + // Moves the card on top of the waste to the target pile + place_card(m.to, take_card(waste)); + + // Flips the waste back on to the empty stock (if necessary) + if (m.flip_waste) { + assert(rules.stock_redeal && piles[stock].empty()); + while (!piles[waste].empty()) { + place_card(stock, take_card(waste)); + } + } + +#ifndef NDEBUG + auto sz_after = piles[stock].size() + piles[waste].size(); + assert(sz_before == sz_after + 1); + assert(!(rules.stock_size > 0 && rules.stock_redeal && piles[stock].empty() && !piles[waste].empty())); + assert(piles[stock].size() <= rules.stock_size); +#endif +} + +void game_state::undo_stock_k_plus_move(move m) { +#ifndef NDEBUG + assert(rules.stock_deal_t == sdt::WASTE); + assert(m.from == stock); + assert(!rules.stock_redeal || m.to != waste); + auto sz_after = piles[stock].size() + piles[waste].size(); +#endif + + if (m.flip_waste) { + assert(rules.stock_redeal && piles[waste].empty()); + while (!piles[stock].empty()) { + place_card(waste, take_card(stock)); + } + } + + place_card(waste, take_card(m.to)); + + if (m.count > 0) { + for (int i = 0; i < m.count; i++) { + place_card(stock, take_card(waste)); + } + } else { + for (int i = 0; i > m.count; i--) { + place_card(waste, take_card(stock)); + } + } + +#ifndef NDEBUG + auto sz_before = piles[stock].size() + piles[waste].size(); + assert(sz_before == sz_after + 1); + if (rules.stock_redeal) assert(m.count <= piles[stock].size() && m.count > -piles[waste].size()); + assert(!(rules.stock_size > 0 && rules.stock_redeal && piles[stock].empty() && !piles[waste].empty())); + assert(piles[stock].size() <= rules.stock_size); +#endif +} + +void game_state::make_stock_to_all_tableau_move(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_all_tableau_move(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_sequence_move(const move m) { + pile::ref from_seq_ref = m.from / rules.max_rank; + pile::size_type from_card_idx = m.from % rules.max_rank; + card from_card = piles[from_seq_ref][from_card_idx]; + piles[from_seq_ref][from_card_idx] = "AS"; + + pile::ref to_seq_ref = m.to / rules.max_rank; + pile::size_type to_card_idx = m.to % rules.max_rank; + assert(piles[to_seq_ref][to_card_idx] == "AS"); + piles[to_seq_ref][to_card_idx] = from_card; +} + +void game_state::undo_sequence_move(const move m) { + pile::ref to_seq_ref = m.to / rules.max_rank; + pile::size_type to_card_idx = m.to % rules.max_rank; + card to_card = piles[to_seq_ref][to_card_idx]; + piles[to_seq_ref][to_card_idx] = "AS"; + + pile::ref from_seq_ref = m.from / rules.max_rank; + pile::size_type from_card_idx = m.from % rules.max_rank; + assert(piles[from_seq_ref][from_card_idx] == "AS"); + piles[from_seq_ref][from_card_idx] = to_card; +} + +void game_state::make_accordion_move(move m) { + make_built_group_move(m); + accordion.remove(m.from); +} + +void game_state::undo_accordion_move(move m) { + accordion.insert(upper_bound(begin(accordion), end(accordion), m.from), m.from); + undo_built_group_move(m); +} + +// 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; +} + +#ifndef NDEBUG +void game_state::check_face_down_consistent() const { + for (auto& p : original_tableau_piles) { + if (piles[p].empty()) continue; + // Makes sure the top cards of each tableau pile are face up + assert(!piles[p].top_card().is_face_down()); + + // Makes sure face down cards are never above face down ones + bool seen_face_up = false; + for (auto& c : piles[p].pile_vec) { + seen_face_up = seen_face_up || !c.is_face_down(); + assert(!(c.is_face_down() && seen_face_up)); + } + } +} +#endif + + +//////////////////////// +// 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 if (rules.foundations_present) { + for (auto f : foundations) { + if (piles[f].size() != rules.max_rank) { + solved = false; + } + } + } else if (rules.sequence_count > 0) { + for (pile::ref i = 0; i < sequences.size() && solved; i++) { + for (pile::ref j = piles[sequences[i]].size(); j-- > 2;) { + if (!is_next_legal_card(rules.sequence_build_pol, piles[sequences[i]][j-1], piles[sequences[i]][j])) { + solved = false; + break; + } + } + if (piles[sequences[i]].top_card() != "AS") solved = false; + } + } else if (rules.accordion_size > 0) { + return accordion.size() == 1; + } else { + assert(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 if (rules.foundations_present) { + bool non_foundation_ref = + pr < foundations.front() + || pr >= foundations.front() + foundations.size(); + if (non_foundation_ref && !piles[pr].empty()) { + rest_empty = false; + break; + } + } + } + if (rules.sequence_count > 0) { + for (auto seq : sequences) { + assert(piles[seq].size() == rules.max_rank); + } + } else { + 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/solvitaire/src/main/game/search-state/game_state.dominance_moves.cpp b/solvitaire/src/main/game/search-state/game_state.dominance_moves.cpp new file mode 100644 index 0000000..d0b4b43 --- /dev/null +++ b/solvitaire/src/main/game/search-state/game_state.dominance_moves.cpp @@ -0,0 +1,192 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#include "game_state.h" +#include "../sol_rules.h" + + +typedef sol_rules::build_policy pol; +typedef game_state::streamliner_options sos; +typedef sol_rules::stock_deal_type sdt; +typedef sol_rules::spaces_policy s_pol; + +using std::max; +using boost::optional; + +bool game_state::is_valid_auto_foundation_move(pile::ref target_pile) const { + if (rules.foundations_only_comp_piles || rules.two_decks) + return false; + else if ( stream_opts == sos::AUTO_FOUNDATIONS + || stream_opts == sos::BOTH + || rules.build_pol == pol::NO_BUILD + || rules.build_pol == pol::SAME_SUIT) + return true; + + card::suit_t target_suit(target_pile - foundations.front()); + card::rank_t move_up_rank = piles[target_pile].empty() + ? card::rank_t(1) + : foundation_base_convert(piles[target_pile].top_card().get_rank() + card::rank_t(1)); + + // The card to be moved up + card move_up_card(target_suit, move_up_rank); + + // 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) + : foundation_base_convert(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 +optional<move> game_state::get_dominance_move() const { +#ifndef NO_AUTO_FOUNDATIONS + if (rules.spaces_pol == s_pol::AUTO_RESERVE_THEN_WASTE) { + optional<move> arm = auto_reserve_move(); + if (arm) return arm; + } else if (rules.spaces_pol == s_pol::AUTO_WASTE_THEN_STOCK) { + optional<move> awsm = auto_waste_stock_move(); + if (awsm) return awsm; + } + + // If there are 2 decks or no foundations, return + if (!rules.foundations_present || 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, waste or stock cards to the foundations + if ((pr >= foundations.front() && pr <= foundations.back()) + || (rules.hole && pr == hole) + || (rules.stock_size > 0 && pr == stock) + || (rules.stock_size > 0 && rules.stock_deal_t == sdt::WASTE && pr == waste) + || (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) + : foundation_base_convert(piles[target_foundation].top_card().get_rank() + card::rank_t(1)); + if (target_rank == foundation_base_convert(c.get_rank()) && + auto_foundation_moves[c.get_suit()]) { + move m(move::mtype::dominance, pr, target_foundation); + + // If this dominance move reveals a card, adds this to the move + if (piles[pr].size() > 1 && piles[pr][1].is_face_down()) + m.make_reveal_move(); + + return m; + } + } +#endif + + return boost::none; +} + +optional<move> game_state::auto_reserve_move() const { + if (rules.spaces_pol == s_pol::AUTO_RESERVE_THEN_WASTE && !piles[reserve.front()].empty()) { + for (auto to : tableau_piles) { + if (piles[to].empty()) { + return move(move::mtype::dominance, reserve.front(), to); + } + } + } + return boost::none; +} + +optional<move> game_state::auto_waste_stock_move() const { + if (!piles[waste].empty()) { + for (auto to : tableau_piles) { + if (piles[to].empty()) { + return move(move::mtype::dominance, waste, to); + } + } + } else if (!piles[stock].empty()) { + for (auto to : tableau_piles) { + if (piles[to].empty()) { + return move(move::mtype::dominance, stock, to); + } + } + } + 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_present + || 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); + } +} + +card::rank_t game_state::foundation_base_convert(card::rank_t r) const { + card::rank_t s = r - (foundations_base - card::rank_t(1)); + if (s < 1) s += rules.max_rank; + return s; +} diff --git a/solvitaire/src/main/game/search-state/game_state.h b/solvitaire/src/main/game/search-state/game_state.h new file mode 100644 index 0000000..1698122 --- /dev/null +++ b/solvitaire/src/main/game/search-state/game_state.h @@ -0,0 +1,182 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#ifndef SOLVITAIRE_GAME_STATE_H +#define SOLVITAIRE_GAME_STATE_H + +#include <vector> +#include <list> +#include <string> +#include <random> +#include <functional> + +#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; + friend class test_helper; + friend class json_helper; +public: + enum class streamliner_options {NONE, AUTO_FOUNDATIONS, SUIT_SYMMETRY, BOTH}; + + /* Constructors */ + + // Creates a game state representation from a JSON doc + game_state(const sol_rules&, const rapidjson::Document&, streamliner_options); + // Does the same from a seed + game_state(const sol_rules&, int seed, streamliner_options); + // Does the same but with an initialiser list (useful for testing) + game_state(const sol_rules&, std::initializer_list<std::initializer_list<std::string>>); + // Does the same but with vectors + game_state(const sol_rules&, std::vector<std::vector<std::string>>); + // Does the same but with lots of vectors + game_state(const sol_rules&, std::vector<std::vector<card::suit_t>>, + std::vector<std::vector<card::rank_t>>, + std::vector<std::vector<bool>>); + + /* 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&, streamliner_options); + static std::vector<card> gen_shuffled_deck(card::rank_t, bool, std::mt19937); + template<class RandomIt, class URBG> static void shuffle(RandomIt, RandomIt, URBG&&); + + /* 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_k_plus_move(move move); + void undo_stock_k_plus_move(move move); + void make_stock_to_all_tableau_move(move move); + void undo_stock_to_all_tableau_move(move move); + void make_sequence_move(move move); + void undo_sequence_move(move move); + void make_accordion_move(move move); + void undo_accordion_move(move move); + +#ifndef NDEBUG + void check_face_down_consistent() const; +#endif + + /* Legal move generation */ + + bool stock_can_deal_all_tableau() const; + move get_stock_to_all_tableau_move() const; + + std::set<std::pair<int8_t, bool>, std::greater<>> generate_k_plus_moves_to_check() const; + void add_stock_to_cell_move(std::vector<move>&, pile::ref) const; + void add_stock_to_tableau_moves(std::vector<move>&) const; + void add_stock_to_hole_foundation_moves(std::vector<move>&) const; + card stock_card_from_count(int8_t) const; + void add_foundation_complete_piles_moves(std::vector<move> &) const; + void add_accordion_moves(std::vector<move>&) const; + + bool is_valid_tableau_move(pile::ref, pile::ref) const; + bool is_valid_tableau_move(card, pile::ref) const; + bool is_next_tableau_card(card, card) const; + bool is_valid_foundations_move(pile::ref, pile::ref) const; + bool is_valid_foundations_move(card, pile::ref) const; + bool is_valid_hole_move(pile::ref) const; + bool is_valid_hole_move(card) const; + + void add_valid_tableau_moves(std::vector<move>&, pile::ref) const; + void add_built_group_moves(std::vector<move>&, bool) const; + void add_built_group_moves(std::vector<move>&, pile::ref, pile::size_type, bool) const; + void add_whole_pile_moves(std::vector<move>&) const; + void add_whole_pile_moves(std::vector<move>&, pile::ref, pile::size_type) const; + pile::size_type get_built_group_height(pile::ref) const; + bool is_next_built_group_card(card, card) const; + void add_empty_built_group_moves(std::vector<move>&, pile::ref, pile::ref, pile::size_type, bool, bool) const; + void add_kings_only_built_group_move(std::vector<move>&, pile::ref, pile::ref, pile::size_type, bool) const; + void add_non_empty_built_group_move(std::vector<move>&, pile::ref, pile::ref, pile::size_type, bool, bool) const; + void add_sequence_moves(std::vector<move>&) const; + bool tableau_space_and_auto_reserve() const; + + bool is_next_legal_card(sol_rules::build_policy, card, card) const; + bool is_next_legal_card(std::vector<sol_rules::accordion_policy>, card, card) const; + void turn_face_down_cards(std::vector<move>&) const; + + /* Auto-foundation moves */ + + boost::optional<move> auto_reserve_move() const; + boost::optional<move> auto_waste_stock_move() const; + 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); + card::rank_t foundation_base_convert(card::rank_t) const; + + /* Game rules */ + + const sol_rules rules; + streamliner_options stream_opts; + card::rank_t foundations_base; + + /* 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; + std::vector<pile::ref> sequences; + std::list<pile::ref> accordion; + 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/solvitaire/src/main/game/search-state/game_state.legal_moves.cpp b/solvitaire/src/main/game/search-state/game_state.legal_moves.cpp new file mode 100644 index 0000000..63a4764 --- /dev/null +++ b/solvitaire/src/main/game/search-state/game_state.legal_moves.cpp @@ -0,0 +1,640 @@ +// +// Created by thecharlesblake on 07/06/18. +// + +#include "game_state.h" +#include "../sol_rules.h" +#include "../move.h" + +#include <boost/optional/optional.hpp> +#include <iostream> + +using std::vector; +using std::min; +using std::list; +using std::pair; +using std::set; +using std::greater; +using namespace rapidjson; + +typedef sol_rules::build_policy pol; +typedef sol_rules::spaces_policy s_pol; +typedef sol_rules::accordion_policy acc_pol; +typedef sol_rules::stock_deal_type sdt; +typedef sol_rules::face_up_policy fu; +typedef sol_rules::direction dir; +typedef sol_rules::built_group_type bgt; + +//////////////////////////////// +// 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) { + // Order: + // Accordion moves + // Foundations complete piles moves + // Tableau / cells / reserve / stock-waste (redeal) to hole / foundation moves + // Cell to tableau moves + // Sequence to sequence moves + // Tableau to tableau moves + // Tableau built group moves + // Stock-waste to tableau moves (redeal) + // Reserve to tableau moves + // Foundation to tableau moves + // Stock-waste to tableau moves (no redeal) + // Stock-waste (no redeal) to hole / foundation moves + // Tableau / reserve / stock-waste to cell moves + // Stock to all tableau moves + + vector<move> moves; + + // Stock to all tableau moves + if (rules.stock_size > 0 && stock_can_deal_all_tableau()) + moves.emplace_back(get_stock_to_all_tableau_move()); + + // Tableau / reserve / stock-waste to cell moves + pile::ref empty_cell = 255; + for (auto c : cells) { + if (piles[c].empty()) empty_cell = c; + } + if (empty_cell != 255) { + for (auto t : tableau_piles) { + if (piles[t].empty() || parent_move.to == t) continue; + else moves.emplace_back(move::mtype::regular, t, empty_cell); + } + + for (auto r : reserve) + if (!piles[r].empty()) + moves.emplace_back(move::mtype::regular, r, empty_cell); + + if (rules.stock_size > 0 && rules.stock_deal_t == sdt::WASTE) + add_stock_to_cell_move(moves, empty_cell); + } + + // Stock-waste (no redeal) to hole / foundation moves + if (rules.hole || (rules.foundations_present && !rules.foundations_only_comp_piles)) { + if (rules.stock_size > 0 && rules.stock_deal_t == sdt::WASTE && !rules.stock_redeal) + add_stock_to_hole_foundation_moves(moves); + } + + // Stock-waste to tableau moves (no redeal) + if (rules.stock_size > 0 && rules.stock_deal_t == sdt::WASTE && !rules.stock_redeal) + add_stock_to_tableau_moves(moves); + + // Foundation to tableau / empty cell moves + if (rules.foundations_removable) { + for (auto f : foundations) { + if (piles[f].empty() || parent_move.to == f || dominance_blocks_foundation_move(f)) continue; + + add_valid_tableau_moves(moves, f); + + if (empty_cell != 255) + moves.emplace_back(move::mtype::regular, f, empty_cell); + } + } + + // Reserve to tableau moves + for (auto r : reserve) { + if (piles[r].empty()) continue; + + add_valid_tableau_moves(moves, r); + } + + // Stock-waste to tableau moves (redeal) + if (rules.stock_size > 0 && rules.stock_deal_t == sdt::WASTE && rules.stock_redeal) + add_stock_to_tableau_moves(moves); + + // Tableau built group moves + switch (rules.move_built_group) { + case sol_rules::built_group_type::YES: + add_built_group_moves(moves, false); + break; + case sol_rules::built_group_type::MAXIMAL_GROUP: + add_built_group_moves(moves, true); + break; + case sol_rules::built_group_type::WHOLE_PILE: + add_whole_pile_moves(moves); + break; + case sol_rules::built_group_type::NO: + break; + } + + // Tableau to tableau moves + // If only whole pile moves are available, doesn't make regular ones + if (rules.move_built_group != bgt::WHOLE_PILE) { + for (auto t_from : tableau_piles) { + // Forbids moves from empty piles, reversing parent moves, or from single- + // card piles to empty piles + if (piles[t_from].empty() || parent_move.to == t_from || tableau_space_and_auto_reserve()) continue; + + for (auto to : tableau_piles) { + if (is_valid_tableau_move(t_from, to) + && !(piles[t_from].size() == 1 && piles[to].empty())) { + moves.emplace_back(move::mtype::regular, t_from, to); + } + } + } + } + + // Sequence to sequence moves + if (rules.sequence_count > 0) { + add_sequence_moves(moves); + } + + // Cell to tableau moves + for (auto c : cells) { + if (piles[c].empty() || parent_move.to == c) continue; + + add_valid_tableau_moves(moves, c); + } + + // Tableau / cells / reserve / stock-waste (redeal) to hole / foundation moves + if (rules.hole || (rules.foundations_present && !rules.foundations_only_comp_piles)) { + // Stock + if (rules.stock_size > 0 && rules.stock_deal_t == sdt::WASTE && rules.stock_redeal) + add_stock_to_hole_foundation_moves(moves); + + list<pile::ref> from_piles = tableau_piles; + if (rules.cells > 0) from_piles.insert(from_piles.end(), cells.begin(), cells.end()); + if (rules.reserve_size > 0) from_piles.insert(from_piles.end(), reserve.begin(), reserve.end()); + + for (auto fp : from_piles) { + if (piles[fp].empty() || (parent_move.to == fp && parent_move.type != move::mtype::dominance)) continue; + + for (auto f : foundations) + if (is_valid_foundations_move(fp, f)) + moves.emplace_back(move::mtype::regular, fp, f); + if (rules.hole && is_valid_hole_move(fp)) + moves.emplace_back(move::mtype::regular, fp, hole); + } + } + + if (rules.foundations_only_comp_piles) // i.e. Spider-type winning condition + add_foundation_complete_piles_moves(moves); + + if (rules.tableau_pile_count > 0 && rules.face_up != fu::ALL) + turn_face_down_cards(moves); + + if (rules.accordion_size > 0) + add_accordion_moves(moves); + + return moves; +} + + +//////////////////////////////// +// REGULAR MOVE GEN FUNCTIONS // +//////////////////////////////// + +bool game_state::stock_can_deal_all_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_to_all_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_all_tableau, 0, 0, stock_moves); +} + +set<pair<int8_t, bool>, greater<>> game_state::generate_k_plus_moves_to_check() const { + set<pair<int8_t, bool>, greater<>> stock_moves_to_check; + + // If the waste isn't empty, adds the move from the top of the current waste + if (!piles[waste].empty()) stock_moves_to_check.insert(pair<int8_t, bool>(0, false)); + else if (piles[stock].empty()) return stock_moves_to_check; + + // Adds multiples of deal count (excluding last card) + for (int8_t count = rules.stock_deal_count; + count < piles[stock].size(); + count += rules.stock_deal_count) + stock_moves_to_check.insert(pair<int8_t, bool>(count, false)); + + // Adds last card + bool flip_waste = rules.stock_redeal; + stock_moves_to_check.insert(pair<int8_t, bool>(static_cast<int8_t>(piles[stock].size()), flip_waste)); + + // If the stock can be redealt, searches through the waste then the stock again + if (rules.stock_redeal) + for (auto count = static_cast<int8_t>(-piles[waste].size() + rules.stock_deal_count); + count < piles[stock].size(); + count += rules.stock_deal_count) + stock_moves_to_check.insert(pair<int8_t, bool>(count, false)); + + return stock_moves_to_check; +} + +void game_state::add_stock_to_cell_move(std::vector<move>& moves, pile::ref empty_cell) const { + for (auto k_plus_mv : generate_k_plus_moves_to_check()) + moves.emplace_back(move::mtype::stock_k_plus, stock, empty_cell, k_plus_mv.first, false, k_plus_mv.second); +} + +void game_state::add_stock_to_tableau_moves(std::vector<move>& moves) const { + // For each stock move to check, if it can be moved legally to one of the tableau + // piles, adds this as a move + for (auto k_plus_mv : generate_k_plus_moves_to_check()) { + card from = stock_card_from_count(k_plus_mv.first); + + // Obeys the auto-reserve restriction unless the reserve is empty + if (!piles[reserve.front()].empty() && tableau_space_and_auto_reserve()) return; + + for (auto t : tableau_piles) { + if (is_valid_tableau_move(from, t)) { + moves.emplace_back(move::mtype::stock_k_plus, stock, t, k_plus_mv.first, false, k_plus_mv.second); + } + } + } +} + +void game_state::add_stock_to_hole_foundation_moves(std::vector<move>& moves) const { + for (auto k_plus_mv : generate_k_plus_moves_to_check()) { + card from = stock_card_from_count(k_plus_mv.first); + + for (auto f : foundations) + if (is_valid_foundations_move(from, f)) + moves.emplace_back(move::mtype::stock_k_plus, stock, f, k_plus_mv.first, false, k_plus_mv.second); + + if (rules.hole && is_valid_hole_move(from)) + moves.emplace_back(move::mtype::stock_k_plus, stock, hole, k_plus_mv.first, false, k_plus_mv.second); + } +} + +card game_state::stock_card_from_count(int8_t count) const { + if (count > 0) { + return piles[stock][count - 1]; + } else { + return piles[waste][-count]; + } +} + +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; + + return is_valid_tableau_move(piles[rem_ref].top_card(), add_ref); +} + +bool game_state::is_valid_tableau_move(const card rem_c, + const pile::ref add_ref) const { + 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 rem_c.get_rank() == 13; + default: + return true; + } + } else { + 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_only_comp_piles) return false; + + return is_valid_foundations_move(piles[rem_ref].top_card(), add_ref); +} + +bool game_state::is_valid_foundations_move(const card rem_c, + const pile::ref add_ref) const { + if (piles[add_ref].size() == rules.max_rank) return false; + + // 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() == foundations_base; + else + return rem_c.get_rank() == (piles[add_ref].top_card().get_rank() % rules.max_rank) + 1; +} + +bool game_state::is_valid_hole_move(const pile::ref rem_ref) const { + if (rem_ref == hole) return false; + return is_valid_hole_move(piles[rem_ref].top_card()); +} + +bool game_state::is_valid_hole_move(const card c) const { + card::rank_t rank = c.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_valid_tableau_moves(std::vector<move>& moves, pile::ref from) const { + if (tableau_space_and_auto_reserve()) return; + + for (auto to : tableau_piles) { + if (is_valid_tableau_move(from, to)) { + moves.emplace_back(move::mtype::regular, from, to); + } + } +} + +void game_state::add_built_group_moves(vector<move>& moves, bool only_maximal) const { + assert(rules.built_group_pol != pol::NO_BUILD); + if (tableau_space_and_auto_reserve()) return; + + // 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; + + add_built_group_moves(moves, rem_ref, built_group_height, only_maximal); + } +} + +void game_state::add_built_group_moves(vector<move>& moves, pile::ref rem_ref, pile::size_type built_group_height, + bool only_maximal) const { + // 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]; + bool base_face_down = + piles[rem_ref].size() > built_group_height + && piles[rem_ref][built_group_height].is_face_down(); + + if (piles[add_ref].empty()) { + if (rules.spaces_pol == s_pol::ANY) { + add_empty_built_group_moves(moves, rem_ref, add_ref, built_group_height, base_face_down, only_maximal); + } else if (rules.spaces_pol == s_pol::KINGS && bg_high.get_rank() == 13) { + add_kings_only_built_group_move(moves, rem_ref, add_ref, built_group_height, base_face_down); + } + } else { + add_non_empty_built_group_move(moves, rem_ref, add_ref, built_group_height, base_face_down, only_maximal); + } + } +} + +void game_state::add_whole_pile_moves(vector<move>& moves) const { + assert(rules.built_group_pol != pol::NO_BUILD); + if (tableau_space_and_auto_reserve()) return; + + // Cycles through each pile to see if it contains a whole-pile built group + for (auto rem_ref : tableau_piles) { + auto built_group_height = get_built_group_height(rem_ref); + + if (built_group_height == piles[rem_ref].size()) { + add_whole_pile_moves(moves, rem_ref, built_group_height); + } + } +} + +void game_state::add_whole_pile_moves(vector<move>& moves, pile::ref rem_ref, pile::size_type built_group_height) const { + // 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)) { + moves.emplace_back(move::mtype::built_group, rem_ref, add_ref, built_group_height); + } + } 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 (i < piles[ref].size() + && is_next_built_group_card(piles[ref][i], piles[ref][i-1]) + && !piles[ref][i].is_face_down()) + i++; + return i; +} + +bool game_state::is_next_built_group_card(card a, card b) const { + return is_next_legal_card(rules.built_group_pol, a, b); +} + +// 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, + pile::size_type built_group_height, bool base_face_down, bool only_maximal) +const { + auto start_idx = static_cast<pile::size_type>(only_maximal ? built_group_height - 1 : 1); + for (pile::size_type card_idx = start_idx; card_idx < built_group_height; card_idx++) { + bool is_reveal_move = card_idx + 1 == built_group_height && base_face_down; + moves.emplace_back(move::mtype::built_group, rem_ref, add_ref, card_idx + 1, is_reveal_move); + } +} + +void game_state::add_kings_only_built_group_move(vector<move>& moves, pile::ref rem_ref, pile::ref add_ref, + pile::size_type built_group_height, bool base_face_down) const { + + moves.emplace_back(move::mtype::built_group, rem_ref, add_ref, built_group_height, base_face_down); +} + +void game_state::add_non_empty_built_group_move(vector<move>& moves, pile::ref rem_ref, pile::ref add_ref, + pile::size_type built_group_height, bool base_face_down, bool only_maximal) const { + + auto start_idx = static_cast<pile::size_type>(only_maximal ? built_group_height - 1 : 1); + + // Given rank of add pile, get card of that rank - 1 in rem pile and see if next bg card + // For each card going down from top card in rem pile, check if is next bg card + for (pile::ref r = start_idx; r < built_group_height; r++) { + if (is_next_built_group_card(piles[add_ref].top_card(), piles[rem_ref][r])) { + + bool is_reveal_move = r + 1 == built_group_height && base_face_down; + moves.emplace_back(move::mtype::built_group, rem_ref, add_ref, r + 1, is_reveal_move); + break; + } + } +} + +void game_state::add_sequence_moves(std::vector<move>& moves) const { + // Note, the sequence moves are encoded by counting each card's location (1-52) and adding that into 'to' and 'from' + + // Finds the spaces + vector<pair<uint8_t, uint8_t>> space_locations; + for (pile::ref i = 0; i < sequences.size(); i++) { + + for (pile::ref j = piles[sequences[i]].size(); j --> 0 ;) { + if (piles[sequences[i]][j] == "AS") { + space_locations.emplace_back(i, j); + } + } + } + + // Searches through the cards again to find valid moves into the spaces + for (pile::ref i = 0; i < sequences.size(); i++) { + for (pile::ref j = piles[sequences[i]].size(); j --> 0 ;) { + pile::ref from_idx = i * piles[sequences[i]].size() + j; // Encoded index of card to be moved + card from_card = piles[sequences[i]][j]; + if (from_card == "AS") continue; + + // Adds valid moves + for (pair<uint8_t, uint8_t> space_loc : space_locations) { + pile::ref space_idx = space_loc.first * piles[sequences[i]].size() + space_loc.second; // Encoded index of space + + if (rules.sequence_direction == dir::LEFT || rules.sequence_direction == dir::BOTH) { + // Only twos in the far left column + if (space_loc.second == piles[sequences[i]].size() - 1) { + if (from_card.get_rank() == 2) { + bool is_legal = false; + + if (rules.sequence_fixed_suit) { + if (from_card.get_suit() == space_loc.first) { + is_legal = true; + } + } else { + is_legal = true; + } + + if (is_legal) { + moves.emplace_back(move::mtype::sequence, from_idx, space_idx); + } + } + } + // Otherwise must agree with left neighbour + else { + card neighbour_card = piles[sequences[space_loc.first]][space_loc.second + 1]; + if (neighbour_card != "AS" && is_next_legal_card(rules.sequence_build_pol, from_card, neighbour_card)) + moves.emplace_back(move::mtype::sequence, from_idx, space_idx); + } + } + + if (rules.sequence_direction == dir::RIGHT || rules.sequence_direction == dir::BOTH) { + // Only max rank in the far right column + if (space_loc.second == 0) { + if (from_card.get_rank() == rules.max_rank) + moves.emplace_back(move::mtype::sequence, from_idx, space_idx); + } + // Otherwise must agree with right neighbour + else { + card neighbour_card = piles[sequences[space_loc.first]][space_loc.second - 1]; + if (neighbour_card != "AS" && is_next_legal_card(rules.sequence_build_pol, neighbour_card, from_card)) + moves.emplace_back(move::mtype::sequence, from_idx, space_idx); + } + } + } + } + } +} + +void game_state::add_accordion_moves(vector<move>& moves) const { + int idx = 0, idx_max = static_cast<int>(accordion.size()); + for (auto from_it = begin(accordion); from_it != end(accordion); from_it++, idx++) { + for (pair<dir, uint8_t> move_rule : rules.accordion_moves) { + auto to_it = from_it; + + if (move_rule.first == dir::LEFT && idx - move_rule.second >= 0) { + for (uint8_t i = 0; i < move_rule.second; i++) to_it--; + } else if (move_rule.first == dir::RIGHT && idx + move_rule.second < idx_max) { + for (uint8_t i = 0; i < move_rule.second; i++) to_it++; + } else { + continue; + } + + if (is_next_legal_card(rules.accordion_pol, piles[*to_it].top_card(), piles[*from_it].top_card())) + moves.emplace_back(move::mtype::accordion, *from_it, *to_it, piles[*from_it].size()); + } + } +} + +// If auto-reserve is enabled and there is a space, returns +bool game_state::tableau_space_and_auto_reserve() const { + if (rules.spaces_pol == s_pol::AUTO_RESERVE_THEN_WASTE) + for (auto to : tableau_piles) + if (piles[to].empty()) return true; + return false; +} + +/////////////////////// + +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 + auto final_rank = foundations_base == 1 + ? rules.max_rank + : foundations_base - card::rank_t(1); + if (b.get_rank() == final_rank) { + return false; + } else { + return (b.get_rank() % rules.max_rank) + 1 == a.get_rank(); + } +} + +bool game_state::is_next_legal_card(vector<acc_pol> vp, card a, card b) const { + for (auto p : vp) { + switch (p) { + case sol_rules::accordion_policy::SAME_RANK: + if (b.get_rank() == a.get_rank()) return true; + break; + case sol_rules::accordion_policy::SAME_SUIT: + if (b.get_suit() == a.get_suit()) return true; + break; + case sol_rules::accordion_policy::RED_BLACK: + if (b.get_colour() != a.get_colour()) return true; + break; + case sol_rules::accordion_policy::ANY_SUIT: + return true; + } + } + return false; +} + +void game_state::turn_face_down_cards(vector<move>& moves) const { + for (auto& m : moves) { + bool is_tableau_move = m.from >= original_tableau_piles.front() && m.from <= original_tableau_piles.back(); + if (is_tableau_move && piles[m.from].size() > 1 && piles[m.from][1].is_face_down()) { + m.make_reveal_move(); + } + } +} diff --git a/solvitaire/src/main/game/search-state/game_state.pile_order.cpp b/solvitaire/src/main/game/search-state/game_state.pile_order.cpp new file mode 100644 index 0000000..736cc89 --- /dev/null +++ b/solvitaire/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/solvitaire/src/main/game/sol_rules.cpp b/solvitaire/src/main/game/sol_rules.cpp new file mode 100644 index 0000000..940b1a4 --- /dev/null +++ b/solvitaire/src/main/game/sol_rules.cpp @@ -0,0 +1,43 @@ +// +// Created by thecharlesblake on 1/12/18. +// + +#include "sol_rules.h" + +typedef sol_rules::build_policy pol; +typedef sol_rules::spaces_policy s_pol; +typedef sol_rules::stock_deal_type sdt; +typedef sol_rules::direction dir; +typedef sol_rules::face_up_policy fu; +typedef sol_rules::built_group_type bgt; +typedef sol_rules::foundations_init_type fit; + +// Note that the 'default' sol rules are set up by parsing the default json +// rules description. This initialisation is really just for testing purposes. +sol_rules::sol_rules() : + tableau_pile_count(0), + build_pol(pol::ANY_SUIT), + spaces_pol(s_pol::ANY), + move_built_group(bgt::NO), + built_group_pol(pol::ANY_SUIT), + two_decks(false), + max_rank(13), + hole(false), + foundations_present(false), + foundations_init_cards(fit::NONE), + foundations_base(1), + foundations_only_comp_piles(false), + diagonal_deal(false), + cells(0), + cells_pre_filled(0), + stock_size(0), + stock_deal_t(sdt::TABLEAU_PILES), + stock_deal_count(1), + reserve_size(0), + reserve_stacked(false), + face_up(fu::ALL), + sequence_count(0), + sequence_direction(dir::LEFT), + sequence_build_pol(pol::SAME_SUIT), + accordion_size(0) { +} diff --git a/solvitaire/src/main/game/sol_rules.h b/solvitaire/src/main/game/sol_rules.h new file mode 100644 index 0000000..6a6b575 --- /dev/null +++ b/solvitaire/src/main/game/sol_rules.h @@ -0,0 +1,95 @@ +// +// Created by thecharlesblake on 10/28/17. +// + +#ifndef SOLVITAIRE_SOL_RULES_H +#define SOLVITAIRE_SOL_RULES_H + +#include <string> +#include <vector> +#include <boost/optional.hpp> + +#include "card.h" +#include "../../../lib/rapidjson/document.h" + +struct sol_rules { + sol_rules(); + + // Tableau policies + enum class build_policy { + NO_BUILD, + SAME_SUIT, + RED_BLACK, + ANY_SUIT + }; + enum class spaces_policy { + NO_BUILD, + KINGS, + ANY, + AUTO_RESERVE_THEN_WASTE, + AUTO_WASTE_THEN_STOCK + }; + enum class accordion_policy { + SAME_RANK, + SAME_SUIT, + RED_BLACK, + ANY_SUIT + }; + enum class stock_deal_type { + WASTE, + TABLEAU_PILES + }; + enum class face_up_policy { + ALL, + TOP_CARDS + }; + enum class direction { + LEFT, + RIGHT, + BOTH + }; + enum class built_group_type { + YES, + NO, + WHOLE_PILE, + MAXIMAL_GROUP + }; + enum class foundations_init_type { + NONE, + ONE, + ALL + }; + + uint8_t tableau_pile_count; + build_policy build_pol; + spaces_policy spaces_pol; + built_group_type move_built_group; + build_policy built_group_pol; + bool two_decks; + uint8_t max_rank; + bool hole; + bool foundations_present; + foundations_init_type foundations_init_cards; + boost::optional<card::rank_t> foundations_base; + bool foundations_removable; + bool foundations_only_comp_piles; + bool diagonal_deal; + uint8_t cells; + uint8_t cells_pre_filled; + uint8_t stock_size; + stock_deal_type stock_deal_t; + uint8_t stock_deal_count; + bool stock_redeal; + uint8_t reserve_size; + bool reserve_stacked; + face_up_policy face_up; + uint8_t sequence_count; + direction sequence_direction; + build_policy sequence_build_pol; + bool sequence_fixed_suit; + uint8_t accordion_size; + std::vector<std::pair<direction, uint8_t>> accordion_moves; + std::vector<accordion_policy> accordion_pol; +}; + +#endif //SOLVITAIRE_SOL_RULES_H diff --git a/solvitaire/src/main/input-output/input/command_line_helper.cpp b/solvitaire/src/main/input-output/input/command_line_helper.cpp new file mode 100644 index 0000000..ae0f9c4 --- /dev/null +++ b/solvitaire/src/main/input-output/input/command_line_helper.cpp @@ -0,0 +1,335 @@ +// +// Created by thecharlesblake on 10/16/17. +// + +#include <tuple> +#include <vector> + +#include <boost/program_options.hpp> + +#include "command_line_helper.h" +#include "../../game/sol_rules.h" +#include "../output/log_helper.h" +#include "sol_preset_types.h" + +using namespace std; + +namespace po = boost::program_options; + +command_line_helper::command_line_helper() + : main_options("options") { + + main_options.add_options() + ("help", "produce help message") + ("type", po::value<string>(), + "specify the type of the solitaire game to be solved from the list " + "of preset games. Must supply either this 'type' option, " + "or the 'custom-rules' option") + ("available-game-types", "outputs a list of the different preset " + "game types that can be solved") + ("describe-game-rules", po::value<string>(), + "outputs the JSON that describes the rules of the supplied " + "preset game type") + ("custom-rules", po::value<string>(), + "the path to a JSON file describing the rules of the solitaire " + "to be solved. Must supply either 'type' or 'custom-rules' option") + ("random", po::value<int>(), "create and solve a random solitaire " + "deal based on a seed. Must supply either 'random'," + "'solvability', 'benchmark' or list of deals to be solved.") + ("classify", "outputs a simple 'solvable/not solvable' " + "classification") + ("cache-capacity", po::value<uint64_t>(), "sets an upper bound on the number of states allowed in " + "the cache") + ("solvability", po::value<int>(), "calculates the solvability " + "percentage of the supplied solitaire game, given a limit for the number of seeds. Must supply " + "either 'random', 'benchmark', 'solvability' or list of deals to be solved.") + ("timeout", po::value<uint64_t>(), "adds a timeout to searches") + ("resume", po::value<vector<int>>()->multitoken(), "resumes the solvability percentage calculation from a " + "previous run. Must be supplied with the solvability option. " + "Syntax: [sol unsol intract in-progress-1 in-progress-2 ...]") + ("cores", po::value<uint>(), "the number of cores for the solvability percentages to be run across. " + "Must be supplied with the solvability option.") + ("streamliners", po::value<string>(), + "Applies streamliners to the search. Options include 'none', 'both', 'suit-symmetry'," + " 'auto-foundations', and 'smart-solvability'. Defaults to 'none', unless '--solvability' is" + " also supplied, in which case defaults to 'smart-solvability'. 'smart-solvability' mode" + " runs first with both streamliners and a 10% timeout. If this" + " is unsuccessful (unsolvable or timeout), then runs again without streamliners.") + ("benchmark", "outputs performance statistics for the solver on the " + "supplied solitaire game. Must supply " + "either 'random', 'benchmark', 'solvability' or list of deals to be " + "solved.") + ("deal-only", "outputs the starting deal for a given game type & random seed as json"); + + po::options_description hidden_options("Hidden options"); + hidden_options.add_options() + ("input-files", po::value<vector<string>>(), + "the file containing the deal to be solved"); + + cmdline_options.add(main_options).add(hidden_options); + + p.add("input-files", -1); +} + +// Returns true if we can continue solving the supplied solitaire(s) +bool command_line_helper::parse(int argc, const char* argv[]) { + po::variables_map vm; + // Attempts to parse cmdln options. Catches basic errors + try { + store(po::command_line_parser(argc, argv).options(cmdline_options) + .positional(p).run(), vm); + } catch(po::error& e) { + LOG_ERROR ("Error: " << e.what()); + return false; + } + + // Updates the variables map which the user's options are stored in + notify(vm); + + // Converts the variables map into flags and values + + help = (vm.count("help") != 0); + + available_game_types = (vm.count("available-game-types") != 0); + + if (vm.count("describe-game-rules")) { + describe_game_rules = vm["describe-game-rules"].as<string>(); + } + + classify = (vm.count("classify") != 0); + + deal_only = (vm.count("deal-only") != 0); + + if (vm.count("input-files")) { + input_files = vm["input-files"].as<vector<string>>(); + } + + if (vm.count("type")) { + solitaire_type = vm["type"].as<string>(); + } + + if (vm.count("custom-rules")) { + rules_file = vm["custom-rules"].as<string>(); + } + + if (vm.count("random")) { + random_deal = vm["random"].as<int>(); + } else { + random_deal = -1; + } + + if (vm.count("cache-capacity")) { + cache_capacity = vm["cache-capacity"].as<uint64_t>(); + } else { + cache_capacity = 100000000; // One hundred-million + } + + if (vm.count("solvability")) { + solvability = vm["solvability"].as<int>(); + } else { + solvability = -1; + } + + if (vm.count("timeout")) { + timeout = vm["timeout"].as<uint64_t>(); + } else { + timeout = 604800000; // 1 week in milliseconds + } + + if (vm.count("cores")) { + cores = vm["cores"].as<uint>(); + } else { + cores = 1; + } + + if (vm.count("resume")) { + resume = vm["resume"].as<vector<int>>(); + } else { + resume = {0, 0, 0}; + for (uint i = 0; i < cores; i++) resume.push_back(i); + } + + if (vm.count("streamliners")) { + auto& s = vm["streamliners"].as<string>(); + + if (s == "auto-foundations" ) streamliners = streamliner_opt::AUTO_FOUNDATIONS; + else if (s == "suit-symmetry") streamliners = streamliner_opt::SUIT_SYMMETRY; + else if (s == "both") streamliners = streamliner_opt::BOTH; + else if (s == "smart-solvability") streamliners = streamliner_opt::SMART; + else if (s == "none") streamliners = streamliner_opt::NONE; + else { + print_streamliner_error(s); + return false; + } + } else { + if (solvability == -1) streamliners = streamliner_opt::NONE; + else streamliners = streamliner_opt::SMART; + } + + benchmark = (vm.count("benchmark") != 0); + + // Handle logic error scenarios + return assess_errors(); +} + +bool command_line_helper::assess_errors() { + if (help) { + print_help(); + return false; + } + + if (available_game_types || !describe_game_rules.empty()) return true; + + if (solvability > 0 && resume.size() != 3 + cores) { + print_resume_error(); + return false; + } + + // The user must either supply input files, a random seed, or ask for the + // solvability percentage, or benchmark + int opt_count = (random_deal != -1) + !input_files.empty() + (solvability > 0) + benchmark; + + if (opt_count > 1) { + print_too_many_opts_error(); + return false; + } else if (opt_count < 1) { + print_no_opts_error(); + return false; + } + + // The user must supply either a solitaire type or a rules file + if ((solitaire_type.empty() && rules_file.empty()) + || (!solitaire_type.empty() && !rules_file.empty())) { + print_sol_type_rules_error(); + return false; + } + + if (!solitaire_type.empty()) { + return assess_sol_type(); + } else { + return true; + } +} + +// Checks if the supplied solitaire type is in the list of valid solitaires +bool command_line_helper::assess_sol_type() { + if (sol_preset_types::is_valid_preset(solitaire_type)) { + return true; + + } else { + LOG_ERROR ("Error: Solitaire type is not valid: " << solitaire_type); + print_help(); + return false; + } +} + +void command_line_helper::print_help() { + cerr << "Usage: solvitaire [options] input-file1 input-file2 ...\n" + << main_options << "\n"; +} + +void command_line_helper::print_no_opts_error() { + LOG_ERROR ("Error: User must supply input file(s), the '--random' " + "option, the 'benchmark' option, or the '--solvability' option"); + print_help(); +} + +void command_line_helper::print_sol_type_rules_error() { + LOG_ERROR ("Error: User must supply either a solitaire type, or a 'rules' " + "file"); + print_help(); +} + +void command_line_helper::print_too_many_opts_error() { + LOG_ERROR ("Error: User must supply input file(s), the '--random' option, the 'benchmark' option,, " + "or the '--solvability' option, not multiple"); + print_help(); +} + +void command_line_helper::print_resume_error() { + LOG_ERROR ("Error: Resume contains " << resume.size() << " options, and should contain " << cores + 3); + print_help(); +} + +void command_line_helper::print_streamliner_error(const string& str) { + LOG_ERROR ("Error: invalid streamliner: " + str + ".\nAvailable options are: 'none', 'both', 'suit-symmetry'," + " 'auto-foundations', and 'smart-solvability'"); +} + +const vector<string> command_line_helper::get_input_files() { + return input_files; +} + +const string command_line_helper::get_solitaire_type() { + return solitaire_type; +} + +const string command_line_helper::get_rules_file() { + return rules_file; +} + +int command_line_helper::get_random_deal() { + return random_deal; +} + +bool command_line_helper::get_classify() { + return classify; +} + +bool command_line_helper::get_deal_only() { + return deal_only; +} + +uint64_t command_line_helper::get_cache_capacity() { + return cache_capacity; +} + +int command_line_helper::get_solvability() { + return solvability; +} + +uint64_t command_line_helper::get_timeout() { + return timeout; +} + +vector<int> command_line_helper::get_resume() { + return resume; +} + +uint command_line_helper::get_cores() { + return cores; +} + +bool command_line_helper::get_available_game_types() { + return available_game_types; +} + +string command_line_helper::get_describe_game_rules() { + return describe_game_rules; +} + +bool command_line_helper::get_benchmark() { + return benchmark; +} + +command_line_helper::streamliner_opt command_line_helper::get_streamliners() { + return streamliners; +} + +game_state::streamliner_options command_line_helper::get_streamliners_game_state() { + return convert_streamliners(streamliners); +} + +game_state::streamliner_options command_line_helper::convert_streamliners(streamliner_opt so) { + switch (so){ + case command_line_helper::streamliner_opt::NONE: return game_state::streamliner_options::NONE; + case command_line_helper::streamliner_opt::AUTO_FOUNDATIONS: return game_state::streamliner_options::AUTO_FOUNDATIONS; + case command_line_helper::streamliner_opt::SUIT_SYMMETRY: return game_state::streamliner_options::SUIT_SYMMETRY; + case command_line_helper::streamliner_opt::BOTH: return game_state::streamliner_options::BOTH; + case command_line_helper::streamliner_opt::SMART: + default: + assert(false); + throw runtime_error("attempted to convert smart streamliner mode to single streamliner"); + return game_state::streamliner_options::NONE;; + } +} diff --git a/solvitaire/src/main/input-output/input/command_line_helper.h b/solvitaire/src/main/input-output/input/command_line_helper.h new file mode 100644 index 0000000..f2a9d74 --- /dev/null +++ b/solvitaire/src/main/input-output/input/command_line_helper.h @@ -0,0 +1,67 @@ +// +// Created by thecharlesblake on 10/16/17. +// + +#ifndef SOLVITAIRE_COMMAND_LINE_HELPER_H +#define SOLVITAIRE_COMMAND_LINE_HELPER_H + +#include <boost/program_options.hpp> +#include "../../game/search-state/game_state.h" + +class command_line_helper { +public: + command_line_helper(); + enum class streamliner_opt {NONE, AUTO_FOUNDATIONS, SUIT_SYMMETRY, BOTH, SMART}; + + bool parse(int argc, const char* argv[]); + const std::vector<std::string> get_input_files(); + const std::string get_solitaire_type(); + const std::string get_rules_file(); + int get_random_deal(); + bool get_classify(); + bool get_deal_only(); + int get_solvability(); + uint get_cores(); + bool get_available_game_types(); + bool get_benchmark(); + streamliner_opt get_streamliners(); + game_state::streamliner_options get_streamliners_game_state(); + std::vector<int> get_resume(); + uint64_t get_cache_capacity(); + std::string get_describe_game_rules(); + uint64_t get_timeout(); + static game_state::streamliner_options convert_streamliners(streamliner_opt); + +private: + bool assess_errors(); + bool assess_sol_type(); + void print_help(); + void print_sol_type_rules_error(); + void print_no_opts_error(); + void print_too_many_opts_error(); + void print_resume_error(); + void print_streamliner_error(const std::string&); + + boost::program_options::options_description cmdline_options; + boost::program_options::options_description main_options; + boost::program_options::positional_options_description p; + + std::vector<std::string> input_files; + std::string solitaire_type; + std::string rules_file; + std::string describe_game_rules; + int random_deal; + bool help; + bool classify; + bool deal_only; + int solvability; + std::vector<int> resume; + uint cores; + bool available_game_types; + bool benchmark; + streamliner_opt streamliners; + uint64_t cache_capacity; + uint64_t timeout; +}; + +#endif //SOLVITAIRE_COMMAND_LINE_HELPER_H diff --git a/solvitaire/src/main/input-output/input/json-parsing/deal_parser.cpp b/solvitaire/src/main/input-output/input/json-parsing/deal_parser.cpp new file mode 100644 index 0000000..8b8a36a --- /dev/null +++ b/solvitaire/src/main/input-output/input/json-parsing/deal_parser.cpp @@ -0,0 +1,290 @@ +// +// Created by thecharlesblake on 10/21/17. +// + +#include "deal_parser.h" +#include "../../../game/search-state/game_state.h" +#include "json_helper.h" +#include "../../../game/sol_rules.h" + +using namespace std; +using namespace rapidjson; + +typedef sol_rules::build_policy pol; +typedef sol_rules::stock_deal_type sdt; +typedef sol_rules::face_up_policy fu; +typedef sol_rules::foundations_init_type fit; + +void deal_parser::parse(game_state &gs, const rapidjson::Document& doc) { + // There are two stages to reading in the supplied deal. It is both put + // through the deal schema validator, and also parsed into + // the game state object (with some further checking done). The parsing is + // done first because the errors it detects tend to give clearer error + // messages than the schema validator + + // Construct tableau piles + if (gs.rules.tableau_pile_count > 0) { + parse_tableau_piles(gs, doc); + } + + // Construct hole card + if (gs.rules.hole) { + parse_hole(gs, doc); + } + + // Construct filled cells + if (gs.rules.cells) { + parse_cells(gs, doc); + } + + // Construct stock + if (gs.rules.stock_size > 0) { + parse_stock(gs, doc); + } + + // Construct waste + if (gs.rules.stock_deal_t == sdt::WASTE) { + parse_waste(gs, doc); + } + + // Construct reserve + if (gs.rules.reserve_size > 0) { + parse_reserve(gs, doc); + } + + // Construct sequences + if (gs.rules.sequence_count > 0) { + parse_sequences(gs, doc); + } + + // Construct accordion + if (gs.rules.accordion_size > 0) { + parse_accordion(gs, doc); + } + + // If the foundations begin with cards in them, fill them + if (gs.rules.foundations_present) { + bool supplied_foundations = parse_foundations(gs, doc); + + if (!supplied_foundations && gs.rules.foundations_init_cards == fit::ALL) { + fill_foundations(gs); + } + } + + Document d; + d.Parse(deal_schema_json().c_str()); + assert(!d.HasParseError()); + SchemaDocument sd(d); + SchemaValidator validator(sd); + if(!doc.Accept(validator)) { + throw runtime_error(json_helper::schema_err_str(validator)); + } +} + +string deal_parser::deal_schema_json() { + string schema_json = R"( +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "JSON Schema representing a solitaire game state to solve", + + "definitions": { + "card": {"type": "string", "pattern": "^(([0-9]|1[0-3]|a|A|j|J|q|Q|k|K)(c|C|d|D|h|H|s|S))$"}, + "cardarray": {"type": "array", "items": {"$ref": "#/definitions/card"}}, + "cardarraywithempty": { + "type": "array", + "items": { + "oneOf":[ + {"$ref": "#/definitions/card"}, + {"type": "string","enum": [""]} + ] + } + } + }, + + "type": "object", "properties": { + + "tableau piles": { + "type": "array", "items": {"$ref": "#/definitions/cardarray"} + }, + "foundations": {"$ref": "#/definitions/cardarray"}, + "sequences": { + "type": "array", "items": {"$ref": "#/definitions/cardarraywithempty"} + }, + "hole": {"$ref": "#/definitions/card"}, + "stock": {"$ref": "#/definitions/cardarray"}, + "waste": {"$ref": "#/definitions/cardarray"}, + "reserve": {"$ref": "#/definitions/cardarray"}, + "accordion": {"$ref": "#/definitions/cardarray"} + + }, "additionalProperties": false +} +)"; + return schema_json; +} + +void deal_parser::parse_tableau_piles(game_state &gs, const rapidjson::Document& doc) { + assert(doc.HasMember("tableau piles")); + const Value& json_tab_piles = doc["tableau piles"]; + assert(json_tab_piles.IsArray()); + + if (json_tab_piles.Size() != gs.rules.tableau_pile_count ) { + json_helper::json_parse_err("Incorrect number of tableau piles"); + } + + for (auto p = std::make_pair(begin(json_tab_piles.GetArray()), begin(gs.original_tableau_piles)); + p.second != end(gs.original_tableau_piles); + ++p.first, ++p.second) { + + for (auto& json_card : p.first->GetArray()) { + assert(json_card.IsString()); + gs.place_card(*p.second, card(json_card.GetString(), gs.rules.face_up != fu::ALL)); + } + } +} + +void deal_parser::parse_hole(game_state &gs, const Document& doc) { + if (doc.HasMember("hole")) { + const Value &json_hole = doc["hole"]; + assert(json_hole.IsString()); + + gs.place_card(gs.hole, card(json_hole.GetString())); + } +} + +void deal_parser::parse_cells(game_state &gs, const Document& doc) { + if (doc.HasMember("cells")) { + const Value &json_cells = doc["cells"]; + assert(json_cells.IsArray()); + + const auto json_cell_arr = json_cells.GetArray(); + + if (json_cell_arr.Empty()) return; + else if (json_cell_arr.Size() != gs.rules.cells) { + json_helper::json_parse_err("Incorrect number of cells"); + } + + for (auto p = std::make_pair(begin(json_cell_arr), begin(gs.original_cells)); + p.second != end(gs.original_cells); + ++p.first, ++p.second) { + + auto json_card = p.first; + assert(json_card->IsString()); + gs.place_card(*p.second, card(json_card->GetString())); + } + } +} + +void deal_parser::parse_stock(game_state &gs, const Document& doc) { + if (doc.HasMember("stock")) { + const Value &json_stock = doc["stock"]; + assert(json_stock.IsArray()); + + for (const Value& json_card : json_stock.GetArray()) { + assert(json_card.IsString()); + gs.place_card(gs.stock, card(json_card.GetString())); + } + } +} + +void deal_parser::parse_waste(game_state &gs, const Document& doc) { + if (doc.HasMember("waste")) { + const Value &json_waste = doc["waste"]; + assert(json_waste.IsArray()); + + for (const Value& json_card : json_waste.GetArray()) { + assert(json_card.IsString()); + gs.place_card(gs.waste, card(json_card.GetString())); + } + } +} + +void deal_parser::parse_reserve(game_state &gs, const Document& doc) { + assert(doc.HasMember("reserve")); + const Value& json_reserve_piles = doc["reserve"]; + assert(json_reserve_piles.IsArray()); + + const auto& json_card_arr = json_reserve_piles.GetArray(); + + // We treat a regular reserve like multiple single-card piles, + // but a stacked reserve as a single multiple-card pile + for (pile::ref i = 0; i < json_card_arr.Size(); i++) { + assert(json_card_arr[i].IsString()); + pile::ref pr = gs.original_reserve[0]; + if (!gs.rules.reserve_stacked) pr += i; + gs.place_card(pr, card(json_card_arr[i].GetString())); + } +} + +void deal_parser::parse_sequences(game_state& gs, const rapidjson::Document& doc) { + assert(doc.HasMember("sequences")); + const Value& json_seqs = doc["sequences"]; + assert(json_seqs.IsArray()); + + if (json_seqs.Size() != gs.rules.sequence_count ) { + json_helper::json_parse_err("Incorrect number of sequences"); + } + + for (auto p = std::make_pair(begin(json_seqs.GetArray()), begin(gs.sequences)); + p.second != end(gs.sequences); + ++p.first, ++p.second) { + + for (auto& json_card : p.first->GetArray()) { + assert(json_card.IsString()); + string card_str = json_card.GetString(); + card c = card_str.empty() ? "AS" : card(json_card.GetString()); + gs.place_card(*p.second, c); + } + } +} + +void deal_parser::parse_accordion(game_state &gs, const Document& doc) { + assert(doc.HasMember("accordion")); + const Value& json_accordion_piles = doc["accordion"]; + assert(json_accordion_piles.IsArray()); + + const auto& json_card_arr = json_accordion_piles.GetArray(); + + // We treat a regular reserve like multiple single-card piles, + // but a stacked reserve as a single multiple-card pile + if (json_card_arr.Size() != gs.rules.accordion_size) { + json_helper::json_parse_err("Incorrect accordion size"); + } + + auto acc_it = begin(gs.accordion); + for (pile::ref i = 0; i < json_card_arr.Size(); i++, acc_it++) { + assert(json_card_arr[i].IsString()); + pile::ref pr = *acc_it; + gs.place_card(pr, card(json_card_arr[i].GetString())); + } +} + +bool deal_parser::parse_foundations(game_state &gs, const rapidjson::Document& doc) { + if (!doc.HasMember("foundations")) return false; + + const Value& json_foundations = doc["foundations"]; + assert(json_foundations.IsArray()); + + card c; + for (auto j = begin(json_foundations.GetArray()); j != end(json_foundations.GetArray()); j++) { + assert(j->IsString()); + c = card(j->GetString()); + gs.place_card(gs.foundations[c.get_suit()], c); + } + + // If the game uses a random base for foundations, assume that the first card in the first foundation is that base + if (!gs.rules.foundations_base) { + auto& first_found = gs.piles[gs.foundations[c.get_suit()]]; + gs.foundations_base = first_found[first_found.size() - 1].get_rank(); + } + + return true; +} + +void deal_parser::fill_foundations(game_state &gs) { + auto foundations_count = uint8_t(4 * (gs.rules.two_decks ? 2:1)); + assert(gs.foundations.size() == foundations_count); + + for (uint8_t f_idx = 0; f_idx < foundations_count; f_idx++) { + gs.place_card(gs.foundations[f_idx], card(f_idx % uint8_t(4), 1)); + } +} diff --git a/solvitaire/src/main/input-output/input/json-parsing/deal_parser.h b/solvitaire/src/main/input-output/input/json-parsing/deal_parser.h new file mode 100644 index 0000000..36f58d5 --- /dev/null +++ b/solvitaire/src/main/input-output/input/json-parsing/deal_parser.h @@ -0,0 +1,33 @@ +// +// Created by thecharlesblake on 10/21/17. +// + +#ifndef SOLVITAIRE_DEAL_PARSER_H +#define SOLVITAIRE_DEAL_PARSER_H + +#include <vector> + +#include <boost/optional.hpp> + +#include "../../../../../lib/rapidjson/document.h" +#include "../../../../../lib/rapidjson/schema.h" + +class game_state; + +class deal_parser { +public: + static void parse(game_state&, const rapidjson::Document&); + static void parse_tableau_piles(game_state&, const rapidjson::Document&); + static void parse_hole(game_state&, const rapidjson::Document&); + static void parse_cells(game_state&, const rapidjson::Document&); + static void parse_stock(game_state&, const rapidjson::Document&); + static void parse_waste(game_state&, const rapidjson::Document&); + static void parse_reserve(game_state&, const rapidjson::Document&); + static void parse_sequences(game_state&, const rapidjson::Document&); + static void parse_accordion(game_state&, const rapidjson::Document&); + static bool parse_foundations(game_state&, const rapidjson::Document&); + static void fill_foundations(game_state&); + static std::string deal_schema_json(); +}; + +#endif //SOLVITAIRE_DEAL_PARSER_H diff --git a/solvitaire/src/main/input-output/input/json-parsing/json_helper.cpp b/solvitaire/src/main/input-output/input/json-parsing/json_helper.cpp new file mode 100644 index 0000000..3e6b99c --- /dev/null +++ b/solvitaire/src/main/input-output/input/json-parsing/json_helper.cpp @@ -0,0 +1,110 @@ +// +// Created by thecharlesblake on 11/13/17. +// + +#include <fstream> +#include <sstream> + +#include "json_helper.h" +#include "../../../../../lib/rapidjson/stringbuffer.h" +#include "../../output/log_helper.h" + +using namespace std; +using namespace rapidjson; + +using boost::property_tree::ptree; +using boost::property_tree::write_json; + +Document json_helper::get_file_json(const string& filename) { + // Reads the file into a string + std::ifstream ifstr(filename); + std::stringstream buf; + buf << ifstr.rdbuf(); + + if (ifstr.fail()) { + throw runtime_error("could not read file " + filename); + } else { + Document d; + + d.Parse(buf.str().c_str()); + if (d.HasParseError()) { + throw runtime_error(filename + " not valid json"); + } else { + return d; + } + } +} + +void json_helper::json_parse_err(const string& msg) { + string err_msg = "Error in JSON doc: " + msg; + LOG_DEBUG(err_msg); + throw runtime_error(err_msg); +} + +void json_helper::json_parse_warning(const string& msg) { + LOG_WARNING("Error in JSON doc: " + msg); +} + +const string json_helper::schema_err_str(const SchemaValidator& validator) { + string ret = "Input JSON failed to match the required schema. Schema Validator Error = "; + + StringBuffer sb; + validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); + ret += validator.GetInvalidSchemaKeyword(); + ret += ": "; + + sb.Clear(); + validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); + + ret += sb.GetString(); + return ret; +} + +void json_helper::print_game_state_as_json(const game_state& gs) { + ptree pt; + if (!gs.tableau_piles.empty()) pt.add_child("tableau piles", piles_to_ptree(gs, gs.tableau_piles)); + if (!gs.cells.empty()) pt.add_child("cells", piles_to_ptree(gs, gs.cells)); + if (!gs.reserve.empty()) pt.add_child("reserve", piles_to_ptree(gs, gs.reserve)); + if (!gs.foundations.empty()) pt.add_child("foundations", piles_to_ptree(gs, gs.foundations)); + if (!gs.sequences.empty()) pt.add_child("sequences", piles_to_ptree(gs, gs.sequences)); + if (!gs.accordion.empty()) pt.add_child("accordion", piles_to_ptree(gs, gs.accordion)); + if (gs.rules.stock_size > 0) { + pt.add_child("stock", pile_to_ptree(gs.piles[gs.stock])); + if (gs.rules.stock_deal_t == sol_rules::stock_deal_type::WASTE) { + pt.add_child("waste", pile_to_ptree(gs.piles[gs.waste])); + } + } + if (gs.rules.hole) pt.add_child("hole", pile_to_ptree(gs.piles[gs.hole])); + + write_json (cout, pt); +} + +ptree json_helper::piles_to_ptree(const game_state& gs, const std::list<pile::ref>& piles) { + ptree pt; + for (pile::ref pr : piles) { + pt.push_back(make_pair("", pile_to_ptree(gs.piles[pr]))); + } + return pt; +} + +ptree json_helper::piles_to_ptree(const game_state& gs, const std::vector<pile::ref>& piles) { + ptree pt; + for (pile::ref pr : piles) { + pt.push_back(make_pair("", pile_to_ptree(gs.piles[pr]))); + } + return pt; +} + +ptree json_helper::pile_to_ptree(const pile& pile) { + ptree pt; + for (pile::size_type i = pile.size(); i-->0; ) { + pt.push_back(make_pair("", card_to_ptree(pile[i]))); + } + return pt; +} + +ptree json_helper::card_to_ptree(const card& card) { + ptree pt; + pt.put("", card.to_string()); + return pt; +} diff --git a/solvitaire/src/main/input-output/input/json-parsing/json_helper.h b/solvitaire/src/main/input-output/input/json-parsing/json_helper.h new file mode 100644 index 0000000..460911f --- /dev/null +++ b/solvitaire/src/main/input-output/input/json-parsing/json_helper.h @@ -0,0 +1,31 @@ +// +// Created by thecharlesblake on 11/13/17. +// + +#ifndef SOLVITAIRE_UTIL_H +#define SOLVITAIRE_UTIL_H + +#include <string> + +#include <boost/property_tree/ptree.hpp> +#include <boost/property_tree/json_parser.hpp> + +#include "../../../../../lib/rapidjson/schema.h" +#include "../../../game/search-state/game_state.h" + +class json_helper { +public: + static rapidjson::Document get_file_json(const std::string&); + static void json_parse_warning(const std::string& msg); + static void json_parse_err(const std::string& msg); + static const std::string schema_err_str(const rapidjson::SchemaValidator&); + static void print_game_state_as_json(const game_state&); +private: + static boost::property_tree::ptree piles_to_ptree(const game_state&, const std::list<pile::ref>&); + static boost::property_tree::ptree piles_to_ptree(const game_state&, const std::vector<pile::ref>&); + static boost::property_tree::ptree pile_to_ptree(const pile&); + static boost::property_tree::ptree card_to_ptree(const card&); +}; + + +#endif //SOLVITAIRE_UTIL_H diff --git a/solvitaire/src/main/input-output/input/json-parsing/rules_parser.cpp b/solvitaire/src/main/input-output/input/json-parsing/rules_parser.cpp new file mode 100644 index 0000000..7c49577 --- /dev/null +++ b/solvitaire/src/main/input-output/input/json-parsing/rules_parser.cpp @@ -0,0 +1,746 @@ +// +// Created by thecharlesblake on 1/3/18. +// + +#include <vector> +#include <algorithm> + +#include "../../../../../lib/rapidjson/error/en.h" + +#include "rules_parser.h" +#include "json_helper.h" +#include "../sol_preset_types.h" +#include "../../../game/card.h" +#include "../../../game/sol_rules.h" + +using namespace std; +using namespace rapidjson; + +//////////// +// Static // +//////////// + +typedef sol_rules::build_policy pol; +typedef sol_rules::spaces_policy s_pol; +typedef sol_rules::accordion_policy acc_pol; +typedef sol_rules::stock_deal_type sdt; +typedef sol_rules::face_up_policy fu; +typedef sol_rules::direction dir; +typedef sol_rules::built_group_type bgt; +typedef sol_rules::foundations_init_type fit; + +const sol_rules rules_parser::from_file(const string rules_file) { + sol_rules sr = get_default(); + Document d = json_helper::get_file_json(rules_file); + + modify_sol_rules(sr, d); + + return sr; +} + +const sol_rules rules_parser::from_preset(const string sol_type) { + sol_rules sr = get_default(); + + const string preset_json = sol_preset_types::get(sol_type); + + Document d; + d.Parse(preset_json.c_str()); + assert(!d.HasParseError()); + + modify_sol_rules(sr, d); + return sr; +} + +sol_rules rules_parser::get_default() { + sol_rules sr; + const string default_json = sol_preset_types::get("default"); + + Document d; + d.Parse(default_json.c_str()); + assert(!d.HasParseError()); + + modify_sol_rules(sr, d); + return sr; +} + +void rules_parser::modify_sol_rules(sol_rules& sr, Document& d) { + // There are two stages to reading in a rules document. It is both put + // through the rule schema validator, and also parsed into + // the game rules object (with some further checking done). The parsing is + // done first because the errors it detects tend to give clearer error + // messages than the schema validator + + if (!d.IsObject()) { + json_helper::json_parse_err("JSON doc must be object"); + } + + if (d.HasMember("tableau piles")) { + if (d["tableau piles"].IsObject()) { + + if (d["tableau piles"].HasMember("count")) { + if (d["tableau piles"]["count"].IsInt()) { + sr.tableau_pile_count = static_cast<uint8_t>(d["tableau piles"]["count"].GetInt()); + if (sr.tableau_pile_count > 52) { + json_helper::json_parse_warning("[tableau piles][count] may be too high"); + } + } else { + json_helper::json_parse_err("[tableau piles][count] must be an integer"); + } + } + + if (d["tableau piles"].HasMember("build policy")) { + if (d["tableau piles"]["build policy"].IsString()) { + string bp_str = d["tableau piles"]["build policy"].GetString(); + + if (bp_str == "any-suit") { + sr.build_pol = pol::ANY_SUIT; + } else if (bp_str == "red-black") { + sr.build_pol = pol::RED_BLACK; + } else if (bp_str == "same-suit") { + sr.build_pol = pol::SAME_SUIT; + } else if (bp_str == "no-build") { + sr.build_pol = pol::NO_BUILD; + } else { + json_helper::json_parse_err("[tableau piles][build policy] is invalid"); + } + + } else { + json_helper::json_parse_err("[tableau piles][build policy] must be an string"); + } + } + + if (d["tableau piles"].HasMember("spaces policy")) { + if (d["tableau piles"]["spaces policy"].IsString()) { + string sp_str = d["tableau piles"]["spaces policy"].GetString(); + + if (sp_str == "any") { + sr.spaces_pol = s_pol::ANY; + } else if (sp_str == "no-build") { + sr.spaces_pol = s_pol::NO_BUILD; + } else if (sp_str == "kings") { + sr.spaces_pol = s_pol::KINGS; + } else if (sp_str == "auto-reserve-then-waste") { + sr.spaces_pol = s_pol::AUTO_RESERVE_THEN_WASTE; + } else if (sp_str == "auto-waste-then-stock") { + sr.spaces_pol = s_pol::AUTO_WASTE_THEN_STOCK; + } else { + json_helper::json_parse_err("[tableau piles][spaces policy] is invalid"); + } + + } else { + json_helper::json_parse_err("[tableau piles][spaces policy] must be a string"); + } + } + + if (d["tableau piles"].HasMember("move built group")) { + if (d["tableau piles"]["move built group"].IsString()) { + string mbg_str = d["tableau piles"]["move built group"].GetString(); + + if (mbg_str == "yes") { + sr.move_built_group = bgt::YES; + } else if (mbg_str == "no") { + sr.move_built_group = bgt::NO; + } else if (mbg_str == "whole-pile") { + sr.move_built_group = bgt::WHOLE_PILE; + } else if (mbg_str == "maximal-group") { + sr.move_built_group = bgt::MAXIMAL_GROUP; + } else { + json_helper::json_parse_err("[tableau piles][move built group] is invalid"); + } + } else { + json_helper::json_parse_err("[tableau piles][move built group] must be a string"); + } + } + + string mbgp_str; + if (d["tableau piles"].HasMember("move built group policy")) { + if (d["tableau piles"]["move built group policy"].IsString()) { + mbgp_str = d["tableau piles"]["move built group policy"].GetString(); + } else { + json_helper::json_parse_err("[tableau piles][move built group policy] must be a string"); + } + } else { + mbgp_str = "same-as-build"; + } + if (mbgp_str == "same-as-build") { + sr.built_group_pol = sr.build_pol; + } else if (mbgp_str == "any-suit") { + sr.built_group_pol = pol::ANY_SUIT; + } else if (mbgp_str == "red-black") { + sr.built_group_pol = pol::RED_BLACK; + } else if (mbgp_str == "same-suit") { + sr.built_group_pol = pol::SAME_SUIT; + } else if (mbgp_str == "no-build") { + sr.built_group_pol = pol::NO_BUILD; + } else { + json_helper::json_parse_err("[tableau piles][move built group policy] is invalid"); + } + + if (d["tableau piles"].HasMember("diagonal deal")) { + if (d["tableau piles"]["diagonal deal"].IsBool()) { + sr.diagonal_deal = d["tableau piles"]["diagonal deal"].GetBool(); + } else { + json_helper::json_parse_err("[tableau piles][diagonal deal] must be a boolean"); + } + } + + string face_up_str; + if (d["tableau piles"].HasMember("face up cards")) { + if (d["tableau piles"]["face up cards"].IsString()) { + face_up_str = d["tableau piles"]["face up cards"].GetString(); + + if (face_up_str == "all") { + sr.face_up = fu::ALL; + } else if (face_up_str == "top") { + sr.face_up = fu::TOP_CARDS; + } else { + string err = "[tableau piles][face up cards] is invalid: " + face_up_str; + json_helper::json_parse_err(err); + } + + } else { + json_helper::json_parse_err("[tableau piles][face up cards] must be a string"); + } + } + + } else { + json_helper::json_parse_err("[tableau piles] must be an object"); + } + } + + if (d.HasMember("foundations")) { + if (d["foundations"].IsObject()) { + if (d["foundations"].HasMember("present")) { + if (d["foundations"]["present"].IsBool()) { + sr.foundations_present = d["foundations"]["present"].GetBool(); + } else { + json_helper::json_parse_err("[foundations][present] must be a boolean"); + } + } + + if (d["foundations"].HasMember("initial cards")) { + if (d["foundations"]["initial cards"].IsString()) { + string ic_str = d["foundations"]["initial cards"].GetString(); + + if (ic_str == "none") { + sr.foundations_init_cards = fit::NONE; + } else if (ic_str == "one") { + sr.foundations_init_cards = fit::ONE; + } else if (ic_str == "all") { + sr.foundations_init_cards = fit::ALL; + } else { + string err = "[foundations][initial cards] is invalid: " + ic_str; + json_helper::json_parse_err(err); + } + } else { + json_helper::json_parse_err("[foundations][initial cards] must be a string"); + } + } + + if (d["foundations"].HasMember("base card")) { + if (d["foundations"]["base card"].IsString()) { + string base_card_str = d["foundations"]["base card"].GetString(); + + if (base_card_str == "random") { + sr.foundations_base = boost::none; + } else { + base_card_str += "H"; + sr.foundations_base = card(base_card_str.c_str()).get_rank(); + } + } else { + json_helper::json_parse_err("[foundations][base card] must be a string"); + } + } + + if (d["foundations"].HasMember("removable")) { + if (d["foundations"]["removable"].IsBool()) { + sr.foundations_removable = d["foundations"]["removable"].GetBool(); + } else { + json_helper::json_parse_err("[foundations][removable] must be a boolean"); + } + } + + if (d["foundations"].HasMember("complete piles")) { + if (d["foundations"]["complete piles"].IsBool()) { + sr.foundations_only_comp_piles = d["foundations"]["complete piles"].GetBool(); + } else { + json_helper::json_parse_err("[foundations][complete piles] must be a boolean"); + } + } + + } else { + json_helper::json_parse_err("[foundations] must be an object"); + } + } + + if (d.HasMember("hole")) { + if (d["hole"].IsBool()) { + sr.hole = d["hole"].GetBool(); + } else { + json_helper::json_parse_err("[hole] must be a boolean"); + } + } + + if (d.HasMember("cells")) { + if (d["cells"].IsObject()) { + if (d["cells"].HasMember("count")) { + if (d["cells"]["count"].IsInt()) { + sr.cells = static_cast<uint8_t>(d["cells"]["count"].GetInt()); + } else { + json_helper::json_parse_err("[cells][count] must be an integer"); + } + } + + if (d["cells"].HasMember("pre-filled")) { + if (d["cells"]["pre-filled"].IsInt()) { + sr.cells_pre_filled = static_cast<uint8_t>(d["cells"]["pre-filled"].GetInt()); + } else { + json_helper::json_parse_err("[cells][pre-filled] must be an integer"); + } + } + } else { + json_helper::json_parse_err("[cells] must be an object"); + } + } + + if (d.HasMember("stock")) { + if (d["stock"].IsObject()) { + if (d["stock"].HasMember("size")) { + if (d["stock"]["size"].IsInt()) { + sr.stock_size = static_cast<uint8_t>(d["stock"]["size"].GetInt()); + } else { + json_helper::json_parse_err("[stock][size] must be an integer"); + } + } + + if (d["stock"].HasMember("deal type")) { + if (d["stock"]["deal type"].IsString()) { + if(string(d["stock"]["deal type"].GetString()) == "waste") { + sr.stock_deal_t = sdt::WASTE; + } else { + sr.stock_deal_t = sdt::TABLEAU_PILES; + } + } else { + json_helper::json_parse_err("[stock][deal type] must be a string"); + } + } + + if (d["stock"].HasMember("deal count")) { + if (d["stock"]["deal count"].IsInt()) { + sr.stock_deal_count = static_cast<uint8_t>(d["stock"]["deal count"].GetInt()); + } else { + json_helper::json_parse_err("[stock][deal count] must be an integer"); + } + } + + if (d["stock"].HasMember("redeal")) { + if (d["stock"]["redeal"].IsBool()) { + sr.stock_redeal = static_cast<uint8_t>(d["stock"]["redeal"].GetBool()); + } else { + json_helper::json_parse_err("[stock][redeal] must be a boolean"); + } + } + } else { + json_helper::json_parse_err("[stock] must be an object"); + } + } + + if (d.HasMember("reserve")) { + if (d["reserve"].IsObject()) { + if (d["reserve"].HasMember("size")) { + if (d["reserve"]["size"].IsInt()) { + sr.reserve_size = static_cast<uint8_t>(d["reserve"]["size"].GetInt()); + } else { + json_helper::json_parse_err("[size] must be an integer"); + } + } + + if (d["reserve"].HasMember("stacked")) { + if (d["reserve"]["stacked"].IsBool()) { + sr.reserve_stacked = d["reserve"]["stacked"].GetBool(); + } else { + json_helper::json_parse_err("[stacked] must be a boolean"); + } + } + } else { + json_helper::json_parse_err("[reserve] must be an object"); + } + } + + if (d.HasMember("accordion")) { + if (d["accordion"].IsObject()) { + if (d["accordion"].HasMember("size")) { + if (d["accordion"]["size"].IsInt()) { + sr.accordion_size = static_cast<uint8_t>(d["accordion"]["size"].GetInt()); + } else { + json_helper::json_parse_err("[size] must be an integer"); + } + } + + if (d["accordion"].HasMember("moves")) { + if (d["accordion"]["moves"].IsArray()) { + for (auto& json_move : d["accordion"]["moves"].GetArray()) { + string move_str = json_move.GetString(); + + sol_rules::direction move_dir; + if (move_str[0] == 'L') { + move_dir = sol_rules::direction::LEFT; + } else if (move_str[0] == 'R') { + move_dir = sol_rules::direction::RIGHT; + } else { + json_helper::json_parse_err(R"([accordion][moves] must begin 'L' or 'R')"); + } + + auto count_str = move_str.substr(1, move_str.size() - 1); + auto count = static_cast<uint8_t>(stoi(count_str)); + + sr.accordion_moves.emplace_back(move_dir, count); + } + } else { + json_helper::json_parse_err("[accordion][moves] must be an array"); + } + } + + if (d["accordion"].HasMember("build policies")) { + if (d["accordion"]["build policies"].IsArray()) { + for (auto& json_policy : d["accordion"]["build policies"].GetArray()) { + string policy_str = json_policy.GetString(); + + if (policy_str == "any-suit") { + sr.accordion_pol.emplace_back(acc_pol::ANY_SUIT); + } else if (policy_str == "red-black") { + sr.accordion_pol.emplace_back(acc_pol::RED_BLACK); + } else if (policy_str == "same-suit") { + sr.accordion_pol.emplace_back(acc_pol::SAME_SUIT); + } else if (policy_str == "same-rank") { + sr.accordion_pol.emplace_back(acc_pol::SAME_RANK); + } else { + json_helper::json_parse_err("[accordion][build policies] is invalid"); + } + } + } else { + json_helper::json_parse_err("[accordion][build policies] must be an array"); + } + } + } else { + json_helper::json_parse_err("[accordion] must be an object"); + } + } + + if (d.HasMember("sequences")) { + if (d["sequences"].IsObject()) { + if (d["sequences"].HasMember("count")) { + if (d["sequences"]["count"].IsInt()) { + sr.sequence_count = static_cast<uint8_t>(d["sequences"]["count"].GetInt()); + } else { + json_helper::json_parse_err("[count] must be an integer"); + } + } + + if (d["sequences"].HasMember("build policy")) { + if (d["sequences"]["build policy"].IsString()) { + string bp_str = d["sequences"]["build policy"].GetString(); + + if (bp_str == "any-suit") { + sr.sequence_build_pol = pol::ANY_SUIT; + } else if (bp_str == "red-black") { + sr.sequence_build_pol = pol::RED_BLACK; + } else if (bp_str == "same-suit") { + sr.sequence_build_pol = pol::SAME_SUIT; + } else { + json_helper::json_parse_err("[sequences][build policy] is invalid"); + } + } else { + json_helper::json_parse_err("[sequences][build policy] must be an string"); + } + } + + if (d["sequences"].HasMember("fixed suit")) { + if (d["sequences"]["fixed suit"].IsBool()) { + sr.sequence_fixed_suit = d["sequences"]["fixed suit"].GetBool(); + } else { + json_helper::json_parse_err("[fixed suit] must be a boolean"); + } + } + + if (d["sequences"].HasMember("direction")) { + if (d["sequences"]["direction"].IsString()) { + string dir_str = d["sequences"]["direction"].GetString(); + + if (dir_str == "L") { + sr.sequence_direction = dir::LEFT; + } else if (dir_str == "R") { + sr.sequence_direction = dir::RIGHT; + } else if (dir_str == "LR") { + sr.sequence_direction = dir::BOTH; + } else { + json_helper::json_parse_err("[sequences][direction] is invalid"); + } + } else { + json_helper::json_parse_err("[sequences][direction] must be an string"); + } + } + } else { + json_helper::json_parse_err("[sequences] must be an object"); + } + } + + if (d.HasMember("max rank")) { + if (d["max rank"].IsInt()) { + sr.max_rank = static_cast<card::rank_t>(d["max rank"].GetInt()); + if (sr.max_rank > 13) { + json_helper::json_parse_err("[max rank] must be a valid rank"); + } + } else { + json_helper::json_parse_err("[max rank] must be an integer"); + } + } + + if (d.HasMember("two decks")) { + if (d["two decks"].IsBool()) { + sr.two_decks = d["two decks"].GetBool(); + } else { + json_helper::json_parse_err("[two decks] must be a boolean"); + } + } + + int solution_types = 0; + if (sr.hole) solution_types++; + if (sr.foundations_present) solution_types++; + if (sr.sequence_count > 0) solution_types++; + if (sr.accordion_size > 0) solution_types++; + if (solution_types != 1) { + json_helper::json_parse_err("one and only one of [hole], [foundations], [accordion][size] > 0 and [sequences][count] > 0 " + "must be true"); + } + + Document vd; + vd.Parse(rules_schema_json().c_str()); + assert(!vd.HasParseError()); + SchemaDocument sd(vd); + SchemaValidator validator(sd); + if(!d.Accept(validator)) { + throw runtime_error(json_helper::schema_err_str(validator)); + } +} + +string rules_parser::rules_schema_json() { + string schema_json = R"( +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "JSON Schema representing a generic solitaire game", + "type": "object", + "properties": { + "tableau piles": { + "type": "object", + "properties": { + "count": { + "type": "integer", + "minimum": 0 + }, + "build policy": { + "type": "string", + "enum": [ + "any-suit", + "red-black", + "same-suit", + "no-build" + ] + }, + "spaces policy": { + "type": "string", + "enum": [ + "any", + "no-build", + "kings", + "auto-reserve-then-waste", + "auto-waste-then-stock" + ] + }, + "diagonal deal": { + "type": "boolean" + }, + "move built group": { + "type": "string", + "enum": [ + "yes", + "no", + "whole-pile", + "maximal-group" + ] + }, + "move built group policy": { + "type": "string", + "enum": [ + "same-as-build", + "any-suit", + "red-black", + "same-suit", + "no-build" + ] + }, + "face up cards": { + "type": "string", + "enum": [ + "all", + "top" + ] + } + }, + "additionalProperties": false + }, + "foundations": { + "type": "object", + "properties": { + "present": { + "type": "boolean" + }, + "initial cards": { + "type": "string", + "enum": [ + "none", + "one", + "all" + ] + }, + "base card": { + "type": "string", + "oneOf":[ + {"pattern": "^(([0-9]|1[0-3]|a|A|j|J|q|Q|k|K))$"}, + {"enum": ["random"]} + ] + }, + "removable": { + "type": "boolean" + }, + "only complete pile moves": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "hole": { + "type": "boolean" + }, + "cells": { + "type": "object", + "properties": { + "count": { + "type": "integer", + "minimum": 0 + }, + "pre-filled": { + "type": "integer", + "minimum": 0 + } + }, + "additionalProperties": false + }, + "stock": { + "type": "object", + "properties": { + "size": { + "type": "integer", + "minimum": 0 + }, + "deal type": { + "type": "string", + "enum": [ + "waste", + "tableau piles" + ] + }, + "deal count": { + "type": "integer", + "minimum": 1 + }, + "redeal": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "reserve": { + "type": "object", + "properties": { + "size": { + "type": "integer", + "minimum": 0 + }, + "stacked": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "accordion": { + "type": "object", + "properties": { + "size": { + "type": "integer", + "minimum": 0 + }, + "moves": { + "items": { + "type": "string", + "pattern": "^((L|R)([1-9]|[1-4][0-9]|5[0-2]))$" + } + }, + "build policies": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "same-suit", + "red-black", + "any-suit", + "same-rank" + ] + } + } + }, + "additionalProperties": false + }, + "sequences": { + "type": "object", + "properties": { + "count": { + "type": "integer", + "minimum": 0 + }, + "direction": { + "type": "string", + "enum": [ + "L", + "R", + "LR" + ] + }, + "fixed suit": { + "type": "boolean" + }, + "build policy": { + "type": "string", + "enum": [ + "any-suit", + "red-black", + "same-suit" + ] + } + }, + "additionalProperties": false + }, + "max rank": { + "type": "integer", + "minimum": 1, + "maximum": 13 + }, + "two decks": { + "type": "boolean" + } + }, + "additionalProperties": false +} +)"; + return schema_json; +} diff --git a/solvitaire/src/main/input-output/input/json-parsing/rules_parser.h b/solvitaire/src/main/input-output/input/json-parsing/rules_parser.h new file mode 100644 index 0000000..fdfe018 --- /dev/null +++ b/solvitaire/src/main/input-output/input/json-parsing/rules_parser.h @@ -0,0 +1,22 @@ +// +// Created by thecharlesblake on 1/3/18. +// + +#ifndef SOLVITAIRE_RULES_PARSER_H +#define SOLVITAIRE_RULES_PARSER_H + +#include "../../../game/sol_rules.h" + +class rules_parser { +public: + static const sol_rules from_file(std::string); + static const sol_rules from_preset(std::string); + static std::string rules_schema_json(); + +private: + static sol_rules get_default(); + static void modify_sol_rules(sol_rules&, rapidjson::Document&); +}; + + +#endif //SOLVITAIRE_RULES_PARSER_H diff --git a/solvitaire/src/main/input-output/input/sol_preset_types.cpp b/solvitaire/src/main/input-output/input/sol_preset_types.cpp new file mode 100644 index 0000000..b169370 --- /dev/null +++ b/solvitaire/src/main/input-output/input/sol_preset_types.cpp @@ -0,0 +1,1630 @@ +// +// Created by thecharlesblake on 11/14/17. +// + +#include <iostream> +#include "sol_preset_types.h" +using namespace std; + +string sol_preset_types::get(const string& s) { + return mp[s]; +} + +bool sol_preset_types::is_valid_preset(const string& s) { + return mp.count(s) > 0; +} + +map<string, string> sol_preset_types::mp = { + { + "default", + + R"( +{ + "tableau piles": { + "count": 8, + "build policy": "any-suit", + "spaces policy": "any", + "diagonal deal": false, + "move built group": "no", + "move built group policy": "same-as-build", + "face up cards": "all" + }, + "foundations": { + "present": true, + "initial cards": "none", + "base card": "A", + "removable": false, + "only complete pile moves": false + }, + "hole": false, + "cells": { + "count": 0 + }, + "stock": { + "size": 0, + "deal type": "waste", + "deal count": 1, + "redeal": false + }, + "reserve": { + "size": 0, + "stacked": false + }, + "accordion": { + "size": 0, + "moves": [], + "build policies": [] + }, + "sequences": { + "count": 0, + "direction": "L", + "build policy": "same-suit", + "fixed suit": false + }, + "max rank": 13, + "two decks": false +} +)" + + }, + { + "spanish-patience", + + R"( +{ + "tableau piles": { + "count": 13 + }, + "foundations": { + "removable": true + } +} +)" + + }, + { + "simple-spanish-patience", + + R"( +{ + "tableau piles": { + "count": 3 + }, + "foundations": { + "removable": true + }, + "max rank": 2 +} +)" + + }, + { + "free-cell", + + R"( +{ + "tableau piles": { + "build policy": "red-black" + }, + "cells": { + "count": 4 + } +} +)" + + }, + { + "simple-free-cell", + + R"( +{ + "tableau piles": { + "count": 4, + "build policy": "red-black" + }, + "cells": { + "count": 1 + }, + "max rank": 4 +} +)" + + }, + { + "bakers-dozen", + + R"( +{ + "tableau piles": { + "count": 13, + "spaces policy": "no-build" + }, + "foundations": { + "removable": true + } +} +)" + + }, + { + "simple-bakers-dozen", + + R"( +{ + "tableau piles": { + "count": 3, + "spaces policy": "no-build" + }, + "foundations": { + "removable": true + }, + "max rank": 3 +} +)" + + }, + { + "black-hole", + + R"( +{ + "tableau piles": { + "count": 17, + "build policy": "no-build" + }, + "foundations": { + "present": false + }, + "hole": true +} +)" + + }, + { + "simple-black-hole", + + R"( +{ + "tableau piles": { + "count": 4, + "build policy": "no-build" + }, + "foundations": { + "present": false + }, + "hole": true, + "max rank": 5 +} +)" + + }, + { + "fortunes-favor", + + R"( +{ + "tableau piles": { + "count": 12, + "build policy": "same-suit", + "spaces policy": "auto-waste-then-stock" + }, + "foundations": { + "initial cards": "all" + }, + "stock": { + "size": 36 + } +} +)" + + }, + { + "simple-fortunes-favor", + + R"( +{ + "tableau piles": { + "count": 3, + "build policy": "same-suit" + }, + "foundations": { + "initial cards": "all" + }, + "stock": { + "size": 3 + }, + "max rank": 4 +} +)" + + }, + { + "flower-garden", + + R"( +{ + "tableau piles": { + "count": 6 + }, + "reserve": { + "size": 16 + }, + "foundations": { + "removable": true + } +} +)" + + }, + { + "simple-flower-garden", + + R"( +{ + "tableau piles": { + "count": 3 + }, + "reserve": { + "size": 3 + }, + "foundations": { + "removable": true + }, + "max rank": 3 +} +)" + + }, + { + "canfield", + + R"( +{ + "tableau piles": { + "count": 4, + "build policy": "red-black", + "move built group": "whole-pile", + "spaces policy": "auto-reserve-then-waste" + }, + "foundations": { + "initial cards": "one", + "base card": "random" + }, + "stock": { + "size": 34, + "deal count": 3, + "redeal": true + }, + "reserve": { + "size": 13, + "stacked": true + } +} +)" + + }, + { + "simple-canfield", + + R"( +{ + "tableau piles": { + "count": 3, + "build policy": "red-black", + "move built group": "whole-pile", + "spaces policy": "auto-reserve-then-waste" + }, + "foundations": { + "initial cards": "one", + "base card": "random" + }, + "stock": { + "size": 6, + "deal count": 3, + "redeal": true + }, + "reserve": { + "size": 2, + "stacked": true + }, + "max rank": 3 +} +)" + + }, + { + "somerset", + + R"( +{ + "tableau piles": { + "count": 10, + "build policy": "red-black", + "diagonal deal": true + }, + "foundations": { + "removable": true + } +} +)" + + }, + { + "simple-somerset", + + R"( +{ + "tableau piles": { + "count": 4, + "build policy": "red-black", + "diagonal deal": true + }, + "foundations": { + "removable": true + }, + "max rank": 2 +} +)" + + }, + { + "alpha-star", + + R"( +{ + "tableau piles": { + "count": 12, + "build policy": "same-suit", + "move built group": "yes" + }, + "foundations": { + "initial cards": "all" + } +} +)" + + }, + { + "simple-alpha-star", + + R"( +{ + "tableau piles": { + "count": 3, + "build policy": "same-suit", + "move built group": "yes" + }, + "foundations": { + "initial cards": "all" + }, + "max rank": 6 +} +)" + + }, + { + "spider", + + R"( +{ + "tableau piles": { + "count": 10, + "build policy": "any-suit", + "move built group": "yes", + "move built group policy": "same-suit", + "face up cards": "top" + }, + "foundations": { + "only complete pile moves": true + }, + "stock": { + "size": 50, + "deal type": "tableau piles" + }, + "two decks": true +} +)" + + }, + { + "simple-spider", + + R"( +{ + "tableau piles": { + "count": 4, + "build policy": "any-suit", + "move built group": "yes", + "move built group policy": "same-suit", + "face up cards": "top" + }, + "foundations": { + "only complete pile moves": true + }, + "stock": { + "size": 12, + "deal type": "tableau piles" + }, + "two decks": true, + "max rank": 3 +} +)" + + }, + + { + "simple-klondike", + + R"( +{ + "tableau piles": { + "count": 4, + "build policy": "red-black", + "move built group": "yes", + "diagonal deal": true, + "face up cards": "top" + }, + "stock": { + "size": 6, + "deal count": 3, + "redeal": true + }, + "max rank": 4 +} +)" + }, + // --- END OF 'CANONICAL' GAMES --- + + { + "raglan", + + R"( +{ + "tableau piles": { + "count": 9, + "build policy": "red-black", + "diagonal deal": true + }, + "reserve": { + "size": 6 + }, + "foundations": { + "removable": true, + "initial cards": "all" + } +} +)" + + }, + + { + "klondike-deal-1", + + R"( +{ + "tableau piles": { + "count": 7, + "build policy": "red-black", + "spaces policy": "kings", + "move built group": "yes", + "diagonal deal": true, + "face up cards": "top" + }, + "foundations": { + "removable": true + }, + "stock": { + "size": 24, + "deal count": 1, + "redeal": true + } +} +)" + + }, + + { + "klondike", + + R"( +{ + "tableau piles": { + "count": 7, + "build policy": "red-black", + "spaces policy": "kings", + "move built group": "yes", + "diagonal deal": true, + "face up cards": "top" + }, + "foundations": { + "removable": true + }, + "stock": { + "size": 24, + "deal count": 3, + "redeal": true + } +} +)" + + }, + { + "alina", + + R"( +{ + "tableau piles": { + "count": 13, + "build policy": "any-suit", + "spaces policy": "no-build" + }, + "foundations": { + "removable": true + }, + "cells": { + "count": 1 + } +} +)" + + }, + { + "castles-of-spain", + + R"( +{ + "tableau piles": { + "count": 13, + "build policy": "red-black" + }, + "foundations": { + "removable": true + } +} +)" + + }, + { + "delta-star", + + R"( +{ + "tableau piles": { + "count": 12, + "build policy": "same-suit" + }, + "foundations": { + "initial cards": "all" + } +} +)" + + }, + { + "martha", + + R"( +{ + "tableau piles": { + "count": 12, + "build policy": "red-black" + }, + "foundations": { + "initial cards": "all", + "removable": true + } +} +)" + + }, + { + "one-cell", + + R"( +{ + "tableau piles": { + "count": 13, + "build policy": "red-black" + }, + "foundations": { + "initial cards": "all", + "removable": true + }, + "cells": { + "count": 1 + } +} +)" + + }, + { + "two-cell", + + R"( +{ + "tableau piles": { + "count": 13, + "build policy": "red-black" + }, + "foundations": { + "initial cards": "all", + "removable": true + }, + "cells": { + "count": 2 + } +} +)" + + }, + { + "free-cell-3-cell", + + R"( +{ + "tableau piles": { + "build policy": "red-black" + }, + "cells": { + "count": 3 + } +} +)" + + }, + { + "free-cell-2-cell", + + R"( +{ + "tableau piles": { + "build policy": "red-black" + }, + "cells": { + "count": 2 + } +} +)" + + }, + { + "free-cell-1-cell", + + R"( +{ + "tableau piles": { + "build policy": "red-black" + }, + "cells": { + "count": 1 + } +} +)" + + }, + { + "free-cell-0-cell", + + R"( +{ + "tableau piles": { + "build policy": "red-black" + } +} +)" + + }, + { + "free-cell-7-pile", + + R"( +{ + "tableau piles": { + "count": 7, + "build policy": "red-black" + }, + "cells": { + "count": 4 + } +} +)" + + }, + { + "free-cell-6-pile", + + R"( +{ + "tableau piles": { + "count": 6, + "build policy": "red-black" + }, + "cells": { + "count": 4 + } +} +)" + + }, + { + "free-cell-5-pile", + + R"( +{ + "tableau piles": { + "count": 5, + "build policy": "red-black" + }, + "cells": { + "count": 4 + } +} +)" + + }, + { + "free-cell-4-pile", + + R"( +{ + "tableau piles": { + "count": 4, + "build policy": "red-black" + }, + "cells": { + "count": 4 + } +} +)" + + }, + { + "bakers-game", + + R"( +{ + "tableau piles": { + "build policy": "same-suit" + }, + "cells": { + "count": 4 + } +} +)" + + }, + { + "eight-off", + + R"( +{ + "tableau piles": { + "build policy": "same-suit", + "spaces policy": "kings" + }, + "cells": { + "count": 8, + "pre-filled": 4 + } +} +)" + + }, + { + "eight-off-any-card-spaces", + + R"( +{ + "tableau piles": { + "build policy": "same-suit" + }, + "cells": { + "count": 8 + } +} +)" + + }, + { + "fore-cell", + + R"( +{ + "tableau piles": { + "build policy": "red-black", + "spaces policy": "kings" + }, + "cells": { + "count": 4, + "pre-filled": 4 + } +} +)" + + }, + { + "fore-cell-same-suit", + + R"( +{ + "tableau piles": { + "build policy": "same-suit", + "spaces policy": "kings" + }, + "cells": { + "count": 4, + "pre-filled": 4 + } +} +)" + + }, + { + "penguin", + R"( + +{ + "tableau piles": { + "count": 7, + "build policy": "same-suit", + "move built group": "yes", + "spaces policy": "kings" + }, + "cells": { + "count": 7 + }, + "foundations": { + "initial cards": "all" + } +} +)" + + }, + { + "sea-towers", + R"( + +{ + "tableau piles": { + "count": 10, + "build policy": "same-suit", + "move built group": "yes", + "spaces policy": "kings" + }, + "cells": { + "count": 4 + } +} +)" + + }, + { + "duchess", + R"( + +{ + "tableau piles": { + "count": 4, + "build policy": "red-black", + "move built group": "yes" + }, + "foundations": { + "initial cards": "all" + }, + "reserve": { + "size": 12 + }, + "stock": { + "size": 36 + } +} +)" + + }, + { + "chameleon", + R"( + +{ + "tableau piles": { + "count": 3, + "build policy": "any-suit", + "move built group": "yes" + }, + "reserve": { + "size": 13, + "stacked": true + }, + "stock": { + "size": 36 + } +} +)" + + }, + { + "fan", + R"( + +{ + "tableau piles": { + "count": 18, + "build policy": "same-suit", + "spaces policy": "kings" + }, + "foundations": { + "removable": true + } +} +)" + + }, + { + "scotch-patience", + R"( + +{ + "tableau piles": { + "count": 18, + "build policy": "red-black", + "spaces policy": "no-build" + }, + "foundations": { + "removable": true + } +} +)" + + }, + { + "blind-alleys", + R"( + +{ + "tableau piles": { + "count": 6, + "build policy": "red-black", + "move built group": "yes" + }, + "foundations": { + "initial cards": "all", + "removable": true + }, + "stock": { + "size": 30 + } +} +)" + + }, + { + "east-haven", + R"( + +{ + "tableau piles": { + "count": 7, + "build policy": "red-black", + "move built group": "yes", + "face up cards": "top" + }, + "foundations": { + "removable": true + }, + "stock": { + "size": 31, + "deal type": "tableau piles" + } +} +)" + + }, + { + "northwest-territory", + R"( + +{ + "tableau piles": { + "build policy": "red-black", + "move built group": "yes", + "spaces policy": "kings", + "diagonal deal": true + }, + "foundations": { + "removable": true + }, + "reserve": { + "size": 16 + } +} +)" + + }, + { + "king-albert", + R"( + +{ + "tableau piles": { + "count": 9, + "build policy": "red-black", + "diagonal deal": true + }, + "foundations": { + "removable": true + }, + "reserve": { + "size": 7 + } +} +)" + + }, + { + "spiderette", + + R"( +{ + "tableau piles": { + "count": 7, + "build policy": "any-suit", + "move built group": "yes", + "move built group policy": "same-suit", + "diagonal deal": true, + "face up cards": "top" + }, + "foundations": { + "only complete pile moves": true + }, + "stock": { + "size": 24, + "deal type": "tableau piles" + } +} +)" + + }, + { + "will-o-the-wisp", + + R"( +{ + "tableau piles": { + "count": 7, + "build policy": "any-suit", + "move built group": "yes", + "move built group policy": "same-suit" + }, + "foundations": { + "only complete pile moves": true + }, + "stock": { + "size": 31, + "deal type": "tableau piles" + } +} +)" + + }, + { + "simple-simon", + + R"( +{ + "tableau piles": { + "count": 10, + "diagonal deal": true, + "move built group": "yes", + "move built group policy": "same-suit" + }, + "foundations": { + "only complete pile moves": true + } +} +)" + + }, + { + "gaps", + + R"( +{ + "foundations": { + "present": false + }, + "tableau piles": { + "count": 0 + }, + "sequences": { + "count": 4, + "direction": "L", + "build policy": "same-suit", + "fixed suit": false + } +} +)" + + }, + { + "gaps-basic-variant", + + R"( +{ + "foundations": { + "present": false + }, + "tableau piles": { + "count": 0 + }, + "sequences": { + "count": 4, + "direction": "L", + "build policy": "same-suit", + "fixed suit": true + } +} +)" + + }, + { + "simple-gaps", + + R"( +{ + "foundations": { + "present": false + }, + "tableau piles": { + "count": 0 + }, + "sequences": { + "count": 4, + "direction": "L", + "build policy": "same-suit" + }, + "max rank": 4 +} +)" + + }, + { + "simple-accordion", + + R"( +{ + "foundations": { + "present": false + }, + "tableau piles": { + "count": 0 + }, + "accordion": { + "size": 10, + "moves": ["L1", "L3"], + "build policies": ["same-suit", "same-rank"] + } +} +)" + + }, + { + "accordion-knuth", + + R"( +{ + "foundations": { + "present": false + }, + "tableau piles": { + "count": 0 + }, + "accordion": { + "size": 18, + "moves": ["L1", "L3"], + "build policies": ["same-suit", "same-rank"] + } +} +)" + + }, + { + "accordion", + + R"( +{ + "foundations": { + "present": false + }, + "tableau piles": { + "count": 0 + }, + "accordion": { + "size": 52, + "moves": ["L1", "L3"], + "build policies": ["same-suit", "same-rank"] + } +} +)" + + }, + { + "forty-theives", + + R"( +{ + "tableau piles": { + "count": 10, + "build policy": "same-suit" + }, + "stock": { + "size": 64, + "redeal": false + }, + "two decks": true +} +)" + + }, + { + "lucas", + + R"( +{ + "tableau piles": { + "count": 13, + "build policy": "same-suit" + }, + "stock": { + "size": 61, + "redeal": false + }, + "foundations": { + "initial cards": "all" + }, + "two decks": true +} +)" + + }, + { + "maria", + + R"( +{ + "tableau piles": { + "count": 9, + "build policy": "red-black" + }, + "stock": { + "size": 68, + "redeal": false + }, + "two decks": true +} +)" + + }, + { + "limited", + + R"( +{ + "tableau piles": { + "count": 12, + "build policy": "same-suit" + }, + "stock": { + "size": 68, + "redeal": false + }, + "two decks": true +} +)" + + }, + { + "streets", + + R"( +{ + "tableau piles": { + "count": 10, + "build policy": "red-black" + }, + "stock": { + "size": 64, + "redeal": false + }, + "two decks": true +} +)" + + }, + { + "rank-and-file", + + R"( +{ + "tableau piles": { + "count": 10, + "build policy": "red-black", + "face up cards": "top", + "move built group": "yes" + }, + "stock": { + "size": 64, + "redeal": false + }, + "two decks": true +} +)" + + }, + { + "american-toad", + + R"( +{ + "tableau piles": { + "count": 8, + "build policy": "same-suit", + "move built group": "whole-pile", + "spaces policy": "auto-reserve-then-waste" + }, + "foundations": { + "initial cards": "one", + "base card": "random" + }, + "stock": { + "size": 75, + "deal count": 1, + "redeal": false + }, + "reserve": { + "size": 20, + "stacked": true + }, + "two decks": true +} +)" + + }, + + { + "gargantua", + + R"( +{ + "tableau piles": { + "count": 9, + "build policy": "red-black", + "spaces policy": "kings", + "move built group": "yes", + "diagonal deal": true, + "face up cards": "top" + }, + "foundations": { + "removable": true + }, + "stock": { + "size": 59, + "deal count": 1, + "redeal": false + }, + "two decks": true +} +)" + + }, + + { + "gargantua-redeal", + + R"( +{ + "tableau piles": { + "count": 9, + "build policy": "red-black", + "spaces policy": "kings", + "move built group": "yes", + "diagonal deal": true, + "face up cards": "top" + }, + "foundations": { + "removable": true + }, + "stock": { + "size": 59, + "deal count": 1, + "redeal": true + }, + "two decks": true +} +)" + + }, + + { + "ultra-klondike-2-deck", + + R"( +{ + "tableau piles": { + "count": 12, + "build policy": "red-black", + "spaces policy": "kings", + "move built group": "yes", + "diagonal deal": true, + "face up cards": "top" + }, + "foundations": { + "removable": true + }, + "stock": { + "size": 26, + "deal count": 3, + "redeal": true + }, + "two decks": true +} +)" + + }, + + { + "american-canister", + + R"( +{ + "tableau piles": { + "count": 8, + "build policy": "red-black", + "move built group": "yes", + "spaces policy": "any" + } +} +)" + + }, + + { + "british-canister", + + R"( +{ + "tableau piles": { + "count": 8, + "build policy": "red-black", + "move built group": "no", + "spaces policy": "kings" + } +} +)" + + }, + + { + "canister-warfield", + + R"( +{ + "tableau piles": { + "count": 8, + "build policy": "any-suit", + "move built group": "yes", + "spaces policy": "any" + } +} +)" + + }, + + { + "beleaguered-castle", + + R"( +{ + "tableau piles": { + "count": 8, + "build policy": "any-suit" + }, + "foundations": { + "initial cards": "all" + } +} +)" + + }, + + { + "klondike-two-deck-9", + + R"( +{ + "tableau piles": { + "count": 9, + "build policy": "red-black", + "spaces policy": "kings", + "move built group": "yes", + "diagonal deal": true, + "face up cards": "top" + }, + "foundations": { + "removable": true + }, + "stock": { + "size": 59, + "deal count": 3, + "redeal": true + }, + "two decks": true +} +)" + + }, + + { + "streets-and-alleys", + + R"( +{ + "tableau piles": { + "count": 8, + "build policy": "any-suit" + }, + "foundations": { + "initial cards": "none" + } +} +)" + + }, + + { + "worm-hole", + + R"( +{ + "tableau piles": { + "count": 17, + "build policy": "no-build" + }, + "foundations": { + "present": false + }, + "cells": { + "count": 1 + }, + "hole": true +} +)" + + } +}; + +void sol_preset_types::print_available_games() { + cout << "The following game types can be supplied to solvitaire using the " + "'--type [name of game]' option:\n\n"; + for (auto const& x : mp) { + cout << x.first << "\n"; + } + cout << "\nUse the '--describe-game-rules [name of game]' option for an " + "overview of the rules of each game:\n"; +} + +void sol_preset_types::describe_game_rules(string game) { + auto rules_it = mp.find(game); + if (rules_it == end(mp)) { + cout << "'" << game << "' is not a valid game type. " + "Enter '--available-game-types' for a " + "list of the games presets that can be solved\n"; + } else { + cout << "The rules of '" << game << "' are as follows:" + << rules_it->second; + + if (game != "default") { + cout << "\nTo see the default values of the JSON fields not covered " + "here, enter '--describe-game-rules default'\n"; + } + } +} diff --git a/solvitaire/src/main/input-output/input/sol_preset_types.h b/solvitaire/src/main/input-output/input/sol_preset_types.h new file mode 100644 index 0000000..c5b27d3 --- /dev/null +++ b/solvitaire/src/main/input-output/input/sol_preset_types.h @@ -0,0 +1,22 @@ +// +// Created by thecharlesblake on 11/14/17. +// + +#ifndef SOLVITAIRE_SOL_PRESET_TYPES_H +#define SOLVITAIRE_SOL_PRESET_TYPES_H + +#include <string> +#include <map> + +class sol_preset_types { +public: + static std::string get(const std::string& s); + static bool is_valid_preset(const std::string& s); + static void print_available_games(); + static void describe_game_rules(std::string); + +private: + static std::map<std::string, std::string> mp; +}; + +#endif //SOLVITAIRE_SOL_PRESET_TYPES_H diff --git a/solvitaire/src/main/input-output/output/log_helper.h b/solvitaire/src/main/input-output/output/log_helper.h new file mode 100644 index 0000000..7762250 --- /dev/null +++ b/solvitaire/src/main/input-output/output/log_helper.h @@ -0,0 +1,19 @@ +// +// Created by thecharlesblake on 10/16/17. +// + +#ifndef SOLVITAIRE_LOG_HELPER_H +#define SOLVITAIRE_LOG_HELPER_H + +#include <iostream> + +#if defined NDEBUG + #define LOG_DEBUG(msg) +#else + #define LOG_DEBUG(msg) clog << "[debug]\n" << msg << "\n" +#endif +#define LOG_INFO(msg) clog << "[info] " << msg << "\n" +#define LOG_WARNING(msg) clog << "[warning] " << msg << "\n" +#define LOG_ERROR(msg) cerr << "[error] " << msg << "\n" + +#endif //SOLVITAIRE_LOG_HELPER_H diff --git a/solvitaire/src/main/input-output/output/state_printer.cpp b/solvitaire/src/main/input-output/output/state_printer.cpp new file mode 100644 index 0000000..3f1978b --- /dev/null +++ b/solvitaire/src/main/input-output/output/state_printer.cpp @@ -0,0 +1,194 @@ +// +// Created by thecharlesblake on 1/3/18. +// + +#include "state_printer.h" + +using std::ostream; +using std::vector; +using std::list; + +typedef sol_rules::stock_deal_type sdt; + +ostream& state_printer::print(ostream& stream, const game_state& gs) { + if (gs.rules.foundations_present) { + state_printer::print_header(stream, "Foundations"); + state_printer::print_top_of_piles(stream, gs.foundations, gs); + } + if (gs.rules.cells) { + state_printer::print_header(stream, "Cells"); + state_printer::print_piles(stream, gs.original_cells, gs); + } + if (gs.rules.tableau_pile_count > 0) { + state_printer::print_header(stream, "Tableau Piles"); + state_printer::print_piles(stream, gs.original_tableau_piles, gs); + } + if (gs.rules.reserve_size > 0) { + if (gs.rules.reserve_stacked) { + state_printer::print_header(stream, "Reserve (Stacked)"); + } else { + state_printer::print_header(stream, "Reserve"); + } + state_printer::print_piles(stream, gs.original_reserve, gs); + } + if (gs.rules.stock_size > 0) { + if (gs.rules.stock_deal_t == sdt::WASTE) { + state_printer::print_header(stream, "Stock | Waste"); + state_printer::print_piles(stream, {gs.stock, gs.waste}, gs); + } else { + state_printer::print_header(stream, "Stock"); + state_printer::print_piles(stream, {gs.stock}, gs); + } + } + if (gs.rules.hole) { + state_printer::print_header(stream, "Hole Card"); + state_printer::print_top_of_pile(stream, gs.hole, gs); + } + if (gs.rules.sequence_count > 0) { + state_printer::print_header(stream, "Sequences"); + state_printer::print_sequences(stream, gs.sequences, gs); + } + if (gs.rules.accordion_size > 0) { + state_printer::print_header(stream, "Accordion"); + state_printer::print_accordion(stream, gs.accordion, gs); + } + return stream << "==================================="; +} + +void state_printer::print_header(ostream& stream, const char* header) { + stream << "--- " << header << " "; + size_t pad = 20 - strlen(header); + for (size_t i = 0; i < pad; i++) { + stream << '-'; + } + stream << "\n"; +} + +void state_printer::print_piles(ostream& stream, + const vector<pile::ref>& pile_rs, + const game_state& gs) { + bool empty_row = false; + pile::size_type row_idx = 0; + + // Loops through the rows in each pile, starting from the bottom, until + // one is empty + while (!empty_row) { + // Loops through the current row to determine if it is empty + empty_row = true; + for (const pile::ref pile_r : pile_rs) { + if (gs.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::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]); + } else if (row_idx == 0) { + stream << "[]"; + } + stream << "\t"; + } + + stream << "\n"; + row_idx++; + } + } +} + +void state_printer::print_sequences(ostream& stream, + const vector<pile::ref>& seq_rs, + const game_state& gs) { + for (auto s : seq_rs) { + stream << "\n"; + auto& pile = gs.piles[s]; + for (auto i = pile.size(); i --> 0 ;) { + card c = pile[i]; + if (c == "AS") + stream << "__"; + else + print_card(stream, pile[i]); + stream << " "; + } + stream << "\n"; + } + stream << "\n"; +} + +void state_printer::print_top_of_piles(ostream& stream, + const vector<pile::ref>& vp, + const game_state& gs) { + vector<pile::ref> top(vp); + + for (pile::ref p : top) { + if (gs.piles[p].empty()) { + stream << "[]"; + } else { + print_card(stream, gs.piles[p].top_card()); + } + stream << "\t"; + } + stream << "\n"; +} + +void state_printer::print_accordion(ostream& stream, + const list<pile::ref>& vp, + const game_state& gs) { + for (pile::ref p : vp) { + print_card(stream, gs.piles[p].top_card()); + stream << "\t"; + } + stream << "\n"; +} + +void state_printer::print_top_of_pile(ostream& stream, + const pile::ref pile_r, + const game_state& gs) { + print_top_of_piles(stream, {pile_r}, gs); +} + +void state_printer::print_card(std::ostream& s, const card c) { + s << c.to_string(); +} + +void state_printer::print_move(std::ostream& s, const move m) { + s << "move("; + switch (m.type) { + case move::mtype::regular: + s << "regular"; + break; + case move::mtype::dominance: + s << "dominance"; + break; + case move::mtype::built_group: + s << "built group"; + break; + case move::mtype::stock_k_plus: + s << "stock k-plus"; + break; + case move::mtype::stock_to_all_tableau: + s << "stock-to-all-tableau"; + break; + case move::mtype::sequence: + s << "sequence"; + break; + case move::mtype::accordion: + s << "accordion"; + break; + case move::mtype::null: + s << "null"; + break; + } + s << ", " + << int(m.from) + << ", " + << int(m.to) + << ", " + << int(m.count) + << ", " + << (m.reveal_move ? "true" : "false") + << ")\n"; +} diff --git a/solvitaire/src/main/input-output/output/state_printer.h b/solvitaire/src/main/input-output/output/state_printer.h new file mode 100644 index 0000000..575b973 --- /dev/null +++ b/solvitaire/src/main/input-output/output/state_printer.h @@ -0,0 +1,35 @@ +// +// Created by thecharlesblake on 1/3/18. +// + +#ifndef SOLVITAIRE_STATE_PRINT_H +#define SOLVITAIRE_STATE_PRINT_H + +#include <ostream> + +#include "../../game/search-state/game_state.h" + +class state_printer { +public: + static std::ostream& print(std::ostream&, const game_state&); + static void print_move(std::ostream&, move); + +private: + static void print_header(std::ostream&, const char*); + static void print_piles(std::ostream&, + const std::vector<pile::ref>&, + const game_state&); + static void print_sequences(std::ostream&, + const std::vector<pile::ref>&, + const game_state&); + static void print_top_of_piles(std::ostream&, + const std::vector<pile::ref>&, + const game_state&); + static void print_top_of_pile(std::ostream&, pile::ref, + const game_state&); + static void print_accordion(std::ostream&, const std::list<pile::ref>&, + const game_state&); + static void print_card(std::ostream&, card); +}; + +#endif //SOLVITAIRE_STATE_PRINT_H diff --git a/solvitaire/src/main/main.cpp b/solvitaire/src/main/main.cpp new file mode 100644 index 0000000..faed0ca --- /dev/null +++ b/solvitaire/src/main/main.cpp @@ -0,0 +1,187 @@ +#include <boost/program_options.hpp> +#include <boost/optional.hpp> + +#include "../../lib/rapidjson/document.h" +#include "input-output/input/command_line_helper.h" +#include "input-output/input/sol_preset_types.h" +#include "input-output/input/json-parsing/json_helper.h" +#include "input-output/input/json-parsing/rules_parser.h" +#include "input-output/output/log_helper.h" +#include "solver/solver.h" +#include "evaluation/solvability_calc.h" +#include "evaluation/benchmark.h" + +using namespace rapidjson; + +using namespace std; +using namespace boost; + +namespace po = boost::program_options; + +typedef std::chrono::milliseconds millisec; + +const optional<sol_rules> gen_rules(command_line_helper&); +void solve_random_game(int, const sol_rules&, command_line_helper&); +void solve_input_files(vector<string>, const sol_rules&, command_line_helper&); +void solve_game(const sol_rules& rules, command_line_helper& clh, optional<int> seed, optional<const Document&> in_doc); +pair<solver, solver::result> solve_game(const sol_rules& rules, uint64_t timeout, uint64_t cache_capacity, + game_state::streamliner_options str_opts, + optional<int> seed, optional<const Document&> in_doc); + +// Decides what to do given supplied command-line options +int main(int argc, const char* argv[]) { + + // Parses the command-line options + command_line_helper clh; + if (!clh.parse(argc, argv)) { + return EXIT_FAILURE; + } + + // If the user has asked for the list of preset game types, prints it + if (clh.get_available_game_types()) { + 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); + return EXIT_SUCCESS; + } + + // Generates the rules of the solitaire from the game type + const optional<sol_rules> rules = gen_rules(clh); + if (!rules) return EXIT_FAILURE; + + if (clh.get_deal_only()) { + game_state gs(*rules, clh.get_random_deal(), game_state::streamliner_options::NONE); + json_helper::print_game_state_as_json(gs); + return EXIT_SUCCESS; + } + + // If the user has asked for a solvability percentage, calculates it + if (clh.get_solvability() > 0) { + solvability_calc solv_c(*rules, clh.get_cache_capacity()); + solv_c.calculate_solvability_percentage(clh.get_timeout(), clh.get_solvability(), clh.get_cores(), + clh.get_streamliners(), clh.get_resume()); + } + // 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); + } + // If the benchmark option has been supplied, generates it + else if (clh.get_benchmark()) { + benchmark::run(*rules, clh.get_cache_capacity(), clh.get_streamliners_game_state()); + } + // Otherwise there are supplied input files which should be solved + else { + const vector<string> input_files = clh.get_input_files(); + + // 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); + } + + 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()) { + return rules_parser::from_preset(clh.get_solitaire_type()); + } else { + return rules_parser::from_file(clh.get_rules_file()); + } + } catch (const runtime_error& error) { + string errmsg = "Error in rules generation: "; + errmsg += error.what(); + LOG_ERROR(errmsg); + return none; + } +} + +void solve_random_game(int seed, const sol_rules& rules, command_line_helper& clh) { + if (!clh.get_classify()) + LOG_INFO ("Attempting to solve with seed: " << seed << "..."); + solve_game(rules, clh, seed, none); +} + +void solve_input_files(const vector<string> input_files, const sol_rules& rules, command_line_helper& clh) { + for (const string& input_file : input_files) { + try { + // Reads in the input file to a json doc + const Document in_doc = json_helper::get_file_json(input_file); + + LOG_INFO ("Attempting to solve " << input_file << "..."); + solve_game(rules, clh, none, in_doc); + + } catch (const runtime_error& error) { + string errmsg = "Error parsing deal file: "; + errmsg += error.what(); + LOG_ERROR(errmsg); + } + } +} + +void solve_game(const sol_rules& rules, command_line_helper& clh, optional<int> seed, optional<const Document&> in_doc) { + typedef pair<solver, solver::result> solve_sol; + + bool smart = clh.get_streamliners() == command_line_helper::streamliner_opt::SMART; + + uint64_t timeout; + game_state::streamliner_options str_opt; + if (smart) { + timeout = clh.get_timeout() / 10; + str_opt = game_state::streamliner_options::BOTH; + } else { + timeout = clh.get_timeout(); + str_opt = clh.get_streamliners_game_state(); + } + solve_sol solution = solve_game(rules, timeout, clh.get_cache_capacity(), str_opt, seed, in_doc); + + bool run_again = smart && solution.second.sol_type != solver::result::type::SOLVED; + cout.flush(); + if (run_again) + if (!clh.get_classify()) cout << "Unsolvable using streamliner. Running again...\n"; + optional<solve_sol> streamliner_solution = run_again + ? solve_game(rules, clh.get_timeout(), clh.get_cache_capacity(), game_state::streamliner_options::NONE, seed, in_doc) + : optional<solve_sol>(); + + if (clh.get_classify()) { + if (seed) cout << *seed; + solver::print_result_csv(solution.second); + if (smart) { + if (run_again) { + solver::print_result_csv(streamliner_solution->second); + cout << ", " << streamliner_solution->second.sol_type; + } else { + solver::print_null_seed_info(); + cout << ", " << solution.second.sol_type; + } + } else { + cout << ", " << solution.second.sol_type; + } + cout << "\n"; + } else { + pair<solver, solver::result> s = run_again ? *streamliner_solution : solution; + + if (s.second.sol_type == solver::result::type::SOLVED) { + s.first.print_solution(); + } else { + cout << "Deal:\n" << s.first.init_state << "\n"; + } + cout << s.second; + } + cout.flush(); +} + +pair<solver, solver::result> solve_game(const sol_rules& rules, uint64_t timeout, uint64_t cache_capacity, + game_state::streamliner_options str_opts, + optional<int> seed, optional<const Document&> in_doc) { + game_state gs = seed ? game_state(rules, *seed, str_opts) : game_state(rules, *in_doc, str_opts); + solver sol(gs, cache_capacity); + solver::result res = sol.run(std::chrono::milliseconds(timeout)); + return make_pair(sol, res); +} diff --git a/solvitaire/src/main/solver/solver.cpp b/solvitaire/src/main/solver/solver.cpp new file mode 100644 index 0000000..e10396f --- /dev/null +++ b/solvitaire/src/main/solver/solver.cpp @@ -0,0 +1,318 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#include <string> +#include <ostream> +#include <iostream> +#include <algorithm> +#include <list> +#include <malloc.h> +#include <chrono> +#include <iomanip> +#include <signal.h> + +#include "solver.h" +#include "../game/move.h" +#include "../input-output/output/log_helper.h" +#include "../input-output/output/state_printer.h" +#include "../input-output/input/command_line_helper.h" + +using std::atomic; +using std::vector; +using std::cout; +using std::clog; +using std::pair; +using std::max; +using std::begin; +using std::end; +using boost::optional; +using std::fixed; +using std::setprecision; + +static bool sigint = false; + +void sigint_handler(int i) { + // So it doesn't complain about unused param + sigint = i == 1 ? true : true; +} + +solver::solver(const game_state& gs, uint64_t cache_capacity) + : cache(lru_cache(gs, cache_capacity)) + , init_state(gs) + , state(gs) + , frontier() + , root(move(move::mtype::null)) + , current_node() { + frontier.push_back(root); + current_node = begin(frontier); + res.states_searched = 0; + res.unique_states_searched = 0; + res.backtracks = 0; + res.dominance_moves = 0; + res.states_removed_from_cache = 0; + res.max_depth = 0; + res.depth = 0; +} + +solver::node::node(const move m) + : mv(m), child_moves(), cache_state() { +} + +solver::result solver::run(boost::optional<millisec> timeout) { + // Set interrupt handler + /* signal(SIGINT, sigint_handler); */ + + // Set timings + const clock::time_point start_time = clock::now(); + result::type res_type = timeout ? dfs(start_time + *timeout) : dfs(); + res.sol_type = res_type; + res.states_removed_from_cache = cache.get_states_removed_from_cache(); + res.cache_size = cache.size(); + res.cache_bucket_count = cache.bucket_count(); + res.time = std::chrono::duration_cast<millisec>(clock::now() - start_time); + return res; +} + +solver::result::type solver::dfs(boost::optional<clock::time_point> end_time) { + bool states_exhausted = false; + + while(!(state.is_solved() || states_exhausted)) { + if (end_time && clock::now() >= *end_time) { + return result::type::TIMEOUT; + } else if (sigint) { + return result::type::TERMINATED; + } + +#ifndef NDEBUG + if (current_node->mv.type == move::mtype::dominance) { + LOG_DEBUG("(dominance move)"); + } + LOG_DEBUG(state); +#endif + + // If there is a dominance move available, adds it to the search tree + // and repeats. Doesn't cache the state. + optional<move> dominance_move = state.get_dominance_move(); + if (dominance_move) { + // Adds the dominance move as a child of the current search node; + current_node->child_moves.emplace_back(*dominance_move); + } else { + try { + // Caches the current state + pair<lru_cache::item_list::iterator, bool> insert_res = cache.insert(state); + current_node->cache_state = insert_res.first; + bool is_new_state = insert_res.second; + + if (is_new_state) { + // Gets the legal moves in the current state + vector<move> next_moves = state.get_legal_moves(current_node->mv); + + // If there are none, reverts to the last node with children + if (next_moves.empty()) { + states_exhausted = revert_to_last_node_with_children(insert_res.first); + } else { + current_node->child_moves = std::move(next_moves); + } + } + // If the state is not a new one, reverts to the last node with children + else { + res.unique_states_searched--; + states_exhausted = revert_to_last_node_with_children(); + } + } catch (const std::runtime_error e) { + return result::type::MEM_LIMIT; + } + } + + // Sets the current node to one of its children + assert(states_exhausted == current_node->child_moves.empty()); + if (!states_exhausted) { + set_to_child(); + state.make_move(current_node->mv); + res.depth++; + res.max_depth = max(res.depth, res.max_depth); + if (current_node->mv.type == move::mtype::dominance) res.dominance_moves++; + } + + res.states_searched++; + res.unique_states_searched++; + } + + if (state.is_solved()) { + return result::type::SOLVED; + } else { + assert(states_exhausted); + return result::type::UNSOLVABLE; + } +} + +// Called when the current node's children have been exhausted. Travels back up +// the search tree until it finds a node which still has children. Returns true +// unless all children have been exhausted. + +// If an iterator to the current state is supplied to the function, will also +// make sure to turn the 'live' bit off upon backtracking +bool solver::revert_to_last_node_with_children(optional<lru_cache::item_list::iterator> cur_state) { + if (current_node == begin(frontier)) + return true; + + // Turns the 'live' bit false on the state we are backtracking out of + if (cur_state) cache.set_non_live(*cur_state); + + state.undo_move(current_node->mv); + res.depth--; + res.backtracks++; + +#ifndef NDEBUG + // Checks that the state after the undo is in the cache + // (as long as the move wasn't a dominance move) + + if (current_node->mv.type != move::mtype::dominance) { + if (cache.get_states_removed_from_cache() == 0) { + assert(cache.contains(state)); + } + LOG_DEBUG("(undo move)"); + } else { + LOG_DEBUG("(undo dominance move)"); + } + LOG_DEBUG(state); +#endif + + // Gets a reference to the parent state which can be supplied if this function is + // called recursively. This ensures that the cached state's 'live' bit is set as appropriate + optional<lru_cache::item_list::iterator> p_state = prev(current_node)->cache_state; + + // Reverts the current node to its parent and removes it + frontier.pop_back(); + current_node = prev(end(frontier)); + + // If the current node now has no children, repeat + if (current_node->child_moves.empty()) { + return revert_to_last_node_with_children(p_state); + } else { + return false; + } +} + +void solver::set_to_child() { + assert(!current_node->child_moves.empty()); + + move b = current_node->child_moves.back(); + current_node->child_moves.pop_back(); + frontier.emplace_back(b); + + current_node = prev(end(frontier)); +} + +void solver::print_solution() const { + std::flush(clog); + std::flush(cout); + + auto i = begin(frontier); + game_state state_copy = init_state; + + cout << "Solution:\n"; + cout << state_copy << "\n"; + + if (res.states_searched > 1) { + while (++i != end(frontier)) { + state_copy.make_move(i->mv); + cout << state_copy << "\n"; + } + } + cout << "\n"; +} + +std::ostream& operator<< (std::ostream& out, const solver::result::type& rt) { + switch(rt) { + case solver::result::type::TIMEOUT: + out << "timed-out"; + break; + case solver::result::type::SOLVED: + out << "solved"; + break; + case solver::result::type::UNSOLVABLE: + out << "unsolvable"; + break; + case solver::result::type::MEM_LIMIT: + out << "memory-limit-reached"; + break; + case solver::result::type::TERMINATED: + out << "terminated"; + break; + } + return out; +} + +std::ostream& operator<< (std::ostream& out, const solver::result& r) { + return out + << "Solution Type: " << r.sol_type << "\n" + << "States Searched: " << r.states_searched << "\n" + << "Unique States Searched: " << r.unique_states_searched << "\n" + << "Backtracks: " << r.backtracks << "\n" + << "Dominance Moves: " << r.dominance_moves << "\n" + << "States Removed From Cache: " << r.states_removed_from_cache << "\n" + << "Final States In Cache: " << r.cache_size << "\n" + << "Final Buckets In Cache: " << r.cache_bucket_count << "\n" + << "Maximum Search Depth: " << r.max_depth << "\n" + << "Final Search Depth: " << r.depth << "\n" + << "Time Taken (milliseconds): " << r.time.count() << "\n"; +} + +void solver::print_header(long t, command_line_helper::streamliner_opt stream_opt) { + cout << "Calculating solvability percentage...\n\n"; + if (stream_opt == command_line_helper::streamliner_opt::SMART) { + cout << ", (Streamliner Results:) " + "Attempted Seed" + ", Outcome" + ", Time Taken(ms)" + ", States Searched" + ", Unique States Searched" + ", Backtracks" + ", Dominance Moves" + ", States Removed From Cache" + ", Final States In Cache" + ", Final Buckets In Cache" + ", Maximum Search Depth" + ", Final Search Depth" + ", (Non-Streamliner Results:) "; + } + cout << "Attempted Seed" + ", Outcome" + ", Time Taken(ms)" + ", States Searched" + ", Unique States Searched" + ", Backtracks" + ", Dominance Moves" + ", States Removed From Cache" + ", Final States In Cache" + ", Final Buckets In Cache" + ", Maximum Search Depth" + ", Final Search Depth" + ", Overall Result" + "\n--- Timeout = " << t << " milliseconds ---\n"; + cout << fixed << setprecision(3); +} + +void solver::print_result_csv(solver::result res) { + cout << ", " << res.sol_type + << ", " << res.time.count() + << ", " << res.states_searched + << ", " << res.unique_states_searched + << ", " << res.backtracks + << ", " << res.dominance_moves + << ", " << res.states_removed_from_cache + << ", " << res.cache_size + << ", " << res.cache_bucket_count + << ", " << res.max_depth + << ", " << res.depth; +} + +void solver::print_null_seed_info() { + cout << ", , , , , , , , , , , "; +} + +const vector<solver::node> solver::get_frontier() const { + return frontier; +} diff --git a/solvitaire/src/main/solver/solver.h b/solvitaire/src/main/solver/solver.h new file mode 100644 index 0000000..74c73a8 --- /dev/null +++ b/solvitaire/src/main/solver/solver.h @@ -0,0 +1,78 @@ +// +// Created by thecharlesblake on 10/24/17. +// + +#ifndef SOLVITAIRE_SOLVER_H +#define SOLVITAIRE_SOLVER_H + +#include <string> +#include <vector> +#include <atomic> +#include <chrono> + +#include "../game/global_cache.h" +#include "../game/sol_rules.h" +#include "../input-output/input/command_line_helper.h" + +class solver { +public: + lru_cache cache; + + struct node { + node(move); + const move mv; + std::vector<move> child_moves; + boost::optional<lru_cache::item_list::iterator> cache_state; // Optional, as dominance moves aren't cached + }; + + struct result { + enum class type { TIMEOUT, SOLVED, UNSOLVABLE, MEM_LIMIT, TERMINATED }; + + type sol_type; + uint64_t states_searched; + uint64_t unique_states_searched; + uint64_t backtracks; + uint64_t dominance_moves; + uint64_t states_removed_from_cache; + lru_cache::item_list::size_type cache_size; + lru_cache::item_list::size_type cache_bucket_count; + uint64_t max_depth; + uint64_t depth; + std::chrono::milliseconds time; + }; + + explicit solver(const game_state&, uint64_t); + + result run(boost::optional<std::chrono::milliseconds> = boost::none); + + void print_solution() const; + static void print_header(long, command_line_helper::streamliner_opt); + static void print_result_csv(solver::result); + static void print_null_seed_info(); + const std::vector<node> get_frontier() const; + + const game_state init_state; + +private: + typedef std::chrono::high_resolution_clock clock; + typedef std::chrono::milliseconds millisec; + + result::type dfs(boost::optional<clock::time_point> = boost::none); + + bool revert_to_last_node_with_children(boost::optional<lru_cache::item_list::iterator> = boost::none); + void set_to_child(); + + game_state state; + std::vector<node> frontier; + + result res; + + node root; + std::vector<node>::iterator current_node; +}; + +std::ostream& operator<< (std::ostream&, const solver::result::type&); +std::ostream& operator<< (std::ostream&, const solver::result&); +void sigint_handler(int i); + +#endif //SOLVITAIRE_SOLVER_H diff --git a/solvitaire/src/test/integration_tests/accordion_test.cpp b/solvitaire/src/test/integration_tests/accordion_test.cpp new file mode 100644 index 0000000..bd27dec --- /dev/null +++ b/solvitaire/src/test/integration_tests/accordion_test.cpp @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/accordion/"; +const static std::string type = "simple-accordion"; + +TEST(Accordion, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(Accordion, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(Accordion, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(Accordion, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} diff --git a/solvitaire/src/test/integration_tests/alpha_star_test.cpp b/solvitaire/src/test/integration_tests/alpha_star_test.cpp new file mode 100644 index 0000000..c3b23fe --- /dev/null +++ b/solvitaire/src/test/integration_tests/alpha_star_test.cpp @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/alpha_star/"; +const static std::string type = "simple-alpha-star"; + +TEST(AlphaStar, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(AlphaStar, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(AlphaStar, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(AlphaStar, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} diff --git a/solvitaire/src/test/integration_tests/bakers_dozen_test.cpp b/solvitaire/src/test/integration_tests/bakers_dozen_test.cpp new file mode 100644 index 0000000..f3d4763 --- /dev/null +++ b/solvitaire/src/test/integration_tests/bakers_dozen_test.cpp @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/bakers_dozen/"; +const static std::string type = "simple-bakers-dozen"; + +TEST(BakersDozen, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(BakersDozen, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(BakersDozen, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(BakersDozen, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} diff --git a/solvitaire/src/test/integration_tests/black_hole_test.cpp b/solvitaire/src/test/integration_tests/black_hole_test.cpp new file mode 100644 index 0000000..a0f6707 --- /dev/null +++ b/solvitaire/src/test/integration_tests/black_hole_test.cpp @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/black_hole/"; +const static std::string type = "simple-black-hole"; + +TEST(BlackHole, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(BlackHole, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(BlackHole, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(BlackHole, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} diff --git a/solvitaire/src/test/integration_tests/canfield_test.cpp b/solvitaire/src/test/integration_tests/canfield_test.cpp new file mode 100644 index 0000000..0cb14b2 --- /dev/null +++ b/solvitaire/src/test/integration_tests/canfield_test.cpp @@ -0,0 +1,139 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" +#include "../../main/input-output/input/json-parsing/rules_parser.h" +#include "../../main/game/search-state/game_state.h" + +using std::vector; + +typedef test_helper th; +typedef game_state::streamliner_options so; +typedef std::initializer_list<std::initializer_list<std::string>> string_il; + +const static std::string path = "resources/canfield/"; +const static std::string type = "simple-canfield"; + +TEST(Canfield, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(Canfield, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(Canfield, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(Canfield, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} + +TEST(Canfield, FoundationSingleCard) { + sol_rules sr = rules_parser::from_preset("canfield"); + game_state gs(sr, 0, so::NONE); + + ASSERT_EQ(1, test_helper::cards_in_founds(gs)); +} + +TEST(Canfield, FoundationWraps) { + sol_rules sr = rules_parser::from_preset("simple-canfield"); + + game_state gs(sr, string_il{ + {"3C"},{},{},{}, // Foundations + {},{}, // Stock-waste + {}, // Reserve + {"AC"},{},{} // Tableau piles + }); + + vector<move> actual_moves = gs.get_legal_moves(); + vector<move> exp_moves = { + move(move::mtype::regular, 7, 0, 1) + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(Canfield, MoveWholePile) { + sol_rules sr = rules_parser::from_preset("simple-canfield"); + + game_state gs(sr, string_il{ + {"AC"},{},{},{}, // Foundations + {},{}, // Stock-waste + {}, // Reserve + {"2C","AH"},{"3H"},{"3C","2D"} // Tableau piles + }); + + vector<move> actual_moves = gs.get_legal_moves(); + vector<move> exp_moves = { + move(move::mtype::built_group, 7, 8, 2), + move(move::mtype::regular, 7, 1, 1), + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(Canfield, MoveWholePileNotSpace) { + sol_rules sr = rules_parser::from_preset("simple-canfield"); + + game_state gs(sr, string_il{ + {"3C"},{},{},{}, // Foundations + {},{}, // Stock-waste + {}, // Reserve + {"2H","3S","AH"},{},{"2D"} // Tableau piles + }); + + vector<move> actual_moves = gs.get_legal_moves(); + vector<move> exp_moves = {}; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(Canfield, AutoReserve) { + sol_rules sr = rules_parser::from_preset("simple-canfield"); + + game_state gs(sr, string_il{ + {"2C"},{},{},{}, // Foundations + {"3D","2D"},{}, // Stock-waste + {"3H"}, // Reserve + {"2H","3S","AH"},{},{"AC"} // Tableau piles + }); + + vector<move> actual_moves = gs.get_legal_moves(); + vector<move> exp_moves = {}; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; + + boost::optional<move> actual_dom_move = gs.get_dominance_move(); + boost::optional<move> exp_dom_move = move(move::mtype::dominance, 6, 8, 1); + + ASSERT_EQ(exp_dom_move, actual_dom_move) << *actual_dom_move; +} + +TEST(Canfield, AutoReserveThenWaste) { + sol_rules sr = rules_parser::from_preset("simple-canfield"); + + game_state gs(sr, string_il{ + {"3C"},{},{},{}, // Foundations + {"2D"},{"2S"}, // Stock-waste + {}, // Reserve + {"2H","3S","AH"},{},{"AD"} // Tableau piles + }); + + vector<move> actual_moves = gs.get_legal_moves(); + vector<move> exp_moves = { + move(move::mtype::stock_k_plus, 4, 8, 0), + move(move::mtype::stock_k_plus, 4, 8, 1) + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; + + boost::optional<move> actual_dom_move = gs.get_dominance_move(); + boost::optional<move> exp_dom_move = boost::none; + + ASSERT_EQ(exp_dom_move, actual_dom_move) << *actual_dom_move; +} diff --git a/solvitaire/src/test/integration_tests/flower_garden_test.cpp b/solvitaire/src/test/integration_tests/flower_garden_test.cpp new file mode 100644 index 0000000..641ccc0 --- /dev/null +++ b/solvitaire/src/test/integration_tests/flower_garden_test.cpp @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/flower_garden/"; +const static std::string type = "simple-flower-garden"; + +TEST(FlowerGarden, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(FlowerGarden, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(FlowerGarden, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(FlowerGarden, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} diff --git a/solvitaire/src/test/integration_tests/fortunes_favor_test.cpp b/solvitaire/src/test/integration_tests/fortunes_favor_test.cpp new file mode 100644 index 0000000..5511f9e --- /dev/null +++ b/solvitaire/src/test/integration_tests/fortunes_favor_test.cpp @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/fortunes_favor/"; +const static std::string type = "simple-fortunes-favor"; + +TEST(FortunesFavor, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(FortunesFavor, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(FortunesFavor, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(FortunesFavor, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} diff --git a/solvitaire/src/test/integration_tests/free_cell_test.cpp b/solvitaire/src/test/integration_tests/free_cell_test.cpp new file mode 100644 index 0000000..659d86b --- /dev/null +++ b/solvitaire/src/test/integration_tests/free_cell_test.cpp @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/free_cell/"; +const static std::string type = "simple-free-cell"; + +TEST(FreeCell, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(FreeCell, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(FreeCell, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(FreeCell, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} diff --git a/solvitaire/src/test/integration_tests/gaps_test.cpp b/solvitaire/src/test/integration_tests/gaps_test.cpp new file mode 100644 index 0000000..f7d0ebe --- /dev/null +++ b/solvitaire/src/test/integration_tests/gaps_test.cpp @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/gaps/"; +const static std::string type = "simple-gaps"; + +TEST(Gaps, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(Gaps, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(Gaps, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(Gaps, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} diff --git a/solvitaire/src/test/integration_tests/klondike_test.cpp b/solvitaire/src/test/integration_tests/klondike_test.cpp new file mode 100644 index 0000000..d449495 --- /dev/null +++ b/solvitaire/src/test/integration_tests/klondike_test.cpp @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/klondike/"; +const static std::string type = "simple-klondike"; + +TEST(Klondike, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(Klondike, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(Klondike, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(Klondike, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} diff --git a/solvitaire/src/test/integration_tests/somerset_test.cpp b/solvitaire/src/test/integration_tests/somerset_test.cpp new file mode 100644 index 0000000..fce8e8c --- /dev/null +++ b/solvitaire/src/test/integration_tests/somerset_test.cpp @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/somerset/"; +const static std::string type = "simple-somerset"; + +TEST(Somerset, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(Somerset, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(Somerset, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(Somerset, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} diff --git a/solvitaire/src/test/integration_tests/spanish_patience_test.cpp b/solvitaire/src/test/integration_tests/spanish_patience_test.cpp new file mode 100644 index 0000000..da32fd5 --- /dev/null +++ b/solvitaire/src/test/integration_tests/spanish_patience_test.cpp @@ -0,0 +1,28 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/spanish_patience/"; +const static std::string type = "simple-spanish-patience"; + +TEST(SpanishPatience, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(SpanishPatience, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(SpanishPatience, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +TEST(SpanishPatience, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} diff --git a/solvitaire/src/test/integration_tests/spider_test.cpp b/solvitaire/src/test/integration_tests/spider_test.cpp new file mode 100644 index 0000000..50f16fe --- /dev/null +++ b/solvitaire/src/test/integration_tests/spider_test.cpp @@ -0,0 +1,30 @@ +// +// Created by thecharlesblake on 10/4/17. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" + +typedef test_helper th; + +const static std::string path = "resources/spider/"; +const static std::string type = "simple-spider"; + +TEST(Spider, SimpleSolvable) { + EXPECT_TRUE(th::is_solvable(path + "SimpleSolvable.json", type)); +} + +TEST(Spider, ComplexSolvable) { + EXPECT_TRUE(th::is_solvable(path + "ComplexSolvable.json", type)); +} + +TEST(Spider, SimpleUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "SimpleUnsolvable.json", type)); +} + +/* Taking too long so removed, at least for now +TEST(Spider, ComplexUnsolvable) { + EXPECT_FALSE(th::is_solvable(path + "ComplexUnsolvable.json", type)); +} +*/ diff --git a/solvitaire/src/test/resources/accordion/ComplexSolvable.json b/solvitaire/src/test/resources/accordion/ComplexSolvable.json new file mode 100644 index 0000000..cdb2367 --- /dev/null +++ b/solvitaire/src/test/resources/accordion/ComplexSolvable.json @@ -0,0 +1,3 @@ +{ + "accordion": ["AC","3H","AH","2S","AD","3S","3C","AS","2C","3D"] +} diff --git a/solvitaire/src/test/resources/accordion/ComplexUnsolvable.json b/solvitaire/src/test/resources/accordion/ComplexUnsolvable.json new file mode 100644 index 0000000..09c7d32 --- /dev/null +++ b/solvitaire/src/test/resources/accordion/ComplexUnsolvable.json @@ -0,0 +1,3 @@ +{ + "accordion": ["AD","AS","AH","2S","3C","3S","4C","3H","2C","4D"] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/accordion/SimpleSolvable.json b/solvitaire/src/test/resources/accordion/SimpleSolvable.json new file mode 100644 index 0000000..00de391 --- /dev/null +++ b/solvitaire/src/test/resources/accordion/SimpleSolvable.json @@ -0,0 +1,3 @@ +{ + "accordion": ["AC","AS","AH","2C","2S","2H","3C","3S","3H","4C"] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/accordion/SimpleUnsolvable.json b/solvitaire/src/test/resources/accordion/SimpleUnsolvable.json new file mode 100644 index 0000000..2e1b9c3 --- /dev/null +++ b/solvitaire/src/test/resources/accordion/SimpleUnsolvable.json @@ -0,0 +1,3 @@ +{ + "accordion": ["AC","4S","AH","2S","AD","3S","4C","3H","2C","3D"] +} diff --git a/solvitaire/src/test/resources/alpha_star/ComplexSolvable.json b/solvitaire/src/test/resources/alpha_star/ComplexSolvable.json new file mode 100644 index 0000000..ab6b24e --- /dev/null +++ b/solvitaire/src/test/resources/alpha_star/ComplexSolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["6C","3S","2C","3C","5C","5H","4H"], + ["6S","4S","4C","5S","2D","5D"], + ["6H","6D","2S","2H","3H","4D","3D"] + ] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/alpha_star/ComplexUnsolvable.json b/solvitaire/src/test/resources/alpha_star/ComplexUnsolvable.json new file mode 100644 index 0000000..56ea441 --- /dev/null +++ b/solvitaire/src/test/resources/alpha_star/ComplexUnsolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["6C","2S","2C","3C","5C","5H","4H"], + ["6S","4S","4C","5S","2D","5D"], + ["6H","6D","3S","2H","3H","4D","3D"] + ] +} diff --git a/solvitaire/src/test/resources/alpha_star/SimpleSolvable.json b/solvitaire/src/test/resources/alpha_star/SimpleSolvable.json new file mode 100644 index 0000000..7994021 --- /dev/null +++ b/solvitaire/src/test/resources/alpha_star/SimpleSolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["6C","5S","5C","4C","3C","2S","2C"], + ["6S","6D","5D","4D","3S","3D","2D"], + ["6H","5H","4S","4H","3H","2H"] + ] +} diff --git a/solvitaire/src/test/resources/alpha_star/SimpleUnsolvable.json b/solvitaire/src/test/resources/alpha_star/SimpleUnsolvable.json new file mode 100644 index 0000000..ac6741e --- /dev/null +++ b/solvitaire/src/test/resources/alpha_star/SimpleUnsolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["2S","2C","3C","4C","5S","5C","6C"], + ["2D","3D","4S","4D","5D","6S","6D"], + ["2H","3S","3H","4H","5H","6H"] + ] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/bakers_dozen/ComplexSolvable.json b/solvitaire/src/test/resources/bakers_dozen/ComplexSolvable.json new file mode 100644 index 0000000..b953413 --- /dev/null +++ b/solvitaire/src/test/resources/bakers_dozen/ComplexSolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["AC","2S","AS","3H"], + ["AD","2D","2H","AH"], + ["3D","3C","2C","3S"] + ] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/bakers_dozen/ComplexUnsolvable.json b/solvitaire/src/test/resources/bakers_dozen/ComplexUnsolvable.json new file mode 100644 index 0000000..a8247c4 --- /dev/null +++ b/solvitaire/src/test/resources/bakers_dozen/ComplexUnsolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["AC","2S","AS","3C"], + ["AD","2D","2H","AH"], + ["3D","3H","2C","3S"] + ] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/bakers_dozen/SimpleSolvable.json b/solvitaire/src/test/resources/bakers_dozen/SimpleSolvable.json new file mode 100644 index 0000000..7c00a71 --- /dev/null +++ b/solvitaire/src/test/resources/bakers_dozen/SimpleSolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["3S","2S","AS","AD"], + ["3H","2D","2H","AH"], + ["3D","3C","2C","AC"] + ] +} diff --git a/solvitaire/src/test/resources/bakers_dozen/SimpleUnsolvable.json b/solvitaire/src/test/resources/bakers_dozen/SimpleUnsolvable.json new file mode 100644 index 0000000..0b39a8d --- /dev/null +++ b/solvitaire/src/test/resources/bakers_dozen/SimpleUnsolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["AS","2S","2D","3S"], + ["AD","AH","2H","3H"], + ["AC","2C","3C","3D"] + ] +} diff --git a/solvitaire/src/test/resources/black_hole/ComplexSolvable.json b/solvitaire/src/test/resources/black_hole/ComplexSolvable.json new file mode 100644 index 0000000..15488e9 --- /dev/null +++ b/solvitaire/src/test/resources/black_hole/ComplexSolvable.json @@ -0,0 +1,9 @@ +{ + "tableau piles": [ + ["5D","4D","3D","2D","AD"], + ["5C","4C","3C","2C","4H"], + ["AC","AH","2H","3H","5H"], + ["2S","5S","4S","3S"] + ], + "hole": "AS" +} diff --git a/solvitaire/src/test/resources/black_hole/ComplexUnsolvable.json b/solvitaire/src/test/resources/black_hole/ComplexUnsolvable.json new file mode 100644 index 0000000..ed4ee99 --- /dev/null +++ b/solvitaire/src/test/resources/black_hole/ComplexUnsolvable.json @@ -0,0 +1,9 @@ +{ + "tableau piles": [ + ["5C","3C","2C","4C","AC"], + ["5D","3D","2D","4D","AD"], + ["5H","3H","4S","4H","AH"], + ["5D","2D","2H","2S"] + ], + "hole": "AS" +} diff --git a/solvitaire/src/test/resources/black_hole/SimpleSolvable.json b/solvitaire/src/test/resources/black_hole/SimpleSolvable.json new file mode 100644 index 0000000..3a7be18 --- /dev/null +++ b/solvitaire/src/test/resources/black_hole/SimpleSolvable.json @@ -0,0 +1,9 @@ +{ + "tableau piles": [ + ["AD","2D","3D","4D","5D"], + ["AC","2C","3C","4C","5C"], + ["AH","2H","3H","4H","5H"], + ["2S","3S","4S","5S"] + ], + "hole": "AS" +} diff --git a/solvitaire/src/test/resources/black_hole/SimpleUnsolvable.json b/solvitaire/src/test/resources/black_hole/SimpleUnsolvable.json new file mode 100644 index 0000000..d6a5e7c --- /dev/null +++ b/solvitaire/src/test/resources/black_hole/SimpleUnsolvable.json @@ -0,0 +1,9 @@ +{ + "tableau piles": [ + ["5D","4D","3D","2D","AD"], + ["5C","4C","3C","2C","AC"], + ["5H","4H","3H","2H","AH"], + ["5S","4S","2S","3S"] + ], + "hole": "AS" +} diff --git a/solvitaire/src/test/resources/canfield/ComplexSolvable.json b/solvitaire/src/test/resources/canfield/ComplexSolvable.json new file mode 100644 index 0000000..2a4c252 --- /dev/null +++ b/solvitaire/src/test/resources/canfield/ComplexSolvable.json @@ -0,0 +1,10 @@ +{ + "foundations": ["2C"], + "tableau piles": [ + ["3D"], + ["3H"], + ["3S"] + ], + "reserve": ["AC","2S","3C"], + "stock": ["AH","2H","AD","AS","2D"] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/canfield/ComplexUnsolvable.json b/solvitaire/src/test/resources/canfield/ComplexUnsolvable.json new file mode 100644 index 0000000..297d06b --- /dev/null +++ b/solvitaire/src/test/resources/canfield/ComplexUnsolvable.json @@ -0,0 +1,10 @@ +{ + "foundations": ["2C"], + "tableau piles": [ + ["AS","3D"], + ["AC","3H"], + ["3S"] + ], + "reserve": ["AH","2S","3C"], + "stock": ["AD","2H","2D"] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/canfield/SimpleSolvable.json b/solvitaire/src/test/resources/canfield/SimpleSolvable.json new file mode 100644 index 0000000..3353b5c --- /dev/null +++ b/solvitaire/src/test/resources/canfield/SimpleSolvable.json @@ -0,0 +1,10 @@ +{ + "foundations": ["2C"], + "tableau piles": [ + ["2S"], + ["AC"], + ["3D"] + ], + "reserve": ["AH","3S"], + "stock": ["2H","AS","3H","2D","3C","AD"] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/canfield/SimpleUnsolvable.json b/solvitaire/src/test/resources/canfield/SimpleUnsolvable.json new file mode 100644 index 0000000..440c358 --- /dev/null +++ b/solvitaire/src/test/resources/canfield/SimpleUnsolvable.json @@ -0,0 +1,10 @@ +{ + "foundations": ["2C"], + "tableau piles": [ + ["3D"], + ["3H"], + ["3S"] + ], + "reserve": ["2S","AS"], + "stock": ["AC","2H","3C","AH","AD","2D"] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/flower_garden/ComplexSolvable.json b/solvitaire/src/test/resources/flower_garden/ComplexSolvable.json new file mode 100644 index 0000000..1f1a6e6 --- /dev/null +++ b/solvitaire/src/test/resources/flower_garden/ComplexSolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["AH","2D","AC"], + ["AD","2C","3D"], + ["2H","AS","3H"] + ], + "reserve": ["3C","2S","3S"] +} diff --git a/solvitaire/src/test/resources/flower_garden/ComplexUnsolvable.json b/solvitaire/src/test/resources/flower_garden/ComplexUnsolvable.json new file mode 100644 index 0000000..be0ca64 --- /dev/null +++ b/solvitaire/src/test/resources/flower_garden/ComplexUnsolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["2H","2D","AC"], + ["AD","2C","3D"], + ["AH","AS","3H"] + ], + "reserve": ["3C","2S","3S"] +} diff --git a/solvitaire/src/test/resources/flower_garden/SimpleSolvable.json b/solvitaire/src/test/resources/flower_garden/SimpleSolvable.json new file mode 100644 index 0000000..18c680d --- /dev/null +++ b/solvitaire/src/test/resources/flower_garden/SimpleSolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["3C","2C","AC"], + ["3D","2D","AD"], + ["3H","3S","AH"] + ], + "reserve": ["2H","2S","AS"] +} diff --git a/solvitaire/src/test/resources/flower_garden/SimpleUnsolvable.json b/solvitaire/src/test/resources/flower_garden/SimpleUnsolvable.json new file mode 100644 index 0000000..e57e9ca --- /dev/null +++ b/solvitaire/src/test/resources/flower_garden/SimpleUnsolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["AC","2C","3C"], + ["AD","2D","3D"], + ["AH","AS","3H"] + ], + "reserve": ["2H","2S","3S"] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/fortunes_favor/ComplexSolvable.json b/solvitaire/src/test/resources/fortunes_favor/ComplexSolvable.json new file mode 100644 index 0000000..f00d600 --- /dev/null +++ b/solvitaire/src/test/resources/fortunes_favor/ComplexSolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["2C","2D","4H"], + ["4C","3D","3H"], + ["2S","3C","4D"] + ], + "stock": ["2H","3S","4S"] +} diff --git a/solvitaire/src/test/resources/fortunes_favor/ComplexUnsolvable.json b/solvitaire/src/test/resources/fortunes_favor/ComplexUnsolvable.json new file mode 100644 index 0000000..4f54b94 --- /dev/null +++ b/solvitaire/src/test/resources/fortunes_favor/ComplexUnsolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["2H","2D","4H"], + ["2C","3D","3H"], + ["2S","3C","4D"] + ], + "stock": ["4C","3S","4S"] +} diff --git a/solvitaire/src/test/resources/fortunes_favor/SimpleSolvable.json b/solvitaire/src/test/resources/fortunes_favor/SimpleSolvable.json new file mode 100644 index 0000000..0891746 --- /dev/null +++ b/solvitaire/src/test/resources/fortunes_favor/SimpleSolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["2C","2D","2H"], + ["3C","3D","3H"], + ["4C","4D","4H"] + ], + "stock": ["4S","3S","2S"] +} diff --git a/solvitaire/src/test/resources/fortunes_favor/SimpleUnsolvable.json b/solvitaire/src/test/resources/fortunes_favor/SimpleUnsolvable.json new file mode 100644 index 0000000..44d7359 --- /dev/null +++ b/solvitaire/src/test/resources/fortunes_favor/SimpleUnsolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["2C","2D","3C"], + ["2H","3D","3H"], + ["2S","4D","4H"] + ], + "stock": ["4C","3S","4S"] +} diff --git a/solvitaire/src/test/resources/free_cell/ComplexSolvable.json b/solvitaire/src/test/resources/free_cell/ComplexSolvable.json new file mode 100644 index 0000000..ca370ff --- /dev/null +++ b/solvitaire/src/test/resources/free_cell/ComplexSolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["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/solvitaire/src/test/resources/free_cell/ComplexUnsolvable.json b/solvitaire/src/test/resources/free_cell/ComplexUnsolvable.json new file mode 100644 index 0000000..48ac428 --- /dev/null +++ b/solvitaire/src/test/resources/free_cell/ComplexUnsolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["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/solvitaire/src/test/resources/free_cell/SimpleSolvable.json b/solvitaire/src/test/resources/free_cell/SimpleSolvable.json new file mode 100644 index 0000000..1bebaf2 --- /dev/null +++ b/solvitaire/src/test/resources/free_cell/SimpleSolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["4C","3C","2C","AC"], + ["4D","3D","2D","AD"], + ["4H","3H","2H","AH"], + ["4S","3S","2S","AS"] + ] +} diff --git a/solvitaire/src/test/resources/free_cell/SimpleUnsolvable.json b/solvitaire/src/test/resources/free_cell/SimpleUnsolvable.json new file mode 100644 index 0000000..8cdcc26 --- /dev/null +++ b/solvitaire/src/test/resources/free_cell/SimpleUnsolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["AC","2C","3C","4C"], + ["AD","2D","3D","4D"], + ["AH","2H","3H","4H"], + ["AS","2S","3S","4S"] + ] +} diff --git a/solvitaire/src/test/resources/gaps/ComplexSolvable.json b/solvitaire/src/test/resources/gaps/ComplexSolvable.json new file mode 100644 index 0000000..f9fcb41 --- /dev/null +++ b/solvitaire/src/test/resources/gaps/ComplexSolvable.json @@ -0,0 +1,8 @@ +{ + "sequences": [ + ["4C","2S","2C",""], + ["2D","3S","4D",""], + ["4S","3C","3D",""], + ["2H","3H","4H",""] + ] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/gaps/ComplexUnsolvable.json b/solvitaire/src/test/resources/gaps/ComplexUnsolvable.json new file mode 100644 index 0000000..2c9de3e --- /dev/null +++ b/solvitaire/src/test/resources/gaps/ComplexUnsolvable.json @@ -0,0 +1,8 @@ +{ + "sequences": [ + ["2C","4S","4C",""], + ["3S","2D","4D",""], + ["2S","3C","3D",""], + ["2H","3H","4H",""] + ] +} diff --git a/solvitaire/src/test/resources/gaps/SimpleSolvable.json b/solvitaire/src/test/resources/gaps/SimpleSolvable.json new file mode 100644 index 0000000..2e9cdfe --- /dev/null +++ b/solvitaire/src/test/resources/gaps/SimpleSolvable.json @@ -0,0 +1,8 @@ +{ + "sequences": [ + ["2C","4S","4C",""], + ["2D","3S","4D",""], + ["2S","3C","3D",""], + ["2H","3H","4H",""] + ] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/gaps/SimpleUnsolvable.json b/solvitaire/src/test/resources/gaps/SimpleUnsolvable.json new file mode 100644 index 0000000..b0c0529 --- /dev/null +++ b/solvitaire/src/test/resources/gaps/SimpleUnsolvable.json @@ -0,0 +1,8 @@ +{ + "sequences": [ + ["2C","3C","4C",""], + ["3S","2D","4D",""], + ["2S","4S","3D",""], + ["2H","3H","4H",""] + ] +} diff --git a/solvitaire/src/test/resources/klondike/ComplexSolvable.json b/solvitaire/src/test/resources/klondike/ComplexSolvable.json new file mode 100644 index 0000000..8711780 --- /dev/null +++ b/solvitaire/src/test/resources/klondike/ComplexSolvable.json @@ -0,0 +1,9 @@ +{ + "tableau piles": [ + ["3d","2c","4c","2H"], + ["Ah","3h","2S"], + ["Ad","3C"], + ["4S"] + ], + "stock": ["3S","AS","AC","2D","4H","4D"] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/klondike/ComplexUnsolvable.json b/solvitaire/src/test/resources/klondike/ComplexUnsolvable.json new file mode 100644 index 0000000..7685ce1 --- /dev/null +++ b/solvitaire/src/test/resources/klondike/ComplexUnsolvable.json @@ -0,0 +1,9 @@ +{ + "tableau piles": [ + ["3d","2c","4c","2H"], + ["Ah","3h","2S"], + ["Ad","3C"], + ["4S"] + ], + "stock": ["3S","4D","AC","2D","4H","AS"] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/klondike/SimpleSolvable.json b/solvitaire/src/test/resources/klondike/SimpleSolvable.json new file mode 100644 index 0000000..f54ebbb --- /dev/null +++ b/solvitaire/src/test/resources/klondike/SimpleSolvable.json @@ -0,0 +1,9 @@ +{ + "tableau piles": [ + ["3d","2c","Ac","2H"], + ["4h","3h","2S"], + ["4d","3C"], + ["AS"] + ], + "stock": ["3S","4S","4C","2D","AH","AD"] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/klondike/SimpleUnsolvable.json b/solvitaire/src/test/resources/klondike/SimpleUnsolvable.json new file mode 100644 index 0000000..21a5854 --- /dev/null +++ b/solvitaire/src/test/resources/klondike/SimpleUnsolvable.json @@ -0,0 +1,9 @@ +{ + "tableau piles": [ + ["As","2c","2d","2H"], + ["Ah","3h","2S"], + ["Ad","3C"], + ["4S"] + ], + "stock": ["3S","4D","AC","4C","4H","3D"] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/somerset/ComplexSolvable.json b/solvitaire/src/test/resources/somerset/ComplexSolvable.json new file mode 100644 index 0000000..b316c50 --- /dev/null +++ b/solvitaire/src/test/resources/somerset/ComplexSolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["2S","2C","AC"], + ["2D","AD"], + ["2H","AH"], + ["AS"] + ] +} diff --git a/solvitaire/src/test/resources/somerset/ComplexUnsolvable.json b/solvitaire/src/test/resources/somerset/ComplexUnsolvable.json new file mode 100644 index 0000000..09d7864 --- /dev/null +++ b/solvitaire/src/test/resources/somerset/ComplexUnsolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["AS","AC","2C"], + ["AD","2D"], + ["AH","2H"], + ["2S"] + ] +} diff --git a/solvitaire/src/test/resources/somerset/SimpleSolvable.json b/solvitaire/src/test/resources/somerset/SimpleSolvable.json new file mode 100644 index 0000000..b316c50 --- /dev/null +++ b/solvitaire/src/test/resources/somerset/SimpleSolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["2S","2C","AC"], + ["2D","AD"], + ["2H","AH"], + ["AS"] + ] +} diff --git a/solvitaire/src/test/resources/somerset/SimpleUnsolvable.json b/solvitaire/src/test/resources/somerset/SimpleUnsolvable.json new file mode 100644 index 0000000..09d7864 --- /dev/null +++ b/solvitaire/src/test/resources/somerset/SimpleUnsolvable.json @@ -0,0 +1,8 @@ +{ + "tableau piles": [ + ["AS","AC","2C"], + ["AD","2D"], + ["AH","2H"], + ["2S"] + ] +} diff --git a/solvitaire/src/test/resources/spanish_patience/ComplexSolvable.json b/solvitaire/src/test/resources/spanish_patience/ComplexSolvable.json new file mode 100644 index 0000000..c48ce47 --- /dev/null +++ b/solvitaire/src/test/resources/spanish_patience/ComplexSolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["AS", "2S", "AH"], + ["AD", "2D", "2H"], + ["2C", "AC"] + ] +} diff --git a/solvitaire/src/test/resources/spanish_patience/ComplexUnsolvable.json b/solvitaire/src/test/resources/spanish_patience/ComplexUnsolvable.json new file mode 100644 index 0000000..ba9be59 --- /dev/null +++ b/solvitaire/src/test/resources/spanish_patience/ComplexUnsolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["AS", "2S", "AH"], + ["AD", "2D", "2H"], + ["AC", "2C"] + ] +} diff --git a/solvitaire/src/test/resources/spanish_patience/SimpleSolvable.json b/solvitaire/src/test/resources/spanish_patience/SimpleSolvable.json new file mode 100644 index 0000000..eacad0e --- /dev/null +++ b/solvitaire/src/test/resources/spanish_patience/SimpleSolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["2S", "AS", "AD"], + ["2D", "2H", "AH"], + ["2C", "AC"] + ] +} diff --git a/solvitaire/src/test/resources/spanish_patience/SimpleUnsolvable.json b/solvitaire/src/test/resources/spanish_patience/SimpleUnsolvable.json new file mode 100644 index 0000000..99a3140 --- /dev/null +++ b/solvitaire/src/test/resources/spanish_patience/SimpleUnsolvable.json @@ -0,0 +1,7 @@ +{ + "tableau piles": [ + ["AS", "2S", "2D"], + ["AD", "AH", "2H"], + ["AC", "2C"] + ] +} diff --git a/solvitaire/src/test/resources/spider/ComplexSolvable.json b/solvitaire/src/test/resources/spider/ComplexSolvable.json new file mode 100644 index 0000000..c7d96e2 --- /dev/null +++ b/solvitaire/src/test/resources/spider/ComplexSolvable.json @@ -0,0 +1,13 @@ +{ + "tableau piles": [ + ["2D","AD","3D"], + ["AC","2C","3C"], + ["AS","2S","3S"], + ["3H","2H","AH"] + ], + "stock": [ + "2C","3D","3H","3S", + "AC","AD","AH","AS", + "3C","2D","2H","2S" + ] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/spider/ComplexUnsolvable.json b/solvitaire/src/test/resources/spider/ComplexUnsolvable.json new file mode 100644 index 0000000..2379c9a --- /dev/null +++ b/solvitaire/src/test/resources/spider/ComplexUnsolvable.json @@ -0,0 +1,13 @@ +{ + "tableau piles": [ + ["2D","AD","3D"], + ["AC","2C","3C"], + ["AS","2S","3S"], + ["3H","2H","AH"] + ], + "stock": [ + "3C","3D","3H","3S", + "2C","2D","AH","AS", + "AC","AD","2H","2S" + ] +}
\ No newline at end of file diff --git a/solvitaire/src/test/resources/spider/SimpleSolvable.json b/solvitaire/src/test/resources/spider/SimpleSolvable.json new file mode 100644 index 0000000..f0b9b00 --- /dev/null +++ b/solvitaire/src/test/resources/spider/SimpleSolvable.json @@ -0,0 +1,14 @@ +{ + "tableau piles": [ + ["3C","2C","AC"], + ["3D","2D","AD"], + ["3H","2H","AH"], + ["3S","2S","AS"] + ], + "stock": [ + "3C","2C","AC", + "3D","2D","AD", + "3H","2H","AH", + "3S","2S","AS" + ] +} diff --git a/solvitaire/src/test/resources/spider/SimpleUnsolvable.json b/solvitaire/src/test/resources/spider/SimpleUnsolvable.json new file mode 100644 index 0000000..d11a6dd --- /dev/null +++ b/solvitaire/src/test/resources/spider/SimpleUnsolvable.json @@ -0,0 +1,13 @@ +{ + "tableau piles": [ + ["AC","AC","2C"], + ["AD","AD","2D"], + ["AH","AH","2H"], + ["AS","AS","2S"] + ], + "stock": [ + "3C","3D","3H","3S", + "2C","2D","2H","2S", + "3C","3D","3H","3S" + ] +} diff --git a/solvitaire/src/test/test_helper.cpp b/solvitaire/src/test/test_helper.cpp new file mode 100644 index 0000000..6cc68aa --- /dev/null +++ b/solvitaire/src/test/test_helper.cpp @@ -0,0 +1,148 @@ +// +// Created by thecharlesblake on 12/26/17. +// + +#include <gtest/gtest.h> + +#include "test_helper.h" +#include "../main/game/search-state/game_state.h" +#include "../main/solver/solver.h" +#include "../main/input-output/input/json-parsing/json_helper.h" +#include "../main/input-output/input/json-parsing/rules_parser.h" +#include "../../lib/rapidjson/document.h" + +#define ASSERT_(t_f, statement) ASSERT_TRUE((statement) == (t_f)) + +using namespace rapidjson; +using std::vector; +using std::ostream; + +typedef std::initializer_list<std::initializer_list<std::string>> string_il; +typedef game_state::streamliner_options sos; + + +bool test_helper::is_solvable(const std::string& input_file, const std::string& preset_type) { + const Document in_doc = json_helper::get_file_json(input_file); + const sol_rules rules = rules_parser::from_preset(preset_type); + + game_state gs(rules, in_doc, sos::NONE); + solver sol(gs, 1000000); + + return sol.run().sol_type == solver::result::type::SOLVED; +} + +void test_helper::run_foundations_dominance_test(sol_rules::build_policy policy, + std::vector<card> cards) { + sol_rules rules = rules_parser::from_preset("simple-free-cell"); + rules.build_pol = policy; + rules.foundations_removable = false; + rules.cells = 0; + + game_state gs = game_state(rules, string_il{ + {}, + {}, + {}, + {}, + {"4C","3C","2C","AC"}, + {"4H","3H","2H","AH"}, + {"4S","3S","2S","AS"}, + {"4D","3D","2D","AD"} + }); + + solver sol(gs, 1000000); + sol.run(); + + auto frontier = sol.get_frontier(); + auto i = std::begin(frontier); + + for (card c : cards) { + i++; + ASSERT_TRUE(i->mv.type == move::mtype::dominance); + ASSERT_TRUE(gs.get_data()[i->mv.from].top_card() == c); + ASSERT_TRUE(i->mv.to >= 0 && i->mv.to <= 4); + gs.make_move(i->mv); + } + ASSERT_TRUE(i->child_moves.empty()); +} + +void test_helper::expected_moves_test(sol_rules sr, + string_il piles, + vector<move> exp_moves) { + game_state gs(sr, piles); + vector<move> actual_moves = gs.get_legal_moves(); + + ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +bool test_helper::moves_eq(vector<move>& exp_moves, vector<move>& actual_moves) { + if (exp_moves.size() != actual_moves.size()) return false; + + for (move m : actual_moves) { + auto it = find(begin(exp_moves), end(exp_moves), m); + bool found = it != end(exp_moves); + + if (found) exp_moves.erase(it); + else return false; + } + + return true; +} + +void test_helper::k_plus_stock_test + ( sol_rules sr + , string_il piles + , vector<move> exp_moves + , move m + , pile::size_type stock_size + , pile::size_type waste_size + , card top_stock + , card top_waste + ) { + + game_state gs(sr, piles); + vector<move> actual_moves = gs.get_legal_moves(); + + ASSERT_TRUE(moves_eq(exp_moves, actual_moves)) << actual_moves; + + gs.make_move(m); + + ASSERT_EQ(gs.get_data()[gs.stock].size(), stock_size) << gs.get_data()[gs.stock].size(); + ASSERT_EQ(gs.get_data()[gs.waste].size(), waste_size) << gs.get_data()[gs.waste].size(); + + if (top_stock == card()) + ASSERT_TRUE(gs.get_data()[gs.stock].empty()); + else + ASSERT_EQ(gs.get_data()[gs.stock].top_card(), top_stock ) << gs.get_data()[gs.stock].top_card().to_string(); + + if (top_waste == card()) + ASSERT_TRUE(gs.get_data()[gs.waste].empty()); + else + ASSERT_EQ(gs.get_data()[gs.waste].top_card(), top_waste ) << gs.get_data()[gs.waste].top_card().to_string(); + + gs.undo_move(m); + + ASSERT_EQ(gs.get_data(), game_state(sr, piles).get_data()) << gs; +} + +uint8_t test_helper::cards_in_founds(game_state& gs) { + uint8_t sz = 0; + for (auto found : gs.foundations) { + sz += gs.piles[found].size(); + } + return sz; +} + +ostream& operator <<(ostream& os, const move& m) { + return os << "move:(" << int(m.from) + << "," << int(m.to) + << "," << int(m.count) + << "," << m.reveal_move + << ")"; +} + +ostream& operator <<(ostream& os, const vector<move>& moves) { + for (const move m : moves) { + os << m << ",\n"; + } + return os; +} diff --git a/solvitaire/src/test/test_helper.h b/solvitaire/src/test/test_helper.h new file mode 100644 index 0000000..89d28cb --- /dev/null +++ b/solvitaire/src/test/test_helper.h @@ -0,0 +1,41 @@ +// +// Created by thecharlesblake on 12/26/17. +// + +#ifndef SOLVITAIRE_TEST_HELPER_H +#define SOLVITAIRE_TEST_HELPER_H + +#include <string> + +#include "../main/game/sol_rules.h" +#include "../main/game/card.h" +#include "../main/game/pile.h" +#include "../main/game/move.h" +#include "../main/game/search-state/game_state.h" + +class test_helper { +public: + static bool is_solvable(const std::string&, const std::string&); + static void run_foundations_dominance_test(sol_rules::build_policy policy, + std::vector<card> cards); + static void expected_moves_test(sol_rules sr, std::initializer_list<std::initializer_list<std::string>>, + std::vector<move>); + static void k_plus_stock_test + ( sol_rules sr + , std::initializer_list<std::initializer_list<std::string>> + , std::vector<move> + , move + , pile::size_type + , pile::size_type + , card + , card + ); + static bool moves_eq(std::vector<move>&, std::vector<move>&); + static uint8_t cards_in_founds(game_state&); +}; + +std::ostream& operator <<(std::ostream&, const move&); +std::ostream& operator <<(std::ostream&, const std::vector<move>&); + + +#endif //SOLVITAIRE_TEST_HELPER_H diff --git a/solvitaire/src/test/unit_tests/built_group_move_gen_test.cpp b/solvitaire/src/test/unit_tests/built_group_move_gen_test.cpp new file mode 100644 index 0000000..5e3a492 --- /dev/null +++ b/solvitaire/src/test/unit_tests/built_group_move_gen_test.cpp @@ -0,0 +1,313 @@ +// +// Created by thecharlesblake on 1/11/18. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" +#include "../../main/game/search-state/game_state.h" +#include "../../main/game/sol_rules.h" + +typedef sol_rules::build_policy pol; +typedef sol_rules::spaces_policy s_pol; +typedef sol_rules::built_group_type bgt; + +using std::vector; +using std::ostream; +using std::initializer_list; + +TEST(BuiltGroupMoveGen, SameSuitEmpty) { + sol_rules sr; + sr.tableau_pile_count = 5; + sr.built_group_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + + test_helper::expected_moves_test( + sr, + { + {}, + {"3C", "2C", "AC"}, // Same suit + {"3H", "2S", "AH"}, // Red black + {"3D", "2D", "AS"}, // Any suit + {} + }, + { + // Regular moves + move(move::mtype::regular, 1, 0, 1), + move(move::mtype::regular, 2, 0, 1), + move(move::mtype::regular, 3, 0, 1), + move(move::mtype::regular, 1, 4, 1), + move(move::mtype::regular, 2, 4, 1), + move(move::mtype::regular, 3, 4, 1), + + // Built group moves + move(move::mtype::built_group, 1, 0, 2), + move(move::mtype::built_group, 1, 0, 3), + move(move::mtype::built_group, 1, 4, 2), + move(move::mtype::built_group, 1, 4, 3) + } + ); +} + +TEST(BuiltGroupMoveGen, RedBlackEmpty) { + sol_rules sr; + sr.tableau_pile_count = 5; + sr.built_group_pol = pol::RED_BLACK; + sr.move_built_group = bgt::YES; + + test_helper::expected_moves_test( + sr, + { + {}, + {"3C", "2C", "AC"}, // Same suit + {"3H", "2S", "AH"}, // Red black + {"3D", "2D", "AS"}, // Any suit + {} + }, + { + // Regular moves + move(move::mtype::regular, 1, 0, 1), + move(move::mtype::regular, 2, 0, 1), + move(move::mtype::regular, 3, 0, 1), + move(move::mtype::regular, 1, 4, 1), + move(move::mtype::regular, 2, 4, 1), + move(move::mtype::regular, 3, 4, 1), + + // Built group moves + move(move::mtype::built_group, 2, 0, 2), + move(move::mtype::built_group, 2, 0, 3), + move(move::mtype::built_group, 2, 4, 2), + move(move::mtype::built_group, 2, 4, 3), + + move(move::mtype::built_group, 3, 0, 2), + move(move::mtype::built_group, 3, 4, 2) + } + ); +} + +TEST(BuiltGroupMoveGen, AnySuitEmpty) { + sol_rules sr; + sr.tableau_pile_count = 5; + sr.built_group_pol = pol::ANY_SUIT; + sr.move_built_group = bgt::YES; + + test_helper::expected_moves_test( + sr, + { + {}, + {"3C", "2C", "AC"}, // Same suit + {"3H", "2S", "AH"}, // Red black + {"3D", "2D", "AS"}, // Any suit + {} + }, + { + // Regular moves + move(move::mtype::regular, 1, 0, 1), + move(move::mtype::regular, 2, 0, 1), + move(move::mtype::regular, 3, 0, 1), + move(move::mtype::regular, 1, 4, 1), + move(move::mtype::regular, 2, 4, 1), + move(move::mtype::regular, 3, 4, 1), + + // Built group moves + move(move::mtype::built_group, 1, 0, 2), + move(move::mtype::built_group, 1, 0, 3), + move(move::mtype::built_group, 1, 4, 2), + move(move::mtype::built_group, 1, 4, 3), + + move(move::mtype::built_group, 2, 0, 2), + move(move::mtype::built_group, 2, 0, 3), + move(move::mtype::built_group, 2, 4, 2), + move(move::mtype::built_group, 2, 4, 3), + + move(move::mtype::built_group, 3, 0, 2), + move(move::mtype::built_group, 3, 0, 3), + move(move::mtype::built_group, 3, 4, 2), + move(move::mtype::built_group, 3, 4, 3), + } + ); +} + +TEST(BuiltGroupMoveGen, CantMove) { + sol_rules sr; + sr.tableau_pile_count = 5; + sr.built_group_pol = pol::ANY_SUIT; + sr.move_built_group = bgt::NO; + + test_helper::expected_moves_test( + sr, + { + {}, + {"3C", "2C", "AC"}, // Same suit + {"3H", "2S", "AH"}, // Red black + {"3D", "2D", "AS"}, // Any suit + {} + }, + { + // Regular moves + move(move::mtype::regular, 1, 0, 1), + move(move::mtype::regular, 2, 0, 1), + move(move::mtype::regular, 3, 0, 1), + move(move::mtype::regular, 1, 4, 1), + move(move::mtype::regular, 2, 4, 1), + move(move::mtype::regular, 3, 4, 1) + } + ); +} + +TEST(BuiltGroupMoveGen, SameSuitOccupied) { + sol_rules sr; + sr.tableau_pile_count = 6; + sr.build_pol = pol::SAME_SUIT; + sr.built_group_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + + test_helper::expected_moves_test( + sr, + { + {"4C"}, + {"3C", "2C", "AC"}, // Same suit + {"3H", "2S", "AH"}, // Red black + {"3D", "2D", "AS"}, // Any suit + {}, + {"3C"} + }, + { + // Regular moves + move(move::mtype::regular, 1, 4, 1), + move(move::mtype::regular, 2, 4, 1), + move(move::mtype::regular, 3, 4, 1), + move(move::mtype::regular, 5, 0, 1), + + // Built group moves + move(move::mtype::built_group, 1, 0, 3), + move(move::mtype::built_group, 1, 4, 2), + move(move::mtype::built_group, 1, 4, 3), + move(move::mtype::built_group, 1, 5, 2) + } + ); +} + +TEST(BuiltGroupMoveGen, RedBlackOccupied) { + sol_rules sr; + sr.tableau_pile_count = 6; + sr.build_pol = pol::RED_BLACK; + sr.built_group_pol = pol::RED_BLACK; + sr.move_built_group = bgt::YES; + + test_helper::expected_moves_test( + sr, + { + {"4C"}, + {"3C", "2C", "AC"}, // Same suit + {"3H", "2S", "AH"}, // Red black + {"3D", "2D", "AS"}, // Any suit + {}, + {"3C"} + }, + { + // Regular moves + move(move::mtype::regular, 1, 4, 1), + move(move::mtype::regular, 2, 4, 1), + move(move::mtype::regular, 3, 4, 1), + + // Built group moves + move(move::mtype::built_group, 2, 0, 3), + move(move::mtype::built_group, 2, 4, 2), + move(move::mtype::built_group, 2, 4, 3), + move(move::mtype::built_group, 3, 4, 2), + move(move::mtype::built_group, 3, 5, 2) + } + ); +} + +TEST(BuiltGroupMoveGen, AnySuitOccupied) { + sol_rules sr; + sr.tableau_pile_count = 6; + sr.build_pol = pol::ANY_SUIT; + sr.built_group_pol = pol::ANY_SUIT; + sr.move_built_group = bgt::YES; + + test_helper::expected_moves_test( + sr, + { + {"4C"}, + {"3C", "2C", "AC"}, // Same suit + {"3H", "2S", "AH"}, // Red black + {"3D", "2D", "AS"}, // Any suit + {}, + {"3C"} + }, + { + // Regular moves + move(move::mtype::regular, 1, 4, 1), + move(move::mtype::regular, 2, 4, 1), + move(move::mtype::regular, 3, 4, 1), + move(move::mtype::regular, 5, 0, 1), + + // Built group moves + move(move::mtype::built_group, 1, 0, 3), + move(move::mtype::built_group, 2, 0, 3), + move(move::mtype::built_group, 3, 0, 3), + + move(move::mtype::built_group, 1, 4, 2), + move(move::mtype::built_group, 1, 4, 3), + + move(move::mtype::built_group, 2, 4, 2), + move(move::mtype::built_group, 2, 4, 3), + + move(move::mtype::built_group, 3, 4, 2), + move(move::mtype::built_group, 3, 4, 3), + + move(move::mtype::built_group, 1, 5, 2), + move(move::mtype::built_group, 2, 5, 2), + move(move::mtype::built_group, 3, 5, 2) + } + ); +} + +TEST(BuiltGroupMoveGen, KingsOnly) { + sol_rules sr; + sr.tableau_pile_count = 5; + sr.build_pol = pol::SAME_SUIT; + sr.built_group_pol = pol::RED_BLACK; + sr.move_built_group = bgt::YES; + sr.spaces_pol = s_pol::KINGS; + + test_helper::expected_moves_test( + sr, + { + {}, + {"KC", "QC", "JC"}, // Same suit + {"KH", "QS", "JH"}, // Red black + {"KD", "QD", "JS"}, // Any suit + {} + }, + { + // Built group moves + move(move::mtype::built_group, 2, 0, 3), + move(move::mtype::built_group, 2, 4, 3) + } + ); +} + +TEST(BuiltGroupMoveGen, NoBuild) { + sol_rules sr; + sr.tableau_pile_count = 5; + sr.build_pol = pol::SAME_SUIT; + sr.built_group_pol = pol::RED_BLACK; + sr.move_built_group = bgt::YES; + sr.spaces_pol = s_pol::NO_BUILD; + + test_helper::expected_moves_test( + sr, + { + {}, + {"KC", "QC", "JC"}, // Same suit + {"KH", "QS", "JH"}, // Red black + {"KD", "QD", "JS"}, // Any suit + {} + }, + {} + ); +} diff --git a/solvitaire/src/test/unit_tests/card_test.cpp b/solvitaire/src/test/unit_tests/card_test.cpp new file mode 100644 index 0000000..346dff9 --- /dev/null +++ b/solvitaire/src/test/unit_tests/card_test.cpp @@ -0,0 +1,92 @@ +// +// Created by thecharlesblake on 1/11/18. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" +#include "../../main/game/card.h" + +TEST(Card, Rank) { + for (card::rank_t r = 1; r <= 13; r++) { + card::suit_t s = card::suit::Clubs; + card c(s, r); + ASSERT_EQ(r, c.get_rank()); + } +} + +TEST(Card, Suit) { + for (card::suit_t s : { + card::suit::Clubs, + card::suit::Hearts, + card::suit::Spades, + card::suit::Diamonds + }) { + card::rank_t r = 1; + card c(s, r); + ASSERT_EQ(s, c.get_suit()); + } +} + +TEST(Card, Colour) { + card::rank_t r = 1; + + for (card::suit_t s : { + card::suit::Clubs, + card::suit::Spades + }) { + card c(s, r); + ASSERT_EQ(card::colour::Black, c.get_colour()); + } + + for (card::suit_t s : { + card::suit::Hearts, + card::suit::Diamonds + }) { + card c(s, r); + ASSERT_EQ(card::colour::Red, c.get_colour()); + } +} + +TEST(Card, EqOps) { + for (card::rank_t r = 1; r <= 13; r++) { + for (card::suit_t s : { + card::suit::Clubs, + card::suit::Hearts, + card::suit::Spades, + card::suit::Diamonds + }) { + card a(s, r); + card b(s, r); + ASSERT_TRUE (a == b); + ASSERT_FALSE(a != b); + } + } +} + +TEST(Card, RelativeOps) { + for (card::rank_t r = 1; r <= 12; r++) { + for (card::suit_t s : { + card::suit::Clubs, + card::suit::Hearts, + card::suit::Spades, + card::suit::Diamonds + }) { + card a(s, r); + card b(s, card::rank_t(r+1)); + ASSERT_TRUE (a < b); + ASSERT_TRUE (a <= b); + ASSERT_FALSE(a > b); + ASSERT_FALSE(a >= b); + } + } +} + +TEST(Card, StringConstructor) { + ASSERT_EQ(card(card::suit::Spades , card::rank_t(1) ), card("AS" )); + ASSERT_EQ(card(card::suit::Clubs , card::rank_t(1) ), card("Ac" )); + ASSERT_EQ(card(card::suit::Diamonds, card::rank_t(5) ), card("5D" )); + ASSERT_EQ(card(card::suit::Hearts , card::rank_t(11)), card("11H")); + ASSERT_EQ(card(card::suit::Spades , card::rank_t(11)), card("JS" )); + ASSERT_EQ(card(card::suit::Clubs , card::rank_t(13)), card("kc" )); +} diff --git a/solvitaire/src/test/unit_tests/deal_parser_test.cpp b/solvitaire/src/test/unit_tests/deal_parser_test.cpp new file mode 100644 index 0000000..db2bd31 --- /dev/null +++ b/solvitaire/src/test/unit_tests/deal_parser_test.cpp @@ -0,0 +1,143 @@ +// +// Created by thecharlesblake on 1/11/18. +// + +#include <gtest/gtest.h> + +#include "../../../lib/rapidjson/stringbuffer.h" +#include "../../../lib/rapidjson/document.h" + +#include "../../main/input-output/input/json-parsing/deal_parser.h" +#include "../../main/input-output/input/json-parsing/json_helper.h" + +using namespace std; +using namespace rapidjson; + +void run_deal_parser_test(bool, const char*); + +TEST(DealParser, SimpleTableauLetter) { + run_deal_parser_test(true, R"( +{ + "tableau piles": [ + ["AS"] + ] +} +)"); +} + +TEST(DealParser, SimpleTableauNumber) { + run_deal_parser_test(true, R"( +{ + "tableau piles": [ + ["1S"] + ] +} +)"); +} + +TEST(DealParser, IllegalTableauNumber) { + run_deal_parser_test(false, R"( +{ + "tableau piles": [ + ["14S"] + ] +} +)"); +} + +TEST(DealParser, IllegalTableauSuit) { + run_deal_parser_test(false, R"( +{ + "tableau piles": [ + ["14A"] + ] +} +)"); +} + +TEST(DealParser, SimpleTableauCase) { + run_deal_parser_test(true, R"( +{ + "tableau piles": [ + ["kc"] + ] +} +)"); +} + +TEST(DealParser, AdvancedTableau) { + run_deal_parser_test(true, R"( +{ + "tableau piles": [ + ["5S","13C","4C","3C","2S","2c"], + ["5D","qD","3S","1d","2D"], + ["5H","4S","JH","3h","2H"] + ] +} +)"); +} + +TEST(DealParser, Hole) { + run_deal_parser_test(true, R"( +{ + "tableau piles": [ + ["5S","13C","4C"] + ], + "hole": "qD" +} +)"); +} + +TEST(DealParser, Stock) { + run_deal_parser_test(true, R"( +{ + "tableau piles": [ + ["5S","13C","4C"] + ], + "stock": ["1S","JC","7H"] +} +)"); +} + +TEST(DealParser, Waste) { + run_deal_parser_test(true, R"( +{ + "tableau piles": [ + ["5S","13C","4C"] + ], + "waste": ["1S","JC","7H"] +} +)"); +} + +TEST(DealParser, IllegalPileType) { + run_deal_parser_test(false, R"( +{ + "tableau piles": [ + ["5S","13C","4C"] + ], + "other": ["1S","JC","7H"] +} +)"); +} + +void run_deal_parser_test(bool validity, const char* json) { + Document in_doc; + in_doc.Parse(json); + if (in_doc.HasParseError()) { + throw runtime_error("invalid json"); + } + + Document val_doc; + val_doc.Parse(deal_parser::deal_schema_json().c_str()); + SchemaDocument sd(val_doc); + SchemaValidator validator(sd); + bool acc = in_doc.Accept(validator); + if (acc) { + ASSERT_TRUE(validity == acc) << "JSON accepted when it should not have " + "been:\n" << json; + } else { + ASSERT_TRUE(validity == acc) << json_helper::schema_err_str(validator) + << "\n" << json; + } +} diff --git a/solvitaire/src/test/unit_tests/face_up_cards_test.cpp b/solvitaire/src/test/unit_tests/face_up_cards_test.cpp new file mode 100644 index 0000000..1311958 --- /dev/null +++ b/solvitaire/src/test/unit_tests/face_up_cards_test.cpp @@ -0,0 +1,317 @@ +// +// Created by thecharlesblake on 1/11/18. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" +#include "../../main/game/search-state/game_state.h" +#include "../../main/game/sol_rules.h" +#include "../../main/game/global_cache.h" + +typedef sol_rules::build_policy pol; +typedef sol_rules::face_up_policy fu; +typedef move::mtype mt; +typedef sol_rules::built_group_type bgt; + +using std::vector; +using std::ostream; + +typedef std::initializer_list<std::initializer_list<std::string>> string_il; + +#define ASSERT_FACE_UP(card) ASSERT_FALSE(card.is_face_down()) << card.to_string() << " should be face up" +#define ASSERT_FACE_DOWN(card) ASSERT_TRUE(card.is_face_down()) << card.to_string() << " should be face down" + + +TEST(FaceUpCards, CapsFaceUpIfFaceUpNotAll) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.built_group_pol = pol::SAME_SUIT; + sr.build_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + sr.face_up = fu::TOP_CARDS; + + string_il piles = { + {"3S"}, + {"2s","AS"}, + {} + }; + + game_state gs(sr, piles); + + ASSERT_FACE_UP(gs.get_data()[0][0]); + ASSERT_FACE_UP(gs.get_data()[1][0]); + ASSERT_FACE_DOWN(gs.get_data()[1][1]); +} + +TEST(FaceUpCards, IgnoreCapsIfFaceUpAll) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.built_group_pol = pol::SAME_SUIT; + sr.build_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + sr.face_up = fu::ALL; + + string_il piles = { + {"3S"}, + {"2s","AS"}, + {} + }; + + game_state gs(sr, piles); + + ASSERT_FACE_UP(gs.get_data()[0][0]); + ASSERT_FACE_UP(gs.get_data()[1][0]); + ASSERT_FACE_UP(gs.get_data()[1][1]); +} + +TEST(FaceUpCards, MoveTurnsFaceUp) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.built_group_pol = pol::SAME_SUIT; + sr.build_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + sr.face_up = fu::TOP_CARDS; + + string_il piles = { + {"4S"}, + {"3s","AS"}, // from + {"2S"} // to + }; + + test_helper::expected_moves_test( + sr, + piles, + { + // Regular moves + move(move::mtype::regular, 1, 2, 1, true) + } + ); + + game_state gs(sr, piles); + gs.make_move(move(mt::regular, 1, 2, 1, true)); + + ASSERT_FACE_UP(gs.get_data()[0][0]); + ASSERT_FACE_UP(gs.get_data()[1][0]); + ASSERT_FACE_UP(gs.get_data()[2][0]); +} + +TEST(FaceUpCards, BuiltGroupMoveTurnsFaceUp) { + sol_rules sr; + sr.tableau_pile_count = 2; + sr.built_group_pol = pol::SAME_SUIT; + sr.build_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + sr.face_up = fu::TOP_CARDS; + + string_il piles = { + {"3s","2S","AS"}, // from + {} // to + }; + + test_helper::expected_moves_test( + sr, + piles, + { + // Regular moves + move(move::mtype::regular, 0, 1, 1, false), + // Built-group moves + move(move::mtype::built_group, 0, 1, 2, true) + } + ); + + game_state gs(sr, piles); + gs.make_move(move(mt::built_group, 0, 1, 2, true)); + + ASSERT_FACE_UP(gs.get_data()[0][0]); + ASSERT_FACE_UP(gs.get_data()[1][0]); + ASSERT_FACE_UP(gs.get_data()[1][1]); +} + +TEST(FaceUpCards, MoveAlreadyFaceUpNoChange) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.built_group_pol = pol::SAME_SUIT; + sr.build_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + sr.face_up = fu::TOP_CARDS; + + string_il piles = { + {"4S"}, + {"3s","AS"}, // from + {"2S"} // to + }; + + test_helper::expected_moves_test( + sr, + piles, + { + // Regular moves + move(move::mtype::regular, 1, 2, 1, true) + } + ); + + game_state gs(sr, piles); + gs.make_move(move(mt::regular, 1, 2, 1, true)); + + ASSERT_FACE_UP(gs.get_data()[0][0]); + ASSERT_FACE_UP(gs.get_data()[1][0]); + ASSERT_FACE_UP(gs.get_data()[2][0]); +} + +TEST(FaceUpCards, FaceDownNoBuiltGroup) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.built_group_pol = pol::SAME_SUIT; + sr.build_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + sr.face_up = fu::TOP_CARDS; + + test_helper::expected_moves_test( + sr, + { + {"4S"}, + {"3s","AS"}, + {"2S"} + }, + { + // Regular moves + move(move::mtype::regular, 1, 2, 1, true) + } + ); +} + +TEST(FaceUpCards, FaceUpBuiltGroup) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.built_group_pol = pol::SAME_SUIT; + sr.build_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + sr.face_up = fu::TOP_CARDS; + + test_helper::expected_moves_test( + sr, + { + {"3S"}, + {"2S","AS"}, + {} + }, + { + // Regular moves + move(mt::regular, 1, 2, 1), + + // Built group moves + move(mt::built_group, 1, 0, 2), + move(mt::built_group, 1, 2, 2) + } + ); +} + +TEST(FaceUpCards, FaceUpBuiltGroup2Not3) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.built_group_pol = pol::SAME_SUIT; + sr.build_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + sr.face_up = fu::TOP_CARDS; + + test_helper::expected_moves_test( + sr, + { + {"4S"}, + {"3s","2S","AS"}, + {"3S"} + }, + { + // Regular moves + move(mt::regular, 2, 0, 1, false), + + // Built group moves + move(mt::built_group, 1, 2, 2, true) + } + ); +} + +TEST(FaceUpCards, UndoTurnsBackFaceDown) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.built_group_pol = pol::SAME_SUIT; + sr.build_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + sr.face_up = fu::TOP_CARDS; + + string_il piles = { + {"3S"}, + {"2s","AS"}, // from + {} // to + }; + + game_state gs(sr, piles); + move m = move(mt::regular, 1, 2, 1, true); + gs.make_move(m); + gs.undo_move(m); + + ASSERT_FACE_UP(gs.get_data()[0][0]); + ASSERT_FACE_UP(gs.get_data()[1][0]); + ASSERT_FACE_DOWN(gs.get_data()[1][1]); +} + +TEST(FaceUpCards, UndoBuiltGroupTurnsBackFaceDown) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.built_group_pol = pol::SAME_SUIT; + sr.build_pol = pol::SAME_SUIT; + sr.move_built_group = bgt::YES; + sr.face_up = fu::TOP_CARDS; + + string_il piles = { + {"4S"}, + {"3s","2S","AS"}, // from + {} // to + }; + + game_state gs(sr, piles); + move m = move(mt::built_group, 1, 2, 2, true); + gs.make_move(m); + gs.undo_move(m); + + ASSERT_FACE_UP(gs.get_data()[0][0]); + ASSERT_FACE_UP(gs.get_data()[1][0]); + ASSERT_FACE_UP(gs.get_data()[1][1]); + ASSERT_FACE_DOWN(gs.get_data()[1][2]); +} + +TEST(FaceUpCards, CacheEncodesFaceDown) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.built_group_pol = pol::RED_BLACK; + sr.build_pol = pol::RED_BLACK; + sr.move_built_group = bgt::YES; + sr.face_up = fu::TOP_CARDS; + + string_il piles = { + {"2C"}, + {"2s","AH"}, + {} + }; + + game_state gs(sr, piles); + lru_cache cache(gs, 1000); + bool new_state; + + gs.make_move(move(mt::regular, 1, 2, 1, true)); + new_state = cache.insert(gs).second; + ASSERT_TRUE(new_state) << "AH to empty pile"; + + gs.make_move(move(mt::regular, 2, 1, 1, false)); + new_state = cache.insert(gs).second; + ASSERT_TRUE(new_state) << "AH back to face-up 2S"; + + gs.make_move(move(mt::regular, 1, 0, 1, false)); + new_state = cache.insert(gs).second; + ASSERT_TRUE(new_state) << "AH to 2C"; + + gs.make_move(move(mt::regular, 0, 1, 1, false)); + new_state = cache.insert(gs).second; + ASSERT_FALSE(new_state) << "AH to 2S"; +} diff --git a/solvitaire/src/test/unit_tests/foundations_dominance_test.cpp b/solvitaire/src/test/unit_tests/foundations_dominance_test.cpp new file mode 100644 index 0000000..8fdc285 --- /dev/null +++ b/solvitaire/src/test/unit_tests/foundations_dominance_test.cpp @@ -0,0 +1,29 @@ +// +// Created by thecharlesblake on 1/11/18. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" +#include "../../main/game/search-state/game_state.h" +#include "../../main/game/global_cache.h" + +typedef sol_rules::build_policy pol; + +TEST(FoundationsDominance, SameSuit) { + test_helper::run_foundations_dominance_test(pol::SAME_SUIT, { + "AC","2C","3C","4C","AH","2H","3H","4H","AS","2S","3S","4S","AD", + "2D","3D","4D"}); +} + +TEST(FoundationsDominance, RedBlack) { + test_helper::run_foundations_dominance_test(pol::RED_BLACK, { + "AC","2C","AH","2H","AS","3H","2S","AD","3C","4H","3S","2D","4C", + "4S","3D","4D"}); +} + +TEST(FoundationsDominance, AnySuit) { + test_helper::run_foundations_dominance_test(pol::ANY_SUIT, { + "AC","2C","AH","2H","AS","2S","AD","3C","3H","3S","2D","4C","4H", + "4S","3D","4D"}); +}
\ No newline at end of file diff --git a/solvitaire/src/test/unit_tests/global_cache_test.cpp b/solvitaire/src/test/unit_tests/global_cache_test.cpp new file mode 100644 index 0000000..93ef105 --- /dev/null +++ b/solvitaire/src/test/unit_tests/global_cache_test.cpp @@ -0,0 +1,78 @@ +// +// Created by thecharlesblake on 1/11/18. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" +#include "../../main/game/search-state/game_state.h" +#include "../../main/game/global_cache.h" + +typedef sol_rules::build_policy pol; +typedef std::initializer_list<std::initializer_list<std::string>> string_il; + +TEST(GlobalCache, CommutativeTableauPiles) { + sol_rules rules; + rules.tableau_pile_count = 3; + rules.build_pol = sol_rules::build_policy::SAME_SUIT; + game_state gs(rules, string_il{{},{},{}}); + lru_cache cache(gs, 1000); + + cache.insert (game_state(rules, {{"AC"},{"2D"},{"3H"}})); + ASSERT_TRUE (cache.contains(game_state(rules, {{"2D"},{"3H"},{"AC"}}))); + ASSERT_FALSE(cache.contains(game_state(rules, {{"3H"},{"2D"},{"3H"}}))); + + // Test with empty piles + cache.clear(); + cache.insert (game_state(rules, {{"4C"},{"5D"},{}})); + ASSERT_TRUE (cache.contains(game_state(rules, {{},{"4C"},{"5D"}}))); + ASSERT_FALSE(cache.contains(game_state(rules, {{},{"4C"},{}}))); + + // Test with piles of size > 1 + cache.clear(); + cache.insert (game_state(rules, {{"6C","7D"},{"8C"},{"9D"}})); + ASSERT_TRUE (cache.contains(game_state(rules, {{"8C"},{"6C","7D"},{"9D"}}))); + ASSERT_FALSE(cache.contains(game_state(rules, {{"8C"},{"6C","KD"},{"9D"}}))); +} + +TEST(GlobalCache, CommutativeReserve) { + sol_rules rules; + rules.reserve_size = 3; + rules.build_pol = sol_rules::build_policy::SAME_SUIT; + game_state gs(rules, string_il{{},{},{}}); + lru_cache cache(gs, 1000); + + cache.insert (game_state(rules, {{"AC"},{"2D"},{"3H"}})); + ASSERT_TRUE (cache.contains(game_state(rules, {{"2D"},{"3H"},{"AC"}}))); + ASSERT_FALSE(cache.contains(game_state(rules, {{"3H"},{"2D"},{"3H"}}))); + + // Test with empty piles + cache.clear(); + cache.insert (game_state(rules, {{"4C"},{"5D"},{}})); + ASSERT_TRUE (cache.contains(game_state(rules, {{},{"4C"},{"5D"}}))); + ASSERT_FALSE(cache.contains(game_state(rules, {{},{"4C"},{}}))); + + // Test with piles of size > 1 + cache.clear(); + cache.insert (game_state(rules, {{"6C","7D"},{"8C"},{"9D"}})); + ASSERT_TRUE (cache.contains(game_state(rules, {{"8C"},{"6C","7D"},{"9D"}}))); + ASSERT_FALSE(cache.contains(game_state(rules, {{"8C"},{"6C","KD"},{"9D"}}))); +} + +TEST(GlobalCache, CommutativeCells) { + sol_rules rules; + rules.cells = 3; + rules.build_pol = sol_rules::build_policy::SAME_SUIT; + game_state gs(rules, string_il{{},{},{}}); + lru_cache cache(gs, 1000); + + cache.insert (game_state(rules, {{"AC"},{"2D"},{"3H"}})); + ASSERT_TRUE (cache.contains(game_state(rules, {{"2D"},{"3H"},{"AC"}}))); + ASSERT_FALSE(cache.contains(game_state(rules, {{"3H"},{"2D"},{"3H"}}))); + + // Test with empty piles + cache.clear(); + cache.insert (game_state(rules, {{"4C"},{"5D"},{}})); + ASSERT_TRUE (cache.contains(game_state(rules, {{},{"4C"},{"5D"}}))); + ASSERT_FALSE(cache.contains(game_state(rules, {{},{"4C"},{}}))); +} diff --git a/solvitaire/src/test/unit_tests/k_plus_stock_test.cpp b/solvitaire/src/test/unit_tests/k_plus_stock_test.cpp new file mode 100644 index 0000000..dcd4410 --- /dev/null +++ b/solvitaire/src/test/unit_tests/k_plus_stock_test.cpp @@ -0,0 +1,426 @@ +// +// Created by thecharlesblake on 1/11/18. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" +#include "../../main/game/search-state/game_state.h" +#include "../../main/game/sol_rules.h" + +typedef sol_rules::build_policy pol; +typedef sol_rules::stock_deal_type sdt; + +using std::vector; +using std::ostream; +using std::initializer_list; + + +TEST(KPlusStock, NoRedealExact) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = false; + sr.stock_deal_count = 3; + + test_helper::k_plus_stock_test( + sr, + { + {"2H","2D","3S","AD","2S","3C","AC","AH","AS"}, + {}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 4, 3), + move(move::mtype::stock_k_plus, 0, 3, 9), + }, + move(move::mtype::stock_k_plus, 0, 3, 9), + 0, 8, + card(), "2D" + ); +} + +TEST(KPlusStock, NoRedealOneExtra) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = false; + sr.stock_deal_count = 3; + + test_helper::k_plus_stock_test( + sr, + { + {"2H","AD","2S","3C","AC","AH","AS"}, + {}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 4, 3), + move(move::mtype::stock_k_plus, 0, 3, 7), + }, + move(move::mtype::stock_k_plus, 0, 3, 7), + 0, 6, + card(), "AD" + ); +} + +TEST(KPlusStock, NoRedealTwoExtra) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = false; + sr.stock_deal_count = 3; + + test_helper::k_plus_stock_test( + sr, + { + {"2S","2H","AD","2D","3C","AC","AH","AS"}, + {}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 4, 3) + }, + move(move::mtype::stock_k_plus, 0, 4, 3), + 5, 2, + "3C", "AH" + ); +} + +TEST(KPlusStock, RedealExact) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = true; + sr.stock_deal_count = 3; + + test_helper::k_plus_stock_test( + sr, + { + {"2H","2D","3S","AD","2S","3C","AC","AH","AS"}, + {}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 4, 3, false, false), + move(move::mtype::stock_k_plus, 0, 3, 9, false, true), + }, + move(move::mtype::stock_k_plus, 0, 3, 9, false, true), + 8, 0, + "AS", card() + ); +} + +TEST(KPlusStock, RedealOneExtra) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = true; + sr.stock_deal_count = 3; + + test_helper::k_plus_stock_test( + sr, + { + {"2H","AD","2S","3C","AC","AH","AS"}, + {}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 4, 3, false, false), + move(move::mtype::stock_k_plus, 0, 3, 7, false, true), + }, + move(move::mtype::stock_k_plus, 0, 3, 7, false, true), + 6, 0, + "AS", card() + ); +} + +TEST(KPlusStock, RedealTwoExtra) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = true; + sr.stock_deal_count = 3; + + test_helper::k_plus_stock_test( + sr, + { + {"2S","2H","AD","2D","3C","AC","AH","AS"}, + {}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 4, 3, false, false) + }, + move(move::mtype::stock_k_plus, 0, 4, 3, false, false), + 5, 2, + "3C", "AH" + ); +} + +TEST(KPlusStock, RedealKPlus3Waste) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = true; + sr.stock_deal_count = 3; + + test_helper::k_plus_stock_test( + sr, + { + {"2H","2D","3S","AD","2S","3C"}, + {"AS","AH","AC"}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 3, 6, false, true), + move(move::mtype::stock_k_plus, 0, 4, 0, false, false) + }, + move(move::mtype::stock_k_plus, 0, 3, 6, false, true), + 8, 0, + "AS", card() + ); +} + +TEST(KPlusStock, RedealKPlus4Waste) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = true; + sr.stock_deal_count = 3; + + test_helper::k_plus_stock_test( + sr, + { + {"2H","AD","3S","2D","2S"}, + {"AS","AH","AC","3C"}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 3, 5, false, true), + move(move::mtype::stock_k_plus, 0, 4, -1, false, false), + move(move::mtype::stock_k_plus, 0, 2, 2, false, false) + }, + move(move::mtype::stock_k_plus, 0, 2, 2, false, false), + 3, 5, + "3S", "2S" + ); +} + +TEST(KPlusStock, RedealKPlus5Waste) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 10; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = true; + sr.stock_deal_count = 3; + + test_helper::k_plus_stock_test( + sr, + { + {"2S","2D","2H","AD","2S"}, + {"AS","AH","AC","3C","4S"}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 3, 3, false, false), + move(move::mtype::stock_k_plus, 0, 4, -2, false, false), + move(move::mtype::stock_k_plus, 0, 2, 4, false, false) + }, + move(move::mtype::stock_k_plus, 0, 3, 3, false, false), + 2, 7, + "2D", "AD" + ); +} + +TEST(KPlusStock, RedealKPlusEmptyStock) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = true; + sr.stock_deal_count = 3; + + test_helper::k_plus_stock_test( + sr, + { + {"2H","2D","3S","AD","2S","3C"}, + {"AS","AH","AC"}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 3, 6, false, true), + move(move::mtype::stock_k_plus, 0, 4, 0, false, false) + }, + move(move::mtype::stock_k_plus, 0, 3, 6, false, true), + 8, 0, + "AS", card() + ); +} + +TEST(KPlusStock, NoRedealCellFoundationMoves) { + sol_rules sr; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = false; + sr.stock_deal_count = 3; + sr.cells = 2; + sr.foundations_present = true; + + test_helper::k_plus_stock_test( + sr, + { + {"AC"}, {}, {}, {}, + {"2D"}, {}, + {"2H","AS","2C","AH","2S","3C"}, + {"3S"} + }, + { + // Cell moves + move(move::mtype::stock_k_plus, 6, 5, 3), + move(move::mtype::stock_k_plus, 6, 5, 6), + + // Foundation moves + move(move::mtype::stock_k_plus, 6, 1, 3), + + // Regular waste move + move(move::mtype::stock_k_plus, 6, 5, 0) + }, + move(move::mtype::stock_k_plus, 6, 1, 3), + 3, 3, + "2C", "2S" + ); +} + +TEST(KPlusStock, RedealCellFoundationMoves) { + sol_rules sr; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = true; + sr.stock_deal_count = 3; + sr.cells = 2; + sr.foundations_present = true; + + test_helper::k_plus_stock_test( + sr, + { + {"AC"}, {}, {}, {}, + {"2D"}, {}, + {"2H","AS","2C","AH","2S","3C"}, + {"3S"} + }, + { + // Cell moves + move(move::mtype::stock_k_plus, 6, 5, 3, false, false), + move(move::mtype::stock_k_plus, 6, 5, 6, false, true), + move(move::mtype::stock_k_plus, 6, 5, 2, false, false), + move(move::mtype::stock_k_plus, 6, 5, 5, false, false), + + // Foundation moves + move(move::mtype::stock_k_plus, 6, 1, 3, false, false), + move(move::mtype::stock_k_plus, 6, 2, 5, false, false), + + // Regular waste move + move(move::mtype::stock_k_plus, 6, 5, 0) + }, + move(move::mtype::stock_k_plus, 6, 2, 5, false, false), + 1, 5, + "2H", "2C" + ); +} + +TEST(KPlusStock, RedealCount1BottomStock) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = true; + sr.stock_deal_count = 1; + + test_helper::k_plus_stock_test( + sr, + { + {"2H","2S","AD","2D"}, + {}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 2, 1, false, false), + move(move::mtype::stock_k_plus, 0, 3, 4, false, true) + }, + move(move::mtype::stock_k_plus, 0, 3, 4, false, true), + 3, 0, + "2D", card() + ); +} + +TEST(KPlusStock, RedealCount1TopStock) { + sol_rules sr; + sr.tableau_pile_count = 3; + sr.build_pol = pol::SAME_SUIT; + sr.stock_size = 9; + sr.stock_deal_t = sdt::WASTE; + sr.stock_redeal = true; + sr.stock_deal_count = 1; + + test_helper::k_plus_stock_test( + sr, + { + {"2H","2S","AD","2D"}, + {}, + {"3D"}, + {"3H"}, + {"2C"} + }, + { + move(move::mtype::stock_k_plus, 0, 2, 1, false, false), + move(move::mtype::stock_k_plus, 0, 3, 4, false, true) + }, + move(move::mtype::stock_k_plus, 0, 2, 1, false, false), + 3, 0, + "AD", card() + ); +} diff --git a/solvitaire/src/test/unit_tests/legal_move_gen_test.cpp b/solvitaire/src/test/unit_tests/legal_move_gen_test.cpp new file mode 100644 index 0000000..da5c63c --- /dev/null +++ b/solvitaire/src/test/unit_tests/legal_move_gen_test.cpp @@ -0,0 +1,326 @@ +// +// Created by thecharlesblake on 1/11/18. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" +#include "../../main/game/search-state/game_state.h" +#include "../../main/game/sol_rules.h" +#include "../../main/game/move.h" + +typedef sol_rules::build_policy pol; +typedef sol_rules::spaces_policy s_pol; +typedef sol_rules::stock_deal_type sdt; +typedef sol_rules::built_group_type bgt; + +using std::vector; +using std::ostream; + +typedef std::initializer_list<std::initializer_list<std::string>> string_il; + + +TEST(LegalMoveGen, BuildPolAnySuit) { + sol_rules sr; + sr.build_pol = pol::ANY_SUIT; + sr.tableau_pile_count = 5; + + game_state gs(sr, string_il{ + {"2C"}, + {"2H"}, + {"2D"}, + {"2S"}, + {"AC"} + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + move(move::mtype::regular, 4,0), + move(move::mtype::regular, 4,1), + move(move::mtype::regular, 4,2), + move(move::mtype::regular, 4,3) + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, BuildPolRedBlack) { + sol_rules sr; + sr.build_pol = pol::RED_BLACK; + sr.tableau_pile_count = 5; + + game_state gs(sr, string_il{ + {"2C"}, + {"2H"}, + {"2S"}, + {"2D"}, + {"AC"} + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + move(move::mtype::regular, 4,1), + move(move::mtype::regular, 4,3) + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, BuildPolSameSuit) { + sol_rules sr; + sr.build_pol = pol::SAME_SUIT; + sr.tableau_pile_count = 5; + + game_state gs(sr, string_il{ + {"2C"}, + {"2H"}, + {"2S"}, + {"2D"}, + {"AC"} + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + move(move::mtype::regular, 4,0) + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, BuildPolNoBuild) { + sol_rules sr; + sr.build_pol = pol::NO_BUILD; + sr.tableau_pile_count = 5; + + game_state gs(sr, string_il{ + {"2C"}, + {"2H"}, + {"2S"}, + {"2D"}, + {"AC"} + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, SpacesPolAny) { + sol_rules sr; + sr.spaces_pol = s_pol::ANY; + sr.tableau_pile_count = 2; + + game_state gs(sr, string_il{ + {}, + {"AC"} + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + // move(move::mtype::regular, 1, 0) // Now forbidden as always pointless + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, SpacesPolKings) { + sol_rules sr; + sr.spaces_pol = s_pol::KINGS; + sr.tableau_pile_count = 3; + + game_state gs(sr, string_il{ + {}, + {"AC"}, + {"3S","KD"} + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + move(move::mtype::regular, 2, 0) + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, SpacesPolNoBuild) { + sol_rules sr; + sr.spaces_pol = s_pol::NO_BUILD; + sr.tableau_pile_count = 2; + + game_state gs(sr, string_il{ + {}, + {"AC"} + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, MoveBuiltGroupTrue) { + sol_rules sr; + sr.move_built_group = bgt::YES; + sr.tableau_pile_count = 2; + + game_state gs(sr, string_il{ + {}, + {"2C", "AC"} + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + move(move::mtype::regular, 1, 0, 1), + move(move::mtype::built_group, 1, 0, 2) + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, MoveBuiltGroupFalse) { + sol_rules sr; + sr.move_built_group = bgt::NO; + sr.tableau_pile_count = 2; + + game_state gs(sr, string_il{ + {}, + {"AC", "2C"} + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + move(move::mtype::regular, 1, 0, 1) + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, Foundations) { + sol_rules sr; + sr.foundations_present = true; + sr.tableau_pile_count = 4; + + game_state gs(sr, string_il{ + {}, {}, {}, {}, + {"AC"}, + {"AH"}, + {"AS"}, + {"AD"}, + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + move(move::mtype::regular, 4, 0), + move(move::mtype::regular, 5, 1), + move(move::mtype::regular, 6, 2), + move(move::mtype::regular, 7, 3) + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, FoundationsRemovable) { + sol_rules sr; + sr.foundations_present = true; + sr.foundations_removable = true; + sr.tableau_pile_count = 1; + + game_state gs(sr, string_il{ + {"AC","2C","3C"}, // Without a few cards here dominance logic blocks + {}, // removing from foundation + {}, + {}, + {} + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + move(move::mtype::regular, 0, 4) + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + + +TEST(LegalMoveGen, TwoDecksFoundations) { + sol_rules sr; + sr.two_decks = true; + sr.foundations_removable = true; + sr.foundations_present = true; + sr.tableau_pile_count = 4; + + game_state gs(sr, string_il{ + {"AC"}, {}, {}, {}, {}, {}, {"AS"}, {}, + {}, + {"AH"}, + {}, + {"AD"}, + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + // Aces up + move(move::mtype::regular, 9, 1), + move(move::mtype::regular, 9, 5), + move(move::mtype::regular, 11, 3), + move(move::mtype::regular, 11, 7), + + // Aces down + move(move::mtype::regular, 0, 8), + move(move::mtype::regular, 0, 10), + move(move::mtype::regular, 6, 8), + move(move::mtype::regular, 6, 10), + + // Aces across (forbidden now) + //move(move::mtype::regular, 9, 8), + //move(move::mtype::regular, 9, 10), + //move(move::mtype::regular, 11, 8), + //move(move::mtype::regular, 11, 10), + + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, Cells) { + sol_rules sr; + sr.cells = 2; + sr.tableau_pile_count = 1; + + game_state gs(sr, string_il{ + {"3D"}, {}, // The cells + {"4H"} + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + move(move::mtype::regular, 0, 2), + move(move::mtype::regular, 2, 1) + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} + +TEST(LegalMoveGen, StockDealToTableau) { + sol_rules sr; + sr.foundations_present = true; + sr.tableau_pile_count = 3; + sr.stock_size = 2; + sr.stock_deal_t = sdt::TABLEAU_PILES; + + game_state gs(sr, string_il{ + {}, {}, {}, {}, // The foundations + {"AC", "AD"}, // The stock + {"3H"}, {"5D"}, {"7C"} // The tableau piles + }); + vector<move> actual_moves = gs.get_legal_moves(); + + vector<move> exp_moves = { + move(move::mtype::stock_to_all_tableau, 0, 0, 2) // Special stock-to-tableau syntax + }; + + ASSERT_TRUE(test_helper::moves_eq(exp_moves, actual_moves)) << actual_moves; +} diff --git a/solvitaire/src/test/unit_tests/pile_test.cpp b/solvitaire/src/test/unit_tests/pile_test.cpp new file mode 100644 index 0000000..a5aeb66 --- /dev/null +++ b/solvitaire/src/test/unit_tests/pile_test.cpp @@ -0,0 +1,87 @@ +// +// Created by thecharlesblake on 1/11/18. +// + +#include <gtest/gtest.h> + +#include "../test_helper.h" +#include "../../main/game/pile.h" + +TEST(Pile, Size) { + pile p = {}; + ASSERT_EQ(0, p.size()); + + p = {"AS"}; + ASSERT_EQ(1, p.size()); + + p = {"AS", "KC", "4H"}; + ASSERT_EQ(3, p.size()); +} + +TEST(Pile, TopCard) { + pile p = {"AS"}; + ASSERT_EQ(card("AS"), p.top_card()); + + p = {"AS", "KC", "4H"}; + ASSERT_NE(card("AS"), p.top_card()); + ASSERT_EQ(card("4H"), p.top_card()); +} + +TEST(Pile, Index) { + pile p = {"AS"}; + ASSERT_EQ(card("AS"), p[0]); + + p = {"AS", "KC", "4H"}; + ASSERT_EQ(card("AS"), p[2]); + ASSERT_EQ(card("KC"), p[1]); + ASSERT_EQ(card("4H"), p[0]); +} + +TEST(Pile, Place) { + pile t1 = {}; + pile t2 = {"AS"}; + pile t3 = {"AS", "KC", "4H"}; + + pile p = {}; + ASSERT_EQ(p, t1); + + p.place("AS"); + ASSERT_NE(p, t1); + ASSERT_EQ(p, t2); + + p.place("KC"); + p.place("4H"); + ASSERT_NE(p, t2); + ASSERT_EQ(p, t3); +} + +TEST(Pile, Take) { + pile t1 = {}; + pile t2 = {"AS"}; + pile t3 = {"AS", "KC", "4H"}; + + pile p = {"AS", "KC", "4H"}; + ASSERT_EQ(p, t3); + + p.take(); + p.take(); + ASSERT_NE(p, t3); + ASSERT_EQ(p, t2); + + p.take(); + ASSERT_NE(p, t2); + ASSERT_EQ(p, t1); +} + +TEST(Pile, CompOperators) { + pile p1 = {"3S"}; + pile p2 = {"AS", "AD", "AC"}; + pile p3 = {"2S", "2D", "2C"}; + pile p4 = {"AS", "AD", "AC", "AH"}; + + ASSERT_LT(p1, p2); + ASSERT_LT(p2, p3); + ASSERT_LT(p3, p4); + ASSERT_LT(p1, p4); + ASSERT_EQ(p4, p4); +} |
