Skip to content
danjourPublic

About

Snake game where all logic runs inside PostgreSQL, movement, collisions and scoring are handled by stored procedures and functions. Python handles only rendering and keyboard input via curses.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🐍 Snake Game — PostgreSQL + Python

A Snake game where all game logic runs inside PostgreSQL — movement, collisions, scoring — while Python handles rendering and keyboard input via curses.


Architecture

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

Built with

PostgreSQL Python Docker

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

Requirements

  • Python 3.10+
  • PostgreSQL 13+ (local or Docker)
  • Python dependencies:
pip install psycopg2-binary python-dotenv windows-curses  # windows-curses only on Windows

Setup

1. PostgreSQL with Docker

docker run --name snake \
  -e POSTGRES_PASSWORD=admin \
  -p 5431:5432 \
  -d postgres

2. Configure environment

Create a db.env file in the project root:

DB_HOST=localhost
DB_PORT=5431
DB_NAME=postgres
DB_USER=postgres
DB_PASSWORD=admin

db.env is listed in .gitignore and will not be committed.

3. Run the SQL setup

Connect to the database and run the setup file:

docker exec -it snake psql -U postgres -f snake_game.sql

Or paste the contents of snake_game.sql directly into your PostgreSQL client.

4. Run the game

python main.py

Controls

Key Action
↑ Move up
↓ Move down
← Move left
→ Move right

Project structure

snake/
├── main.py          # Python client — rendering and input
├── snake_game.sql   # PostgreSQL — all game logic
├── db.env           # Database credentials (not committed)
├── .gitignore
└── README.md

How it works

State (PostgreSQL tables)

snake_body   -- ordered segments: head = MAX(id), tail = MIN(id)
food         -- current food position, always 1 row
game_state   -- direction, score, game_over flag

Each frame (tick)

Every 150ms, Python calls CALL tick() which runs a single transaction:

  1. Calculate new head position based on current direction
  2. Check wall collision → set game_over = true if hit
  3. Check body collision → set game_over = true if hit
  4. Insert new head into snake_body
  5. If new head = food position → increment score, generate new food
  6. Otherwise → delete tail (snake moves forward)

Rendering

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
....................

SQL functions

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

Python functions

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

SQL setup (snake_game.sql)

Tables

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
);

Collision functions

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;

Generate food

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;
$$;

Initialize game

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;
$$;

Tick — one game step

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;
$$;

Game view

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;

Known limitations

  • Direction reversal (e.g. RIGHT → LEFT) is not blocked — the snake can collide with itself instantly
  • curses on Windows requires windows-curses and may have limited Unicode support (emojis replaced with ASCII characters)
  • No high score persistence between sessions

About

Snake game where all logic runs inside PostgreSQL, movement, collisions and scoring are handled by stored procedures and functions. Python handles only rendering and keyboard input via curses.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages