From 15660182ef01827ea5c2277adfc467fa39ec57ef Mon Sep 17 00:00:00 2001 From: Tim Wundenberg Date: Fri, 20 Feb 2026 21:10:35 +0100 Subject: [PATCH] fast tick and automatic window size --- src/game.zig | 8 ++------ src/main.zig | 26 ++++++++++++++++++-------- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/src/game.zig b/src/game.zig index a2c11b2..77c1a59 100644 --- a/src/game.zig +++ b/src/game.zig @@ -40,11 +40,11 @@ pub const Game = struct { return self.body.items.len; } - pub fn createWithSize(allocator: std.mem.Allocator, bodySize: u8) !Game { + pub fn create(allocator: std.mem.Allocator) !Game { var body = try std.ArrayList(Vec2).initCapacity(allocator, 400); const startPos: u8 = 10; - for (0..bodySize) |i| { + for (0..3) |i| { const index = std.math.cast(i32, i) orelse unreachable; try body.append(allocator, Vec2{ startPos - index, 10 }); } @@ -64,10 +64,6 @@ pub const Game = struct { }; } - pub fn create(allocator: std.mem.Allocator) !Game { - return createWithSize(allocator, 3); - } - pub fn deinit(self: *Game) void { self.body.deinit(self.allocator); } diff --git a/src/main.zig b/src/main.zig index aa4eb46..ecc5602 100644 --- a/src/main.zig +++ b/src/main.zig @@ -10,17 +10,23 @@ pub fn main() anyerror!void { const allocator = std.heap.page_allocator; const scaleFactor = 20; - const screenWidth = 420; - const screenHeight = 420; - - rl.initWindow(screenWidth, screenHeight, "Snake"); - defer rl.closeWindow(); - rl.setTargetFPS(3); - var game = try g.Game.create(allocator); defer game.deinit(); + const screenWidth = (game.playFieldSize[0] + 1) * scaleFactor; + const screenHeight = (game.playFieldSize[1] + 1) * scaleFactor; + rl.initWindow(screenWidth, screenHeight, "Snake"); + defer rl.closeWindow(); + rl.setTargetFPS(60); + + const tickInterval: f32 = 0.5; + const fastTickInterval: f32 = tickInterval / 3.0; + var tickTimer: f32 = 0; + while (!rl.windowShouldClose()) { + const deltaTime = rl.getFrameTime(); + tickTimer += deltaTime; + rl.beginDrawing(); defer rl.endDrawing(); @@ -39,7 +45,11 @@ pub fn main() anyerror!void { game.setDirection(g.Direction.left); } - try game.tick(); + const currentInterval = if (rl.isKeyDown(.s)) fastTickInterval else tickInterval; + if (tickTimer >= currentInterval) { + tickTimer -= currentInterval; + try game.tick(); + } // Border const fieldWidth = game.playFieldSize[0] * scaleFactor + scaleFactor;