ttt_meta_session.cpp 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // Created by nositelshtanov on 11/11/2023.
  3. //
  4. #include "ttt_meta_session.h"
  5. void ttt_meta_session::play() {
  6. draw_map();
  7. while (!game.is_game_end()) {
  8. size_t x, y;
  9. auto whose_step = game.get_whose_step();
  10. auto map_number = game.get_next_map_number();
  11. try {
  12. if (map_number == ttt_meta::any_map) {
  13. std::cout << (whose_step == mark::zero ? META_O_INVITATION_TWO_PARAMS : META_X_INVITATION_TWO_PARAMS);
  14. std::cin >> x >> y;
  15. game.step(x, y);
  16. }
  17. else {
  18. std::cout << (whose_step == mark::zero ? META_O_INVITATION_ONE_PARAM : META_X_INVITATION_ONE_PARAM);
  19. std::cin >> x;
  20. game.step(game.get_next_map_number(), x);
  21. }
  22. } catch (const invalid_coords_error&) {
  23. std::cout << META_INVALID_COORS_HNDL << std::endl;
  24. continue;
  25. } catch (const step_error& err) {
  26. if (err.get_reason() == step_error::Reason::the_field_is_occupied) { std::cout << META_FIELD_IS_OCCUPIED_HNDL << std::endl; }
  27. else { throw; }
  28. }
  29. draw_map();
  30. }
  31. auto winner = game.get_winner();
  32. if (winner == mark::nothing) { std::cout << META_DRAW << std::endl; }
  33. else if (winner == mark::cross) { std::cout << META_CROSS_WIN << std::endl; }
  34. else { std::cout << META_ZERO_WIN << std::endl; }
  35. }
  36. void ttt_meta_session::draw_map() {
  37. std::size_t i = 0;
  38. print_devider();
  39. while (i < ttt_meta::map_size) {
  40. print_ln(i);
  41. if ((i + 1) % 3 == 0) { print_devider(); }
  42. ++i;
  43. }
  44. }
  45. void ttt_meta_session::print_ln(std::size_t fields_row) {
  46. const auto mapIdxStart = 3 * (fields_row / 3);
  47. const auto mapIdxEnd = mapIdxStart + 3;
  48. const auto fieldIdxStart = (3 * fields_row) % 9;
  49. const auto fieldIdxEnd = fieldIdxStart + 3;
  50. std::cout << META_MAP_BORDER;
  51. // no reason for avoid a nested loop
  52. for (std::size_t i{ mapIdxStart }; i < mapIdxEnd; ++i) {
  53. for (std::size_t j{ fieldIdxStart }; j < fieldIdxEnd; ++j) {
  54. auto cur_mark = game.get_mark(i, j);
  55. auto winner = game.get_mark(i).get_winner();
  56. if (winner == mark::nothing) {
  57. std::cout << (
  58. cur_mark == mark::cross ?
  59. META_MAP_CROSS :
  60. cur_mark == mark::zero ?
  61. META_MAP_ZERO :
  62. i == game.get_next_map_number() || game.get_next_map_number() == ttt_meta::any_map ?
  63. META_MAP_MAY_SELECT:
  64. META_MAP_NOTHING
  65. );
  66. } else if (winner == mark::cross) {
  67. std::cout << META_CROSS_FILL;
  68. } else {
  69. std::cout << META_ZERO_FILL;
  70. }
  71. }
  72. std::cout << META_MAP_BORDER;
  73. }
  74. std::cout << std::endl;
  75. }