ttt_engine.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // Created by nositelshtanov on 11/11/2023.
  3. //
  4. #ifndef TTT_TTT_ENGINE_H
  5. #define TTT_TTT_ENGINE_H
  6. #include <array>
  7. #include <stdexcept>
  8. enum class mark {
  9. nothing,
  10. zero,
  11. cross
  12. };
  13. class invalid_coords_error: public std::runtime_error {
  14. public:
  15. invalid_coords_error(): std::runtime_error("") {}
  16. explicit invalid_coords_error(const char* msg): std::runtime_error(msg) {}
  17. };
  18. class step_error: public std::runtime_error {
  19. public:
  20. enum Reason {
  21. game_already_end,
  22. the_field_is_occupied
  23. };
  24. explicit step_error(Reason reason): std::runtime_error(""), reason(reason) {}
  25. step_error(const char* msg, Reason reason): std::runtime_error(msg), reason(reason) {}
  26. Reason get_reason() const { return reason; }
  27. private:
  28. Reason reason;
  29. };
  30. class ttt_engine {
  31. public:
  32. using combination = std::array<std::size_t, 3>;
  33. using ttt_map = std::array<mark, 9>;
  34. const std::array<combination, 8> win_combinations;
  35. ttt_engine();
  36. mark get_mark(std::size_t field) const { return map[field]; }
  37. mark get_winner() const { return winner; }
  38. void step(mark whose_step, std::size_t field_num);
  39. bool is_game_end() const { return step_count >= 9 || winner != mark::nothing; }
  40. protected:
  41. static bool is_same_marks(mark m1, mark m2, mark m3) { return m1 == m2 && m1 == m3 && m2 == m3; }
  42. mark who_is_winner() const;
  43. private:
  44. ttt_map map;
  45. mark winner;
  46. int step_count;
  47. };
  48. #endif //TTT_TTT_ENGINE_H