games: 60 fps rendering loop + smoother Snake controls

Both games now render at 60 fps independent of the game-logic step rate:
the main loop caps select() at one frame (16 ms) so the screen updates
smoothly even when gravity/snake steps are slow, and renders every frame
or whenever state changed.

Snake: replaced the turn queue with a single buffered direction (latest
keypress wins) so rapid key presses don't queue up and misfire. Base speed
set to 100 px/sec (~90 ms per step) for controllable, responsive play.
Progressive difficulty (+1 px/sec per 5 food) and edge wrap are unchanged.
This commit is contained in:
Luxferre committed 2026-10-24 08:43:39 +03:00
1 parent 0abf305dff
commit 9d4ca2e3a6
6 files changed
+52 -43

No files matched your search

+20 -8
View File
@@ -499,12 +499,19 @@ int main() {
render();
int xfd = ConnectionNumber(dpy);
const unsigned long FRAME_MS = 1000 / 60; // 60 fps rendering
unsigned long lastFrame = now_ms();
while (running) {
long until = (long)nextTick - (long)now_ms();
unsigned long now = now_ms();
long until = (long)nextTick - (long)now;
if (until < 0) until = 0;
// Never block select longer than one frame so the screen stays smooth
long wait = (until < (long)FRAME_MS) ? until : (long)FRAME_MS;
struct timeval tv;
tv.tv_sec = until / 1000;
tv.tv_usec = (until % 1000) * 1000;
tv.tv_sec = wait / 1000;
tv.tv_usec = (wait % 1000) * 1000;
fd_set fds;
FD_ZERO(&fds);
FD_SET(xfd, &fds);
@@ -516,17 +523,22 @@ int main() {
XNextEvent(dpy, &e);
handle_event(e);
if (!running) break;
dirty = true;
}
if (!running) break;
dirty = true;
}
if (running && now_ms() >= nextTick) {
now = now_ms();
if (running && now >= nextTick) {
if (state == PLAYING) step();
if (state == PLAYING) nextTick = now_ms() + speed;
else nextTick = now_ms() + 80;
if (state == PLAYING) nextTick = now + speed;
else nextTick = now + 80;
dirty = true;
}
if (dirty) render();
// Render at 60 fps or whenever state changed
if (dirty || now - lastFrame >= FRAME_MS) {
render();
lastFrame = now;
}
}
XFreeGC(dpy, gc);