Code & API Reference

This section details the exact schemas, tables, and scripts utilized in the project. It is intended for developers looking to modify or extend the codebase.

Database Schema

Input Table

This is the only physical table created by the project. It acts as the asynchronous communication bus between the external Python script and the internal SQL loop.

CREATE UNLOGGED TABLE IF NOT EXISTS Input (
    cmd char, 
    ts timestamp
);
  • cmd: A single character representing the desired action.
  • ts: The exact timestamp the command was issued, populated by clock_timestamp(). The SQL loop uses this to debounce inputs, ensuring a key held down for multiple frames isn't processed multiple times instantly.

Accepted cmd Values:

  • u - Rotate piece
  • d - Soft drop (move down faster)
  • l - Move left
  • r - Move right
  • s - Hard drop (instant drop)
  • p - Pause game

notify Function

A PlpgSQL wrapper required to expose the RAISE NOTICE command to standard SQL queries. This is the core rendering mechanism.

CREATE OR REPLACE FUNCTION notify(str varchar) RETURNS void AS $$
BEGIN
    RAISE NOTICE '%', str;
END
$$ LANGUAGE PLPGSQL;

Python Input Listener (input.py)

The Python script is a lightweight CLI tool. It connects to PostgreSQL using psycopg2 and runs an infinite loop capturing raw keyboard events.

Cross-Platform Keyboard Hooking

Standard Python input() requires the user to press Enter, which is useless for a real-time game. The script implements OS-specific low-level terminal hooks to capture unbuffered keystrokes.

Windows (msvcrt): Uses the Microsoft Visual C Run-Time library to capture raw bytes. Special handling is included for arrow keys, which emit a two-byte sequence (\x00 or \xe0 followed by the keycode).

Linux / MacOS (tty / termios): Uses POSIX terminal interfaces to set the stdin file descriptor to "raw" mode temporarily. This prevents the terminal from buffering the input until a newline is detected. It also includes regex-style mapping for ANSI escape sequences used by arrow keys (e.g., \x1b[A for Up).

Key Translation Map

Internally, the script normalizes WASD and Arrow Keys into a standard format before generating the SQL UPDATE statement.

keyTranslator = {
    "w": "up", 
    "a": "left", 
    "s": "down", 
    "d": "right", 
    " ": "space"
}

When a valid key is pressed, the script executes:

UPDATE Input SET cmd = %s, ts = clock_timestamp()
If the Input table does not exist (because the SQL query hasn't run yet), the script catches the psycopg2.errors.UndefinedTable exception, logs a warning, and continues listening.