So, I'm trying to make a simple snake game in C with raylib, and after adding the ability to eat apples, basically everything breaks. The way I'm doing this, is there is an array of Vector2s that give the position of every square of the snake, which gets rendered to a 20x20 grid. Here's the code, It's kinda spaghetti bc I'm a bad programmer, but I hope somebody can help me out.
#include <stdlib.h>
#include <time.h>
#include <raylib.h>
#define WIDTH 1080
#define HEIGHT 1080
#define FPS 4
#define GRIDSIZE 20
int main()
{
// Random Numbers
srand(time(NULL));
// Define locations
Vector2 playerLoc[10] = {(Vector2) {rand() % GRIDSIZE, rand() % GRIDSIZE}};
Vector2 appleLoc = (Vector2) {rand() % GRIDSIZE, rand() % GRIDSIZE};
// Player Score
int score = 0;
// Define Direction
Vector2 playerDir = (Vector2) {1, 0};
// With of Grid Squares
int gridSize = HEIGHT / GRIDSIZE;
// Initialization
InitWindow(WIDTH, HEIGHT, "Snake Game Test");
SetTargetFPS(FPS);
while (!WindowShouldClose())
{
// Update Variables Here
if (IsKeyPressed('D') || IsKeyPressed('A'))
{
playerDir.x = (int) IsKeyPressed('D') - (int) IsKeyPressed('A');
playerDir.y = 0.0f;
}
else if (IsKeyPressed('S') || IsKeyPressed('W'))
{
playerDir.y = (int) IsKeyPressed('S') - (int) IsKeyPressed('W');
playerDir.x = 0;
}
for (int i = 0; i <= score; i++)
{
playerLoc[i].x += playerDir.x;
playerLoc[i].y += playerDir.y;
}
if (playerLoc[0].x < 0)
break;
else if (playerLoc[0].x >= 1080)
break;
else if (playerLoc[0].y < 0)
break;
else if (playerLoc[0].y >= 1080)
break;
if (playerLoc[0].x == appleLoc.x && playerLoc[0].y == appleLoc.y)
{
appleLoc = (Vector2) {rand() % GRIDSIZE, rand() % GRIDSIZE};
score++;
playerLoc[score].x = playerLoc[score - 1].x + (playerDir.x * -1);
playerLoc[score].y = playerLoc[score - 1].y + (playerDir.y * -1);
}
// Draw
BeginDrawing();
ClearBackground(RAYWHITE);
for (int i = 0; i < GRIDSIZE; i++)
{
for (int j = 0; j < GRIDSIZE; j++)
{
for (int k = 0; k <= score; k++)
{
if (i == playerLoc[k].x && j == playerLoc[k].y)
DrawRectangle(i * gridSize, j * gridSize, gridSize, gridSize, BLACK);
}
if (i == appleLoc.x && j == appleLoc.y)
{
DrawRectangle(i * gridSize, j * gridSize, gridSize, gridSize, RED);
}
}
}
EndDrawing();
// Update Late Variables Here
}
// De-Initialization
CloseWindow();
return 0;
}