Falling Tetromino Engine

May 4, 2026 · View on GitHub

Crates.io Documentation License

A tetromino stacker engine in Rust, with the goals of being featureful, efficient and elegant.

Installation

Run cargo add falling-tetromino-engine.

Most engine types support Serialization through serde, available with the corresponding feature flag:

[dependencies]
falling-tetromino-engine = { version = "X.Y.Z", features = ["serde"] }

Simple Example

use falling_tetromino_engine::*;

// Initialize a game. In-game time starts at 0s.
let mut game = Game::builder()
    .seed(1234)
    /* Further customization possible here. */
    .build();

// Update the game with info that 'left' is activated at second 4.2 (i.e. piece starts moving left).
let input = Input::Activate(Button::MoveLeft);
game.update(InGameTime::from_secs_f64(4.2), Some(input));

// Update the game with info that no input changes up to second 6.79 (e.g. piece falls).
game.update(InGameTime::from_secs_f64(6.79), None);

// Read game state (for rendering etc.)
let State { board, .. } = game.state();

Features Overview

Fundamental points to note:

  • The engine implements the pure game logic/backend, i.e. it accurately and only simulates a virtual board with tetromino pieces spawning/moving/locking, lines clearing etc.
  • The engine is frontend-agnostic and by itself does not prescribe how to interact with the real world player (it does not know about the keyboard, refresh-/framerate etc.)

Internally, the game processes a pure timeline like so:

Piece spawns              e.g. Game state viewed here
|        Piece falls                  |
|        |       Piece falls          |
v        v       v                    v
|--------¦--|----¦-------¦-------¦----+--¦------->
            ^
            |
            "RotateLeft" player input:
             Piece rotates

I.e. running a game at 60 Hz just means that Game::update is called 60 times in one second to determine the state in the timeline and show it. (The precision used internally is currently based on std::time::Duration which goes down to nanoseconds.)

Depending on configuration, calls to Game::update and Game::forfeit can return additional information (Notification) which can facilitate frontend implementation (e.g. hard drop, piece lock, line clears and other visual feedback).

The engine provides possibilities for compile-time modding. Mods may arbitrarily access and modify game state when called on given engine hooks.

In terms of advanced game mechanics the engine aims to compare with other modern tetromino stackers. It should already incorporate many features desired by familiar/experienced players, such as:

  • Available player actions:
    • Move left/right,
    • Rotate left/right/180°
    • Drop soft/hard
    • Teleport down(='Sonic drop') and left/right
    • Hold piece,
  • Tetromino randomizers: 'Uniform', 'Stock' (generalized Bag), 'Recency' (history), 'Balance-out',
  • Piece preview (arbitrary size),
  • Spawn delay (ARE),
  • Spawn manipulation (IRS/IHS/IMS/ITS; by keeping rotate/hold/move/teleport pressed during spawn),
  • Rotation systems: 'Ocular' (engine-specific, playtested), 'Classic', 'Super',
  • Delayed auto-move (DAS),
  • Auto-move rate (ARR),
  • Soft drop rate (SDF),
  • Delayed soft drop ('DAS but for Soft drop'),
  • Customizable gravity/fall and lock delay curves (exponential and/or linear; also, '20G' (fall rate of ≥1200 Hz) just becomes ≤00083s fall delay),
  • Ensure move delay less than lock delay toggle (i.e. DAS/ARR are automatically shortened when lock delay is very low),
  • Allow lenient lock-reset toggle (i.e. reset lock delay even if rotate/move fails),
  • Lock-reset cap factor (i.e. maximum time before lock delay cannot be reset),
  • Line clear duration (LCD),
  • Customizable win/loss conditions based on the time, pieces, lines, points,
  • Score more points for larger lineclears, spins ('allspin'), perfect clear, combo,
  • Game reproducibility (PRNG/determinism).

The basics seem to have been figured out through many iterative improvements. Ongoing areas of investigation (to improve generalization) are:

  • Choice of Notifications provided to frontend clients;
  • Choice of update hooks for modding clients;
  • Choice of natively supported Stats to query game with or make game automatically halt;
  • Various engine and modding generalizations for clients that want to plug custom behavior for currently-hardcoded structures.

Implementation Idea

The game keeps:

  • Configuration to read from, which determines game behavior.
  • State values which persist throughout the game.
  • A dedicated 'phase'-state field:
    • This represents the macro-scale state machine and can store values specific to separate stages during the game.
    • E.g., 'Spawning' (no piece) vs. 'Piece-is-in-play' (with piece data to keep track of).

During each update, the game looks at the (very limited) number of upcoming in-game 'events' and processes them. The only complicated phase is Phase::PieceInPlay { .. }, which encapsulates several types of upcoming events (priority in the given order):

  • Action by player: Player input which causes e.g. the piece to move, makes it lock immediately or cancels auto-movement.
  • Autonomous movement: While move buttons are active ('held down'), the piece may move autonomously.
  • Falling or locking: Whenever the piece is airborne or grounded, there is an upcoming fall or lock scheduled.

Engine Insights using just Type definitions and API

Much of the implementation is tightly encoded into types. It may be instructive to simply consider the main type definitions for good insight into the deeper engine mechanics. See also full documentation.

Main Game type

// The main engine type.
struct Game {
    // May be mutated by user. Not mutated by Game.
    config: Configuration,

    // Cannot be mutated (minimal data used for reproducibility).
    state_init: StateInitialization,

    // Cannot be mutated by user. Mutated by Game.
    state: State,
    // Cannot be mutated by user. Mutated by Game.
    phase: Phase,

    // Modding.
    modifiers: Vec<Box<dyn GameModifier>>,
}

impl Game {
  fn update(
    &mut self,
    mut target_time: InGameTime,
    mut player_input: Option<Input>,
  ) -> Result<NotificationFeed, UpdateGameError>;

  fn forfeit(&mut self) -> Result<NotificationFeed, UpdateGameError>;
}

Game fields types

struct Configuration {
    generate_piece_preview: usize,
    allow_spawn_actions: bool,
    rotation_system: impl PieceRotator,
    spawn_delay: Duration,
    delayed_auto_shift: Duration,
    auto_repeat_rate: Duration,
    delayed_soft_drop: Option<Duration>
    soft_drop_rate: Either<ExtNonNegF64, ExtDuration>,
    fall_delay_params: Either<DelayParameters, DelayTable>,
    lock_delay_params: Option<Either<DelayParameters, DelayTable>>,
    ensure_move_delay_lt_lock_delay: bool,
    allow_lenient_lock_reset: bool,
    lock_reset_cap_factor: ExtNonNegF64,
    line_clear_duration: Duration,
    update_delays_every_n_lineclears: u32,
    game_limits: GameLimits,
    send_notifiations: bool,
}

struct StateInitialization {
    seed: u64,
    tetromino_generator: impl TetrominoGenerator,
}

struct State {
    time: InGameTime,
    active_buttons: [Option<InGameTime>; Button::VARIANTS.len()],
    rng: GameRng,
    tetromino_generator: impl TetrominoGenerator,
    tetromino_preview: VecDeque<Tetromino>,
    tetromino_held: Option<(Tetromino, bool)>,
    board: [[Option<TileID>; Game::WIDTH]; Game::HEIGHT],
    fall_delay: ExtDuration,
    fall_delay_lowerbound_hit_at_n_lineclears: Option<u32>,
    lock_delay: ExtDuration,
    pieces_locked: [u32; Tetromino::VARIANTS.len()],
    lineclears: u32,
    consecutive_lineclears: u32,
    points: u32,
}

enum Phase {
    Spawning { spawn_time: InGameTime },
    PieceInPlay {
        piece: Piece,
        autoshift_scheduled: Option<InGameTime>,
        fall_or_lock_time: InGameTime,
        lock_time_cap: InGameTime,
        lowest_y: isize,
    },
    LinesClearing { clear_finish_time: InGameTime, points_bonus: u32 },
    GameEnd { cause: GameEndCause, is_win: bool },
}

Some Other Types

