diff --git a/include/engine.hpp b/include/engine.hpp index a9cd18f..552a7e6 100644 --- a/include/engine.hpp +++ b/include/engine.hpp @@ -2,21 +2,20 @@ #include #include +#include class Engine { public: Engine(); - ~Engine(); + ~Engine() { endwin(); } void run(); private: + char p1 { 'x' }, p2 { 'o' }, temp { p1 }; std::string status; std::array view; void draw_display() const; - char p1 { 'x' }; - char p2 { 'o' }; - char temp { p1 }; - bool process_input(); - bool check_game_over(); bool check_line(char id) const; + bool update_status(); + bool process_input(); }; diff --git a/src/engine.cpp b/src/engine.cpp index 765a3d9..74a494e 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -1,8 +1,6 @@ #include #include -#include #include -#include #include Engine::Engine() { @@ -14,16 +12,13 @@ Engine::Engine() { view.fill(' '); } -Engine::~Engine() { endwin(); } - void Engine::run() { - while (process_input()) { - bool game_over = check_game_over(); - if(!game_over) { status = "Current Player: " + std::string(1, temp) + "\n"; } + bool game_over; + do { + game_over = update_status(); draw_display(); refresh(); - if(game_over) { break; } - } + } while(!game_over && process_input()); mvprintw(7, 0, "Press any key to quit."); nodelay(stdscr, false); @@ -40,10 +35,11 @@ void Engine::draw_display() const { mvprintw(6, 0, "%s", status.c_str()); } -bool Engine::check_game_over() { +bool Engine::update_status() { if(check_line(p1)) { return status = "Game Over! Player 1 wins!", true; } if(check_line(p2)) { return status = "Game Over! Player 2 wins!", true; } if(std::ranges::count(view, ' ') == 0) { return status = "Game Over! It's a tie!", true; } + status = "Current Player: " + std::string(1, temp) + "\n"; return false; } @@ -55,25 +51,23 @@ bool Engine::process_input() { if(ch == 'q') { return false; } if(ch < '1' || ch > '9') continue; index = ch - '1'; - if(view[index] == ' ') { - view[index] = temp; - temp = (temp == p1) ? p2 : p1; - } + if(view[index] != ' ') continue; + view[index] = temp; + temp = (temp == p1) ? p2 : p1; } if(!hit) { std::this_thread::sleep_for(std::chrono::milliseconds(150)); } return true; } +constexpr std::array, 8> wins = {{ + {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, + {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, + {0, 4, 8}, {2, 4, 6} +}}; + bool Engine::check_line(char id) const { - static constexpr std::array, 8> wins = {{ - {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, - {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, - {0, 4, 8}, {2, 4, 6} - }}; for(const auto& i : wins) { - if(view[i[0]] == id && view[i[1]] == id && view[i[2]] == id) { - return true; - } + if(view[i[0]] == id && view[i[1]] == id && view[i[2]] == id) { return true; } } return false; } diff --git a/src/main.cpp b/src/main.cpp index 043e932..89a9239 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3,5 +3,4 @@ int main() { Engine engine; engine.run(); - return 0; }