I'm trying to make a simple snake game in C and OpenGL, and I have this at the moment, which runs almost perfectly:
#include "glad/glad.h"
#include <GLFW/glfw3.h>
#include "stb/stb_image.h"
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include "cglm/cglm.h"
#include "cglm/call.h"
#include "apple.h"
#include "snake.h"
struct Snake snake;
snakeDir dir;
void initSnake() {
dir = Up; //Initilize direction
snake.speed = 15;
snake.size = 1;
snake.body[0].x = -1.0f;
snake.body[0].y = -1.0f;
snake.head = snake.body[0];
snake.ticks = 0;
}
static void _drawSnake() {
snake.ticks++;
if (glfwGetKey(window.self, GLFW_KEY_UP) == GLFW_PRESS && dir != Down)
dir = Up;
if (glfwGetKey(window.self, GLFW_KEY_DOWN) == GLFW_PRESS && dir != Up)
dir = Down;
if (glfwGetKey(window.self, GLFW_KEY_LEFT) == GLFW_PRESS && dir != Right)
dir = Left;
if (glfwGetKey(window.self, GLFW_KEY_RIGHT) == GLFW_PRESS && dir != Left)
dir = Right;
if (snake.ticks == snake.speed) {
// Move the snake's head in the direction specified by the dir variable
switch(dir) {
case Up:
snake.head.y -= 2.0f;
break;
case Down:
snake.head.y += 2.0f;
break;
case Left:
snake.head.x -= 2.0f;
break;
case Right:
snake.head.x += 2.0f;
break;
}
// Move the snake's body
for (int i = snake.size - 1; i > 0; i--) {
snake.body[i] = snake.body[i-1];
}
snake.body[0] = snake.head;
// Reset ticks
snake.ticks = 0;
}
// Check if the snake eats an apple
if (snake.head.x == apple.x && snake.head.y == apple.y) {
// Generate a new apple
int rx = (rand() % (10 + 1 + 8) - 8);
int ry = (rand() % (10 + 1 + 8) - 8);
float ax = (rx + rx % 2) - 1.0f;
float ay = (ry + ry % 2) - 1.0f;
apple.x = ax;
apple.y = ay;
snake.size++;
}
// Check if the snake hits its own body
for (int i = 1; i < snake.size; i++) {
if (snake.head.x == snake.body[i].x && snake.head.y == snake.body[i].y) {
terminateWindow();
}
}
}
void renderSnake(struct Shader shader) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, snake.texture);
useShader(shader);
glBindVertexArray(snake.VAO);
for (int i = 0; i < snake.size; i++) {
glm_mat4_identity(camera.model); //Reset matrix
glm_rotate(camera.model, glm_rad(90.0f), (vec3) {1.0f, 0.0f, 0.0f});
glm_scale(camera.model, (vec3) {0.1, 0.1, 0.05}); //Construct second matrix
glm_translate(camera.model, (vec3) {snake.body[i].x, snake.body[i].y, -21.0f});
setShaderMat4(shader, "model", camera.model);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
}
_drawSnake();
}
The only problem is that whenever the snake collects an apple, it looks like the head of the snake or something flashes in the middle of the screen for a second then disappears. I tried tracking this bug down but I can't figure out what it's coming from. This is what it looks like:

Does anyone know what bug in my code is causing this? It's really quite annoying and any help is greatly appriciated!