enum Tetromino { O, I, S, Z, T, L, J, }

enum Orientation { N, E, S, W, }

struct Piece {
    tetromino: Tetromino,
    orientation: Orientation,
    position: Coord,
}

enum Button {
    MoveLeft, MoveRight,
    RotateLeft, RotateRight, Rotate180,
    DropSoft, DropHard,
    TeleLeft, TeleRight, TeleDown, 
    HoldPiece,
}

enum Input { Activate(Button), Deactivate(Button), }

type InGameTime = Duration;
type GameRng = ChaCha8Rng;

struct DelayParameters {
    base_delay: ExtDuration,
    factor: ExtNonNegF64,
    subtrahend: ExtDuration,
    lowerbound: ExtDuration,
}

enum Notification {
    HardDrop {
        height_dropped: usize,
        dropped_piece: Piece,
    },
    PieceLocked { piece: Piece },
    LinesClearing {
        y_coords: Vec<usize>,
        line_clear_duration: InGameTime,
    },
    Accolade {
        points_bonus: u32,
        lineclears: u32,
        combo: u32,
        is_spin: bool,
        is_perfect_clear: bool,
        tetromino: Tetromino,
    },
    GameEnded {
        is_win: bool,
    },
    Custom(String),
}

enum NotificationLevel { Silent, Standard, Debug, }

enum UpdateGameError { TargetTimeInPast, AlreadyEnded, }

enum GameEndCause {
    LockOut { locking_piece: Piece },
    BlockOut { blocked_piece: Piece },
    BufferOut { overflowing_lines: Vec<Line> },
    Limit(Stat),
    Forfeit { piece_in_play: Option<Piece> },
    Custom(String),
}

Modding

trait GameModifier: std::fmt::Debug {
    fn id(&self) -> String;
    fn cfg(&self) -> String;
    fn try_clone(&self) -> Result<Box<dyn GameModifier>, String>;

    fn on_player_input_received(&mut self, game: GameAccess, feed: &mut NotificationFeed, time: &mut InGameTime, player_input: &mut Option<Input>) {}
    fn on_game_built(&mut self, game: GameAccess) {}
    fn on_game_ended(&mut self, game: GameAccess, feed: &mut NotificationFeed) {}
    fn on_time_state_progression_pre(&mut self, game: GameAccess, feed: &mut NotificationFeed, time: &mut InGameTime) {}
    fn on_time_state_progression_post(&mut self, game: GameAccess, feed: &mut NotificationFeed) {}
    fn on_check_game_limits_post(&mut self, game: GameAccess, feed: &mut NotificationFeed) {}
    fn on_spawn_pre(&mut self, game: GameAccess, feed: &mut NotificationFeed, time: &mut InGameTime) {}
    fn on_spawn_post(&mut self, game: GameAccess, feed: &mut NotificationFeed) {}
    fn on_player_action_pre(&mut self, game: GameAccess, feed: &mut NotificationFeed, input: Input, time: &mut InGameTime) {}
    fn on_player_action_post(&mut self, game: GameAccess, feed: &mut NotificationFeed, input: Input) {}
    fn on_autoshift_pre(&mut self, game: GameAccess, feed: &mut NotificationFeed, time: &mut InGameTime) {}
    fn on_autoshift_post(&mut self, game: GameAccess, feed: &mut NotificationFeed) {}
    fn on_fall_pre(&mut self, game: GameAccess, feed: &mut NotificationFeed, time: &mut InGameTime) {}
    fn on_fall_post(&mut self, game: GameAccess, feed: &mut NotificationFeed) {}
    fn on_lock_pre(&mut self, game: GameAccess, feed: &mut NotificationFeed, time: &mut InGameTime) {}
    fn on_lock_post(&mut self, game: GameAccess, feed: &mut NotificationFeed) {}
    fn on_lines_clear_pre(&mut self, game: GameAccess, feed: &mut NotificationFeed, time: &mut InGameTime) {}
    fn on_lines_clear_post(&mut self, game: GameAccess, feed: &mut NotificationFeed) {}
}