ref: a5d2874ffb9c29eeec3a6fd430e21bbc93ae0948 snake-zig/src/main.zig -rw-r--r-- 2.0 KiB View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const std = @import("std");
const ArrayList = std.ArrayList;
const c = @import("c.zig");
const panic = std.debug.panic;
const AllShaders = @import("shaders.zig").AllShaders;
const Spritesheet = @import("spritesheet.zig").Spritesheet;
const State = @import("game_state.zig").State;
const PlayingState = @import("game_state.zig").PlayingState;
const MainMenuState = @import("game_state.zig").MainMenuState;
const c_allocator = std.heap.c_allocator;
const graphics = @import("graphics.zig");
const Context = @import("context.zig").Context;
const Key = @import("key.zig").Key;

// global for the callback
var pressed_keys: ArrayList(Key) = ArrayList(Key).init(c_allocator);
extern fn keyCallback(window: ?*c.GLFWwindow, glfw_key: c_int, scancode: c_int, action: c_int, mods: c_int) void {
    if (action != c.GLFW_PRESS) return;
    if (Key.fromGLFW(glfw_key)) |key| {
        pressed_keys.append(key) catch panic("Ran out of memory!");
    }
}

const default_grid_width = 8;
const default_grid_height = 8;
const default_window_width = 800;
const default_window_height = 800;

pub fn main() anyerror!void {
    var ctx = Context.init(8, 8, 800, 800);
    defer ctx.deinit();
    _ = c.glfwSetKeyCallback(ctx.window, keyCallback);

    var game_state = State{ .MainMenu = MainMenuState{ .time = 0.0 } };
    defer game_state.deinit();

    c.glClearColor(0.2, 0.4, 0.3, 1.0);

    var prev_time = c.glfwGetTime();
    while (c.glfwWindowShouldClose(ctx.window) == c.GL_FALSE) {
        c.glClear(c.GL_COLOR_BUFFER_BIT | c.GL_DEPTH_BUFFER_BIT | c.GL_STENCIL_BUFFER_BIT);
        const now = c.glfwGetTime();
        ctx.dt = now - prev_time;
        prev_time = now;

        for (pressed_keys.toSlice()) |key| if (game_state.handleKey(&ctx, key)) |state| {
            game_state = state;
        };
        pressed_keys.shrink(0);

        if (try game_state.update(&ctx)) |state| {
            game_state = state;
        }
        game_state.draw(&ctx);
        c.glfwSwapBuffers(ctx.window);
        c.glfwPollEvents();
    }
}