A classic Snake game implementation in C with SDL3, featuring both human-playable and AI-controlled modes. Inspired by this video.
- Person Mode: Play the game yourself using keyboard controls
- Machine Mode: Watch the AI play using BFS plus a longest-path fallback
- SDL3 graphical versions and terminal versions of both modes(fully made by Opus 5)
- Customizable grid size
- Circular queue-based snake body management
Snake_algorithms/
├── include/
│ ├── const.h # Game constants (grid size, window, speed)
│ ├── circular_queue.h # Circular queue used for the snake body and BFS
│ ├── game.h # GameState and game rules
│ ├── ai.h # AI decision (next_direction)
│ └── sdl_game.h # SDL front-end switch (sdl_autopilot)
├── src/
│ ├── circular_queue.c
│ ├── game.c # Init, apple generation, movement, win/lose
│ ├── ai.c # BFS, longest path, safety check
│ ├── sdl_game.c # SDL window, input and drawing (shared by both modes)
│ ├── person/
│ │ ├── snake.c # Terminal person mode
│ │ └── snake_ui.c # SDL person mode (sdl_autopilot = false)
│ └── machine/
│ ├── snake.c # Terminal machine mode
│ └── snake_ui.c # SDL machine mode (sdl_autopilot = true)
├── CMakeLists.txt
└── algorithm.md # Longest-path algorithm notes
The game rules and the AI live in one place (game.c and ai.c) and every executable reuses them. Both SDL executables share sdl_game.c; the only difference is whether the keyboard or the AI chooses the direction.
- CMake 3.16 or higher
- SDL3 library
- C11 compiler (GCC, Clang, etc.)
cmake -S . -B build
cmake --build buildThe executables are built in build/bin/:
| Executable | Mode |
|---|---|
snake_person |
Human player, SDL |
snake_machine |
AI, SDL |
snake_person_console |
Human player, terminal |
snake_machine_console |
AI, terminal |
./build/bin/snake_person
./build/bin/snake_machine
./build/bin/snake_person_console
./build/bin/snake_machine_consoleControls:
- SDL person mode: arrow keys. Only one turn per tick; reversing is ignored.
- Terminal person mode: type
w,a,sordand press Enter.
The terminal versions print the board every step: 0 empty, 1 snake, 2 apple.
Edit include/const.h:
ROWSandCOLUMNS- Grid dimensionsWIDTHandHEIGHT- Window sizeTIMER- SDL game speed in millisecondsPADDING- Visual padding around the grid
Then rebuild with cmake --build build.