Skip to content

About

Real-time 1v1 block-stacking battle: Laravel 13, Reverb WebSockets, Vue 3, PixiJS, server-validated game engine and house bots

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Duel Stack

CI

A real-time 1v1 block-stacking battle in the browser. Two players are matched by rating and dealt the same seeded pieces. Every line you clear sends garbage rows into your opponent's board, and the first player to top out loses. If nobody else is queueing, a server-side bot steps in after 15 seconds. You can play as a guest in one click.

Play the live demo →

A live ranked match: both boards update over WebSockets and garbage rises from the bottom

Stack: Laravel 13 · PHP 8.4 · Laravel Reverb + Echo (WebSockets) · Vue 3 + Vue Router · PixiJS 8 · Tailwind 4 · MySQL 8 or SQLite

Result and Elo change Replay viewer Against a house bot Phone
Result card Replay viewer Bot match Phone layout

What's in it

  • Ranked 1v1 with Elo ratings (K=32), lifetime stats, player profiles with paginated match history, and a leaderboard per monthly season. When a season ends, its standings are kept and ratings move halfway back to 1000. Ratings above 1200 decay slowly after two weeks without a game.
  • Rating-based matchmaking. The acceptable rating gap widens the longer you wait (±150, plus 25 a second, up to ±1000).
  • House bots. A player left alone for 15 seconds is paired with the closest-rated bot: Rookie, Club or Pro. Bots play on the server under exactly the same rules as players, at a human pace: each piece takes a varying think time, with the odd long pause.
  • A full modern ruleset: SRS rotation with wall kicks, hold, a 5-piece preview, a ghost piece, DAS/ARR and lock delay. Attacks come from combos, back-to-back tetrises and perfect clears, and cancel incoming garbage first.
  • Exact replays of every finished match, with scrubbing, 0.5–4x speed and a board swap.
  • Spectator mode. Anyone can watch a live match from the leaderboard's "Live now" list or a player's profile. Both boards follow a public channel, and each lock is played back as a falling piece.
  • Practice mode against a local bot, rebindable keys with adjustable DAS and ARR, and touch controls on phones.

How it works

sequenceDiagram
    participant A as Player A (Vue + PixiJS)
    participant S as Laravel
    participant R as Reverb
    participant B as Player B
    A->>A: gravity, input and rotation run locally
    A->>S: POST /locks: where the piece came to rest
    S->>S: replay the lock through the PHP engine (row-locked transaction)
    S-->>A: 200 with the authoritative state (or 409 with the state to resync to)
    S->>R: board.updated, garbage.sent
    R->>B: B's view of A's board updates, and garbage is queued under B's stack
    A-->>R: whisper: the falling piece, about 12 times a second
    R-->>B: B watches A's piece move
Loading

The game engine exists twice, and the two copies are tested to agree. The JS engine (resources/js/engine) runs the real-time game in the browser. The PHP port (app/Game) validates it. After every lock, the client sends only where the piece came to rest. The server replays that lock through its own engine and checks that the piece is the right one for the seeded 7-bag and the hold, it is inside the field, it overlaps nothing, it is resting on something, and some sequence of real inputs could have put it there (see the security model below). The server then computes the line clears, score and attack itself. A fixture of 921 locks from bot games and the SRS kick tables, generated by the JS engine, is replayed through the PHP engine in the test suite after every change, so the two copies can't drift apart.

Concurrency. A lock runs in a transaction that holds a row lock on the match. Two players' locks, and the garbage they send each other, are therefore applied one at a time. The piece number makes each submission idempotent. A rejected lock returns 409 with the authoritative state and the pending garbage, and the optimistic client resyncs to it. Matchmaking runs under an atomic cache lock. Rating changes are applied as relative updates, because a bot can be in many matches at once.

Garbage. An attack creates a garbage batch for the opponent, which is broadcast over Reverb. The opponent's client raises it on its next lock that clears no lines and reports which batch ids it applied. The server checks that they are the oldest pending batches, in order, and rejects any lock that skips a batch older than the 3-second grace period.

Bots. php artisan bots:play is a single daemon that plays every bot match. It ports the JS bot's placement search to PHP: height, holes, bumpiness and lines, over every drop of the current piece and the hold swap. It submits each lock through the same LockProcessor that players use. The daemon is stateless: a bot's think time for each piece comes from a hash of the match seed and the piece number, so a restarted daemon picks up at the same pace.

Leaving a match. A running game sends a heartbeat every 5 seconds from its render loop, which stops when the tab is hidden. If a player has had no heartbeat and no lock for 20 seconds, or no lock for 5 minutes, the opponent can claim the win. matches:expire-idle ends matches that both players have abandoned, as a no contest.

Security model

The server is authoritative for everything that affects ratings: piece order, legality, line clears, score, attack, garbage, the result and Elo. Two more checks stop a modified client from playing better than a person could:

  • Reachability. App\Game\Reachability runs a breadth-first search from the spawn point over shifts, soft drops and SRS rotations with wall kicks, and the lock is rejected unless its position is among those reached. Tucks and T-spins pass, and a piece placed inside a sealed cavity does not.
  • Pace. A player's locks may not outrun 5 pieces per second of match time, plus a 15-piece head start. Fast human play is about 3-4. The limit is measured over the whole match rather than a short window, so a burst of queued locks sent after a dropped connection is never mistaken for cheating.

What remains is timing within those limits: a client that plays at a human pace with inhumanly good choices can't be told apart from a strong player. The pace limit can also be banked, by playing slowly and then very fast. The bot autopilot used by the end-to-end test (?autopilot=1) is compiled out of production builds.

Running it locally

Requirements: PHP 8.3+, Composer and Node 20+.

composer setup                    # install, create .env and the key, migrate, build the frontend
php artisan db:seed               # two accounts, alice and bob (password: "password"), a leaderboard and the bots
composer run dev                  # app server, Vite, Reverb, the bot daemon, the scheduler and the queue

Open http://localhost:8040 in two browsers (or a normal window and a private one) and press Play ranked in both. On your own, use Play as a guest and a house bot takes you on after 15 seconds.

To use MySQL instead of SQLite, set DB_CONNECTION=mysql and the DB_* values in .env.

Notes for Windows
  • PHP's built-in server runs on the CLI SAPI, which often has opcache turned off. That makes every request take about 500ms. For realistic timings, serve with opcache on. The command must run from public/, because Laravel's router script uses the working directory as the public path: cd public && php -d opcache.enable_cli=1 -S 127.0.0.1:8040 ../vendor/laravel/framework/src/Illuminate/Foundation/resources/server.php
  • Use REVERB_HOST=127.0.0.1, not localhost. On Windows, localhost tries IPv6 first, which adds about 220ms to every broadcast.

Deploying

deploy/ sets up a single Ubuntu 24.04 server: Nginx in front of PHP-FPM and Reverb (wss:// on the same domain), Supervisor keeping Reverb and the bot daemon running, cron for the scheduler, SQLite, and a Let's Encrypt certificate. No queue worker is needed, because every broadcast is sent immediately.

sudo apt-get update && sudo apt-get install -y git                                 # minimal images lack it
git clone https://github.com/GodfreysDragon/duel-stack.git /tmp/duel-stack
sudo bash /tmp/duel-stack/deploy/setup.sh duel-stack.example.com you@example.com   # once
bash /var/www/stack-duel/deploy/update.sh                                          # each deploy
bash /var/www/stack-duel/deploy/update.sh --rollback                               # back to the previous release

Each deploy builds a fresh release in /var/www/stack-duel-deploy/releases while the current one keeps serving, backs up the database, migrates, and then switches the /var/www/stack-duel symlink in one step. The last 3 releases and 10 database backups are kept. .env, storage/ and the SQLite database live in /var/www/stack-duel-deploy/shared. A rollback switches the code back but leaves migrations applied.

Tests

php artisan test                  # PHPUnit: engine parity, rules, the bot, matchmaking, locks, garbage, Elo, channels, ...
npm run test:js                   # node:test: the JS engine, the game controller, lock sync with the server and the bot
npm run fixture                   # regenerate the parity fixture after changing the engine

CI runs the PHP suite on both SQLite and MySQL 8.4, the JS tests, Pint and Larastan (PHPStan level 8) on every push. The end-to-end test below runs nightly and on demand (the End-to-end workflow), and Dependabot opens weekly update PRs.

End to end. tests/e2e/ranked-match.mjs drives two headless browsers through a complete ranked match against a running app. The steps are: registration, matchmaking, the countdown, 25 seconds of play with every lock validated, garbage crossing over Reverb, a reload mid-match that resumes from server state, and a keyboard top-out. Then it checks the result card and the symmetric Elo change, the profile, the leaderboard and the replay viewer. Finally it covers a bot match, practice mode and the phone layout.

VITE_E2E_AUTOPILOT=true npm run build
php artisan reverb:start & php artisan bots:play &   # plus the app server (see the Windows notes above)
E2E_URL=http://127.0.0.1:8040 npm run test:e2e

Controls

← → move · ↓ soft drop · Space hard drop · ↑/X rotate right · Z/Ctrl rotate left · A rotate 180° · C/Shift hold. Every key, DAS, ARR and the soft-drop speed can be changed on the Settings page; they are saved in the browser. On touch devices, on-screen buttons appear under the board.

License

MIT © 2026 Cal Marusin

About

Real-time 1v1 block-stacking battle: Laravel 13, Reverb WebSockets, Vue 3, PixiJS, server-validated game engine and house bots

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages