ref: a5d2874ffb9c29eeec3a6fd430e21bbc93ae0948 snake-zig/src/game_state.zig -rw-r--r-- 8.7 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
const std = @import("std");
const panic = std.debug.panic;
const root = @import("root");
const c = @import("c.zig");
const Allocator = std.mem.Allocator;
const c_allocator = std.heap.c_allocator;
const Spritesheet = @import("spritesheet.zig").Spritesheet;
const AllShaders = @import("shaders.zig").AllShaders;
const glm = @import("glmath.zig");
const Vec = glm.Vec;
const Mat4 = glm.Mat4;
const Snake = @import("snake.zig").Snake;
const Key = @import("key.zig").Key;
const Context = @import("context.zig").Context;
const graphics = @import("graphics.zig");

pub const State = union(enum) {
    Playing: PlayingState,
    MainMenu: MainMenuState,
    Paused: PausedState,
    GameOver: GameOverState,

    fn handleKey(state: *State, ctx: *Context, key: Key) ?State {
        switch (state.*) {
            .Playing => |*s| {
                switch (key) {
                    .Up => s.snake.next_move = .Up,
                    .Down => s.snake.next_move = .Down,
                    .Left => s.snake.next_move = .Left,
                    .Right => s.snake.next_move = .Right,
                    .Escape => return State{ .Paused = PausedState{ .playing_state = PlayingState.copy(s) } },
                    else => {},
                }
                return null;
            },
            .MainMenu => |*s| switch (key) {
                .Space => return State{ .Playing = PlayingState.init(c_allocator, ctx) },
                .Escape => {
                    c.glfwSetWindowShouldClose(ctx.window, c.GL_TRUE);
                    return null;
                },
                else => return null,
            },
            .GameOver => |*s| switch (key) {
                .Space => return State{ .Playing = PlayingState.init(c_allocator, ctx) },
                .Escape => return State{ .MainMenu = MainMenuState{ .time = 0.0 } },
                else => return null,
            },
            .Paused => |*s| switch (key) {
                .Escape => return State{ .Playing = s.playing_state },
                .Space => return State{ .MainMenu = MainMenuState{ .time = 0.0 } },
                else => return null,
            },
        }
    }

    fn update(state: *State, ctx: *Context) anyerror!?State {
        switch (state.*) {
            .Playing => |*s| return s.update(ctx),
            else => return null,
        }
    }

    fn draw(state: *State, ctx: *Context) void {
        switch (state.*) {
            .Playing => |*s| s.draw(ctx),
            .MainMenu => |*s| s.draw(ctx),
            .Paused => |*s| s.draw(ctx),
            .GameOver => |*s| s.draw(ctx),
        }
    }

    fn deinit(state: *State) void {
        switch (state.*) {
            .Playing => |*s| s.deinit(),
            else => {},
            // .Paused => |*s| s.deinit(),
            // .GameOver => |*s| s.deinit(),
        }
    }
};

pub const PlayingState = struct {
    snake: Snake,
    apple_pos: GridPos,
    tick_rate: f64,
    until_tick: f64,

    pub fn init(alloc: *Allocator, ctx: *Context) PlayingState {
        const snake = Snake.init(
            GridPos{
                .x = ctx.grid_width / 2,
                .y = ctx.grid_height / 2,
            },
            alloc,
        ) catch {
            panic("Not enough memory for the snake!");
        };
        const apple_pos = GridPos{
            .x = ctx.prng.random.int(usize) % ctx.grid_width,
            .y = ctx.prng.random.int(usize) % ctx.grid_height,
        };
        const tick_rate = 0.4;
        const until_tick = 0.0;

        return PlayingState{
            .snake = snake,
            .apple_pos = apple_pos,
            .tick_rate = tick_rate,
            .until_tick = until_tick,
        };
    }

    // should realloc snake, but not needed for what we are using this for
    pub fn copy(state: *PlayingState) PlayingState {
        return PlayingState {
            .snake = state.snake,
            .apple_pos = state.apple_pos,
            .tick_rate = state.tick_rate,
            .until_tick = state.until_tick,
        };
    }

    pub fn update(self: *PlayingState, ctx: *Context) !?State {
        self.until_tick -= ctx.dt;
        if (self.until_tick <= 0.0) {
            self.until_tick = self.tick_rate;
            return self.tick(ctx);
        } else {
            return null;
        }
    }

    fn tick(self: *PlayingState, ctx: *Context) !?State {
        try self.snake.move(ctx.grid_width, ctx.grid_height);
        for (self.snake.tail.toSlice()) |seg| {
            if (self.snake.head_pos.equal(seg.pos)) {
                return State{ .GameOver = GameOverState{ .score = self.snake.tail.count() } };
            }
        }
        if (self.snake.head_pos.equal(self.apple_pos)) {
            self.snake.add_segment = true;
            self.apple_pos = GridPos{
                .x = ctx.prng.random.int(usize) % ctx.grid_width,
                .y = ctx.prng.random.int(usize) % ctx.grid_height,
            };
            self.tick_rate /= 1.01;
        }
        return null;
    }

    pub fn draw(self: *PlayingState, ctx: *Context) void {
        const scale = glm.vec3_from_vec2(ctx.tile_size.scaled(1.0 / 8.0));
        const screenpos = self.apple_pos.to_screen_pos(ctx.tile_size);
        const model = Mat4.identity.translate(glm.vec3_from_vec2(screenpos)).scale(scale);
        ctx.gfx.draw(.Snake, @enumToInt(SpriteIdx.Apple), model);
        self.snake.draw(&ctx.gfx, ctx.tile_size);
    }

    pub fn deinit(self: *PlayingState) void {
        self.snake.deinit();
    }
};

pub const MainMenuState = struct {
    time: f64,

    pub fn draw(state: *MainMenuState, ctx: *Context) void {
        graphics.drawCenteredText(&ctx.gfx, "Snake!", -2, 6.0);
        graphics.drawCenteredText(&ctx.gfx, "Press Space to Play", 1, 5.0);
        graphics.drawCenteredText(&ctx.gfx, "Press Escape to Quit", 2, 5.0);
    }
};

pub const GameOverState = struct {
    score: usize,

    pub fn draw(state: *GameOverState, ctx: *Context) void {
        const out_string = std.fmt.allocPrint(c_allocator, "Your snake was {} segments long.", state.score) catch {
            panic("out of memory!");
        };
        graphics.drawCenteredText(&ctx.gfx, "Game Over!", -1, 6.0);
        graphics.drawCenteredText(&ctx.gfx, out_string, 0, 4.0);
        graphics.drawCenteredText(&ctx.gfx, "Press space to play again.", 2, 4.0);
        graphics.drawCenteredText(&ctx.gfx, "Press escape to return to the main menu", 3, 4.0);
    }
};

pub const PausedState = struct {
    playing_state: PlayingState,

    pub fn draw(state: *PausedState, ctx: *Context) void {
        state.playing_state.draw(ctx);
        graphics.drawCenteredText(&ctx.gfx, "Paused", -1, 6.0);
        graphics.drawCenteredText(&ctx.gfx, "Press escape to resume", 1, 4.0);
        graphics.drawCenteredText(&ctx.gfx, "Press space to go to the main menu", 2, 4.0);
    }
};

pub const SpriteIdx = enum(u4) {
    CornerUR = 0,
    CornerRD = 1,
    CornerDL = 2,
    CornerLU = 3,
    TailR = 4,
    TailD = 5,
    TailL = 6,
    TailU = 7,
    SegmentH = 8,
    SegmentV = 9,
    HeadR = 10,
    HeadD = 11,
    HeadL = 12,
    HeadU = 13,
    Apple = 14,
};

pub const Direction = enum {
    const Self = @This();

    Up,
    Down,
    Left,
    Right,

    pub fn opposite(self: Self, other: Self) bool {
        return switch (self) {
            .Up => other == .Down,
            .Down => other == .Up,
            .Left => other == .Right,
            .Right => other == .Left,
        };
    }

    pub fn init_opposite(self: Self) Self {
        return switch (self) {
            .Up => Self.Down,
            .Down => Self.Up,
            .Left => Self.Right,
            .Right => Self.Left,
        };
    }
};

pub const GridPos = struct {
    const Self = @This();

    x: usize,
    y: usize,

    pub fn equal(self: Self, other: Self) bool {
        return self.x == other.x and self.y == other.y;
    }

    pub fn to_screen_pos(self: Self, grid_tile_size: Vec(2)) Vec(2) {
        const x = @intToFloat(f32, self.x) * grid_tile_size.data[0];
        const y = @intToFloat(f32, self.y) * grid_tile_size.data[1];
        return glm.vec2(x, y);
    }

    pub fn wrapping_move(self: *Self, direction: Direction, max_x: usize, max_y: usize) void {
        switch (direction) {
            .Up => {
                if (self.y == 0) {
                    self.y = max_y;
                }
                self.y -= 1;
            },
            .Down => {
                self.y += 1;
                if (self.y == max_y) {
                    self.y = 0;
                }
            },
            .Left => {
                if (self.x == 0) {
                    self.x = max_x;
                }
                self.x -= 1;
            },
            .Right => {
                self.x += 1;
                if (self.x == max_x) {
                    self.x = 0;
                }
            },
        }
    }
};