From 09c2ff32e1f059b669910e4d7b2e3a4b6363f7ce Mon Sep 17 00:00:00 2001 From: DarthMooMancer <107283522+DarthMooMancer@users.noreply.github.com> Date: Wed, 12 Nov 2025 01:30:32 -0500 Subject: [PATCH] adding timer to engine instead of separate thread --- CMakeLists.txt | 1 - include/engine.hpp | 4 +++- include/timer.hpp | 8 -------- src/engine.cpp | 9 ++++++++- src/timer.cpp | 10 ---------- 5 files changed, 11 insertions(+), 21 deletions(-) delete mode 100644 include/timer.hpp delete mode 100644 src/timer.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index cf4d062..55cfd86 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,7 +7,6 @@ project(pong) set(SOURCES src/main.cpp src/engine.cpp - src/timer.cpp ) add_executable(pong ${SOURCES}) diff --git a/include/engine.hpp b/include/engine.hpp index 957ec76..34640d0 100644 --- a/include/engine.hpp +++ b/include/engine.hpp @@ -2,6 +2,7 @@ #define ENGINE_HPP #include +#include #include constexpr int ROW = 15; @@ -43,12 +44,13 @@ public: private: Window win; - int time_seconds { 30 }; + int clock { 30 }; vec2 score { 0, 0 }; vec2 ball { (COL / 2), (ROW / 2) }; vec2 ball_direction { 1, 1 }; Paddle p1 { { 1, (ROW / 2) - (SIZE / 2) } }; Paddle p2 { { COL - 2, (ROW / 2) - (SIZE / 2) } }; + std::chrono::steady_clock::time_point last_clock_update; bool exit_process(); bool process_input(); diff --git a/include/timer.hpp b/include/timer.hpp deleted file mode 100644 index e087cdd..0000000 --- a/include/timer.hpp +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef TIMER_HPP -#define TIMER_HPP - -struct Timer { - void decrement_time(int &time, bool &running); -}; - -#endif diff --git a/src/engine.cpp b/src/engine.cpp index 0c71e6c..b78e6b7 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -52,6 +52,7 @@ Engine::Engine() { noecho(); curs_set(0); nodelay(stdscr, true); + last_clock_update = std::chrono::steady_clock::now(); } void Engine::on_collision_with_ball() { @@ -82,7 +83,13 @@ void Engine::run() { win.clear_display(); win.update_display(ball, p1, p2); win.draw_display(); - std::cout << "Time left: " << time_seconds << ", Score ( " << score.a << " : " << score.b << " )\n"; + auto current_time = std::chrono::steady_clock::now(); + auto elapsed_time = std::chrono::duration_cast(current_time - last_clock_update).count(); + if(elapsed_time >= 1) { + clock -= elapsed_time; + last_clock_update = current_time; + } + std::cout << "Time left: " << clock << ", Score ( " << score.a << " : " << score.b << " )\n"; std::this_thread::sleep_for(std::chrono::milliseconds(150)); // 1000 / fps; 200ms = 5fps } } diff --git a/src/timer.cpp b/src/timer.cpp deleted file mode 100644 index 326f3e2..0000000 --- a/src/timer.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include -#include -#include "timer.hpp" - -void Timer::decrement_time(int &time, bool &running) { - while (running) { - std::this_thread::sleep_for(std::chrono::seconds(1)); - time--; - } -}