ttt_engine.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //
  2. // Created by nositelshtanov on 11/11/2023.
  3. //
  4. #include "ttt_engine.h"
  5. ttt_engine::ttt_engine() : map{
  6. mark::nothing, mark::nothing, mark::nothing,
  7. mark::nothing, mark::nothing, mark::nothing,
  8. mark::nothing, mark::nothing, mark::nothing
  9. },
  10. winner(mark::nothing),
  11. step_count(0),
  12. win_combinations{
  13. 0, 1, 2,
  14. 3, 4, 5,
  15. 6, 7, 8,
  16. 0, 3, 6,
  17. 1, 4, 7,
  18. 2, 5, 8,
  19. 2, 4, 6,
  20. 0, 4, 8
  21. } {}
  22. void ttt_engine::step(mark whose_step, std::size_t field_num) {
  23. if (winner != mark::nothing || is_game_end()) { throw step_error{"game is end", step_error::Reason::game_already_end}; }
  24. if (map[field_num] != mark::nothing) { throw step_error{step_error::Reason::the_field_is_occupied}; }
  25. if (field_num > 8) { throw invalid_coords_error(); }
  26. map[field_num] = whose_step;
  27. ++step_count;
  28. winner = who_is_winner();
  29. if (winner != mark::nothing) { whose_step = mark::nothing; }
  30. }
  31. mark ttt_engine::who_is_winner() const {
  32. for (combination comb : win_combinations) {
  33. if (is_same_marks(map[comb[0]], map[comb[1]], map[comb[2]]) && map[comb[0]] != mark::nothing) {
  34. return map[comb[0]];
  35. }
  36. }
  37. return mark::nothing;
  38. }