adding timer to engine instead of separate thread

This commit is contained in:
DarthMooMancer
2025-11-12 01:30:32 -05:00
parent 67b13ab164
commit 09c2ff32e1
5 changed files with 11 additions and 21 deletions
-1
View File
@@ -7,7 +7,6 @@ project(pong)
set(SOURCES set(SOURCES
src/main.cpp src/main.cpp
src/engine.cpp src/engine.cpp
src/timer.cpp
) )
add_executable(pong ${SOURCES}) add_executable(pong ${SOURCES})
+3 -1
View File
@@ -2,6 +2,7 @@
#define ENGINE_HPP #define ENGINE_HPP
#include <array> #include <array>
#include <chrono>
#include <ncurses.h> #include <ncurses.h>
constexpr int ROW = 15; constexpr int ROW = 15;
@@ -43,12 +44,13 @@ public:
private: private:
Window win; Window win;
int time_seconds { 30 }; int clock { 30 };
vec2 score { 0, 0 }; vec2 score { 0, 0 };
vec2 ball { (COL / 2), (ROW / 2) }; vec2 ball { (COL / 2), (ROW / 2) };
vec2 ball_direction { 1, 1 }; vec2 ball_direction { 1, 1 };
Paddle p1 { { 1, (ROW / 2) - (SIZE / 2) } }; Paddle p1 { { 1, (ROW / 2) - (SIZE / 2) } };
Paddle p2 { { COL - 2, (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 exit_process();
bool process_input(); bool process_input();
-8
View File
@@ -1,8 +0,0 @@
#ifndef TIMER_HPP
#define TIMER_HPP
struct Timer {
void decrement_time(int &time, bool &running);
};
#endif
+8 -1
View File
@@ -52,6 +52,7 @@ Engine::Engine() {
noecho(); noecho();
curs_set(0); curs_set(0);
nodelay(stdscr, true); nodelay(stdscr, true);
last_clock_update = std::chrono::steady_clock::now();
} }
void Engine::on_collision_with_ball() { void Engine::on_collision_with_ball() {
@@ -82,7 +83,13 @@ void Engine::run() {
win.clear_display(); win.clear_display();
win.update_display(ball, p1, p2); win.update_display(ball, p1, p2);
win.draw_display(); 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<std::chrono::seconds>(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 std::this_thread::sleep_for(std::chrono::milliseconds(150)); // 1000 / fps; 200ms = 5fps
} }
} }
-10
View File
@@ -1,10 +0,0 @@
#include <thread>
#include <chrono>
#include "timer.hpp"
void Timer::decrement_time(int &time, bool &running) {
while (running) {
std::this_thread::sleep_for(std::chrono::seconds(1));
time--;
}
}