A Snake game where all game logic runs inside PostgreSQL — movement, collisions, scoring — while Python handles rendering and keyboard input via curses.
Python (main.py) PostgreSQL
───────────────── ──────────────────────
curses → keyboard input ───→ UPDATE game_state SET direction
timer loop ───→ CALL tick()
render grid ←─── SELECT * FROM game_view
check game over ←─── SELECT game_over FROM game_state
- PostgreSQL — game state, movement logic, collision detection, scoring
- Python — terminal rendering, keyboard capture, game loop timer
| Tool | Purpose |
|---|---|
| PostgreSQL 13+ | Game logic — state, movement, collisions, scoring |
| Python 3.10+ | Rendering and keyboard input |
| Docker | Running PostgreSQL in a container |
| psycopg2 | PostgreSQL driver for Python |
| curses | Terminal rendering and keyboard capture |
| python-dotenv | Loading database credentials from db.env |
- Python 3.10+
- PostgreSQL 13+ (local or Docker)
- Python dependencies:
pip install psycopg2-binary python-dotenv windows-curses # windows-curses only on Windowsdocker run --name snake \
-e POSTGRES_PASSWORD=admin \
-p 5431:5432 \
-d postgresCreate a db.env file in the project root:
DB_HOST=localhost
DB_PORT=5431
DB_NAME=postgres
DB_USER=postgres
DB_PASSWORD=admin
db.envis listed in.gitignoreand will not be committed.
Connect to the database and run the setup file:
docker exec -it snake psql -U postgres -f snake_game.sqlOr paste the contents of snake_game.sql directly into your PostgreSQL client.
python main.py| Key | Action |
|---|---|
| ↑ | Move up |
| ↓ | Move down |
| ← | Move left |
| → | Move right |
snake/
├── main.py # Python client — rendering and input
├── snake_game.sql # PostgreSQL — all game logic
├── db.env # Database credentials (not committed)
├── .gitignore
└── README.md
snake_body -- ordered segments: head = MAX(id), tail = MIN(id)
food -- current food position, always 1 row
game_state -- direction, score, game_over flagEvery 150ms, Python calls CALL tick() which runs a single transaction:
- Calculate new head position based on current direction
- Check wall collision → set
game_over = trueif hit - Check body collision → set
game_over = trueif hit - Insert new head into
snake_body - If new head = food position → increment score, generate new food
- Otherwise → delete tail (snake moves forward)
A PostgreSQL view (game_view) renders the grid as text rows using generate_series and string_agg. Python reads the view and draws it with curses.addstr().
....................
..........*......... * = food
....................
........oooO........ O = head, o = body
....................
| Function | Type | Description |
|---|---|---|
init_game() |
PROCEDURE | Resets and initializes all tables |
generate_food() |
PROCEDURE | Places food in a random free cell |
tick() |
PROCEDURE | Advances the game by one step |
check_collision() |
FUNCTION | Detects wall collision |
check_collision_body() |
FUNCTION | Detects body collision |
check_collision_food() |
FUNCTION | Detects food collision |
game_view |
VIEW | Renders the 20×20 grid as text |
| Function | Description |
|---|---|
get_connection() |
Connects to PostgreSQL using db.env |
set_direction(direction) |
Updates direction in game_state |
tick() |
Calls CALL tick() and commits |
get_grid() |
Reads current grid from game_view |
is_game_over() |
Checks game_over flag |
get_score() |
Returns current score |
CREATE TABLE game_state (
id INT PRIMARY KEY DEFAULT 1,
CHECK (id = 1),
direction TEXT,
score INT DEFAULT 0,
game_over BOOL DEFAULT FALSE,
grid_size INT DEFAULT 20
);
CREATE TABLE food (
x INT,
y INT
);
CREATE TABLE snake_body (
id SERIAL PRIMARY KEY,
x INT,
y INT
);CREATE FUNCTION check_collision(head_x INT, head_y INT, grid_min INT, grid_max INT)
RETURNS BOOLEAN AS $$
BEGIN
RETURN head_x < grid_min OR head_x > grid_max OR head_y < grid_min OR head_y > grid_max;
END;
$$ LANGUAGE plpgsql;
CREATE FUNCTION check_collision_body(head_x INT, head_y INT)
RETURNS BOOLEAN AS $$
BEGIN
RETURN EXISTS (
SELECT 1 FROM snake_body WHERE x = head_x AND y = head_y
);
END;
$$ LANGUAGE plpgsql;
CREATE FUNCTION check_collision_food(head_x INT, head_y INT)
RETURNS BOOLEAN AS $$
BEGIN
RETURN EXISTS (
SELECT 1 FROM food WHERE x = head_x AND y = head_y
);
END;
$$ LANGUAGE plpgsql;CREATE OR REPLACE PROCEDURE generate_food()
LANGUAGE plpgsql AS $$
DECLARE
food_x INT;
food_y INT;
BEGIN
DELETE FROM food;
LOOP
food_x := trunc(random() * 20)::INT;
food_y := trunc(random() * 20)::INT;
EXIT WHEN NOT EXISTS (
SELECT 1 FROM snake_body WHERE x = food_x AND y = food_y
);
END LOOP;
INSERT INTO food (x, y) VALUES (food_x, food_y);
END;
$$;CREATE OR REPLACE PROCEDURE init_game()
LANGUAGE plpgsql AS $$
BEGIN
TRUNCATE game_state, food;
TRUNCATE snake_body RESTART IDENTITY;
INSERT INTO game_state (direction, score, game_over)
VALUES ('RIGHT', 0, false);
INSERT INTO snake_body (x, y)
VALUES (8, 10), (9, 10), (10, 10);
CALL generate_food();
END;
$$;CREATE OR REPLACE PROCEDURE tick()
LANGUAGE plpgsql AS $$
DECLARE
new_x INT;
new_y INT;
BEGIN
SELECT new_head.new_x, new_head.new_y INTO new_x, new_y
FROM (
SELECT
head.x + CASE gs.direction
WHEN 'RIGHT' THEN 1
WHEN 'LEFT' THEN -1
WHEN 'UP' THEN 0
WHEN 'DOWN' THEN 0
END AS new_x,
head.y + CASE gs.direction
WHEN 'RIGHT' THEN 0
WHEN 'LEFT' THEN 0
WHEN 'UP' THEN -1
WHEN 'DOWN' THEN 1
END AS new_y
FROM (
SELECT x, y FROM snake_body
WHERE id = (SELECT MAX(id) FROM snake_body)
) AS head
CROSS JOIN game_state gs
) AS new_head;
IF check_collision(new_x, new_y, 0, 19) THEN
UPDATE game_state SET game_over = true;
RETURN;
END IF;
IF check_collision_body(new_x, new_y) THEN
UPDATE game_state SET game_over = true;
RETURN;
END IF;
INSERT INTO snake_body (x, y) VALUES (new_x, new_y);
IF check_collision_food(new_x, new_y) THEN
UPDATE game_state SET score = score + 1;
CALL generate_food();
ELSE
DELETE FROM snake_body WHERE id = (SELECT MIN(id) FROM snake_body);
END IF;
END;
$$;CREATE VIEW game_view AS
SELECT
string_agg(
CASE
WHEN EXISTS (
SELECT 1 FROM snake_body
WHERE snake_body.x = coluna.cx
AND snake_body.y = linha.ly
AND id = (SELECT MAX(id) FROM snake_body)
) THEN 'O'
WHEN EXISTS (
SELECT 1 FROM snake_body
WHERE snake_body.x = coluna.cx
AND snake_body.y = linha.ly
) THEN 'o'
WHEN EXISTS (
SELECT 1 FROM food
WHERE food.x = coluna.cx
AND food.y = linha.ly
) THEN '*'
ELSE '.'
END, '' ORDER BY coluna.cx
) AS linha
FROM generate_series(0, 19) AS linha(ly)
CROSS JOIN generate_series(0, 19) AS coluna(cx)
GROUP BY linha.ly
ORDER BY linha.ly;- Direction reversal (e.g. RIGHT → LEFT) is not blocked — the snake can collide with itself instantly
curseson Windows requireswindows-cursesand may have limited Unicode support (emojis replaced with ASCII characters)- No high score persistence between sessions