Skip to content

Instantly share code, notes, and snippets.

@glowiak
Created February 11, 2024 20:26
Show Gist options
  • Save glowiak/d98e8f6e7aed12af3e2504856cefcbfa to your computer and use it in GitHub Desktop.
Save glowiak/d98e8f6e7aed12af3e2504856cefcbfa to your computer and use it in GitHub Desktop.
Snake game in C/raylib in only 47 lines of code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <raylib.h>
#define TILE_SIZE 64
#define ROWS 15
#define COLS 10
static short foodPos[2], snakePos[2], snakeDirection = 0, lost = 0, gameRunCooldown = 0, snakePartTime[ROWS][COLS], creationPower = 2;
void main() {
srand(time(0));
InitWindow(ROWS * TILE_SIZE, COLS * TILE_SIZE, "Snake");
SetTargetFPS(10);
foodPos[0] = rand() % ROWS;
foodPos[1] = rand() % COLS;
snakePos[0] = (int)ROWS / 2;
snakePos[1] = (int)COLS / 2;
memset(snakePartTime, 0, sizeof(snakePartTime));
while (!WindowShouldClose()) {
if (gameRunCooldown == 2) {
snakePos[0] += snakeDirection == 0 ? 1 : (snakeDirection == 1 ? - 1 : 0);
snakePos[1] += snakeDirection == 2 ? 1 : (snakeDirection == 3 ? -1 : 0);
if (snakePartTime[snakePos[0]][snakePos[1]] > 0) lost = 1;
snakePartTime[snakePos[0]][snakePos[1]] = creationPower;
for (short i = 0; i < ROWS; i++) for (int j = 0; j < COLS; j++) snakePartTime[i][j] -= snakePartTime[i][j] > 0 ? 1 : 0;
gameRunCooldown = 0;
} gameRunCooldown++;
snakeDirection = IsKeyDown(KEY_LEFT) ? 1 : (IsKeyDown(KEY_RIGHT) ? 0 : (IsKeyDown(KEY_UP) ? 3 : (IsKeyDown(KEY_DOWN) ? 2 : snakeDirection)));
if (snakePos[0] < 0 || snakePos[1] < 0 || snakePos[0] >= ROWS || snakePos[1] >= COLS) lost = 1;
if (snakePos[0] == foodPos[0] && snakePos[1] == foodPos[1]) {
while (snakePartTime[foodPos[0]][foodPos[1]] > 0) {
foodPos[0] = rand() % ROWS;
foodPos[1] = rand() % COLS;
} creationPower++;
}
BeginDrawing();
ClearBackground(BLACK);
if (lost == 0) {
DrawRectangle(foodPos[0] * TILE_SIZE, foodPos[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE, RED);
for (short i = 0; i < ROWS; i++) for (int j = 0; j < COLS; j++) if (snakePartTime[i][j] > 0)
DrawRectangle(i * TILE_SIZE, j * TILE_SIZE, TILE_SIZE, TILE_SIZE, GREEN);
} else
DrawText("You lost", GetScreenWidth() / 2 - (MeasureText("You lost", 50) / 2), GetScreenHeight() / 2 - (MeasureText("You lost", 50) / 2), 50, RED);
EndDrawing();
}
CloseWindow();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment