Skip to content

Instantly share code, notes, and snippets.

@veganaize
Created February 18, 2024 22:52
Show Gist options
  • Save veganaize/e0b0a94a3a5a25ec3c354a257ece3822 to your computer and use it in GitHub Desktop.
Save veganaize/e0b0a94a3a5a25ec3c354a257ece3822 to your computer and use it in GitHub Desktop.
Snake; Raylib; 50 lines
#include "raylib.h"
int main() {
enum { TILE_SIZE=16, ROWS=30, COLS=20 };
int score = 0;
InitWindow(ROWS*TILE_SIZE, COLS*TILE_SIZE, "Snake");
SetTargetFPS(8);
struct { int row; int col; int h_velocity; int v_velocity; int length;
int body[ROWS][COLS]; }
snake = { (int)ROWS/2, (int)COLS/2, 1, 0, 2, { 0 } };
struct { int row; int col; }
food_position = { GetRandomValue(0, ROWS-1),
GetRandomValue(0, COLS-1) };
while (! WindowShouldClose()) {
switch (GetKeyPressed()) {
case KEY_RIGHT: snake.h_velocity = 1; snake.v_velocity = 0; break;
case KEY_LEFT: snake.h_velocity = -1; snake.v_velocity = 0; break;
case KEY_DOWN: snake.v_velocity = 1; snake.h_velocity = 0; break;
case KEY_UP: snake.v_velocity = -1; snake.h_velocity = 0; break;
} snake.row += snake.h_velocity; snake.col += snake.v_velocity;
BeginDrawing();
if (snake.row<0 || snake.col<0 || snake.row>=ROWS || snake.col>=COLS
|| snake.body[snake.row][snake.col] > 0)
break;
snake.body[snake.row][snake.col] = snake.length;
if (snake.row==food_position.row && snake.col==food_position.col) {
score += 100; snake.length++;
food_position.row = GetRandomValue(0, ROWS-1);
food_position.col = GetRandomValue(0, COLS-1);
}
ClearBackground(RAYWHITE); DrawRectangle(food_position.row * TILE_SIZE,
food_position.col * TILE_SIZE,
TILE_SIZE, TILE_SIZE, RED);
for (int i=0; i < ROWS; ++i) for (int j=0; j < COLS; ++j) {
DrawRectangleLines(i*TILE_SIZE, j*TILE_SIZE,
TILE_SIZE, TILE_SIZE, LIGHTGRAY);
snake.body[i][j] -= (snake.body[i][j] > 0) ? 1 : 0;
if (snake.body[i][j] > 0)
DrawRectangle(i * TILE_SIZE, j * TILE_SIZE,
TILE_SIZE, TILE_SIZE, GREEN);
}
DrawText(TextFormat("SCORE: %i", score),
TILE_SIZE, TILE_SIZE-2, 20, BLACK);
EndDrawing();
}
DrawText("GAME OVER!", GetScreenWidth()/2-MeasureText("GAME OVER!",40)/2,
COLS*TILE_SIZE/4, 40, RED); EndDrawing();
CloseWindow(); return 0;
}
@veganaize
Copy link
Author

MSVC compile with:

cl gdi32.lib kernel32.lib msvcrt.lib opengl32.lib raylib.lib shell32.lib user32.lib winmm.lib snake.c -Ic:\path\to\raylib\include /link /libpath:c:\path\to\raylib\lib /NODEFAULTLIB:libcmt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment