DEV Community

Cover image for Garbage rows and a shared 7-bag: how I built Block Drop Duel, a two-player falling-blocks game
My MP Games
My MP Games

Posted on

Garbage rows and a shared 7-bag: how I built Block Drop Duel, a two-player falling-blocks game

Block Drop Duel is the falling-blocks game everyone knows, with two wells side by side. Clear lines and grey "garbage" rows rise up from the bottom of your rival's well. The last stack standing wins.

My other posts in this series walked through one game's rules from top to bottom. This time I'm organising it around the decisions I had to make, because a real-time duel forces more of them than a turn-based board game does. All the rules live in two server files: block-duel-core.js (232 lines of pure functions) and engines/block-duel.js (360 lines: ticks, garbage, the bot). The browser side is a Vue component plus a canvas renderer.

Decision 1: store the well as strings

The well is 10 columns by 22 rows. The top two rows are hidden spawn rows, so you see a normal 10×20 field. Each row is a plain string:

const COLS = 10;
const ROWS = 22; // rows 0-1 are hidden spawn rows
const emptyBoard = () => Array.from({ length: ROWS }, () => '.'.repeat(COLS));
Enter fullscreen mode Exit fullscreen mode

A cell is . when it's empty, a piece letter (I, T, S...) once a piece locks there, or G for garbage. The letter doubles as the colour key on the client. Since the whole match state is plain JSON, a room can be serialised mid-game, and a unit test checks exactly that.

The seven pieces are also written as strings, and all four rotations are generated once at startup by turning the bounding box:

const SHAPES = { T: ['.T.', 'TTT', '...'], I: ['....', 'IIII', '....', '....'], /* ... */ };

function rotateBox(rows) {
  const n = rows.length, out = [];
  for (let r = 0; r < n; r++) {
    let line = '';
    for (let c = 0; c < n; c++) line += rows[n - 1 - c][r];
    out.push(line);
  }
  return out;
}
// CELLS[t][rot] = [[dx, dy], ...]
Enter fullscreen mode Exit fullscreen mode

After that, collision is one small function. Off the sides or below the floor is a miss. Above the top is allowed, so pieces can poke into the hidden rows:

function fits(board, piece) {
  for (const [x, y] of cellsOf(piece)) {
    if (x < 0 || x >= COLS || y >= ROWS) return false;
    if (y < 0) continue;
    if (board[y][x] !== '.') return false;
  }
  return true;
}
Enter fullscreen mode Exit fullscreen mode

Decision 2: use the standard rotation system, kicks included

Players who know the genre expect a T-piece to slide out of a tight spot when it's rotated against a wall. So I used the standard SRS wall-kick tables: one for J, L, S, T and Z, and a separate one for I. Rotation tries each offset in order and keeps the first one that fits:

function tryRotate(board, piece, dir) {
  if (piece.t === 'O') return null;
  const to = (piece.r + (dir > 0 ? 1 : 3)) % 4;
  const table = piece.t === 'I' ? KICKS_I : KICKS_JLSTZ;
  for (const [kx, ky] of table[`${piece.r}>${to}`]) {
    const next = { ...piece, r: to, x: piece.x + kx, y: piece.y - ky };
    if (fits(board, next)) return next;
  }
  return null;
}
Enter fullscreen mode Exit fullscreen mode

Watch the - ky. The published tables use y-up, but my board is y-down, so every vertical kick has to be flipped. Get that wrong and rotations near the floor quietly fail.

Decision 3: both players get the same pieces

In a duel, randomness should come from your opponent, not from the piece generator. Each player has their own pointer into one shared bag. The bag is refilled with shuffled 7-bags, so every set of seven pieces contains each shape exactly once:

function nextFromBag(state, p) {
  while (p.seq >= state.bag.length) {
    const bag = PIECES.slice();
    for (let i = bag.length - 1; i > 0; i--) {
      const j = Math.floor(rand(state.rng) * (i + 1));
      [bag[i], bag[j]] = [bag[j], bag[i]];
    }
    state.bag.push(...bag);
  }
  return state.bag[p.seq++];
}
Enter fullscreen mode Exit fullscreen mode

rand is a tiny mulberry32 generator whose seed lives in the state, not Math.random(), so it can be serialised along with everything else. Clients see the next three pieces. The tradeoff: if you play faster than your opponent, you're effectively seeing their future pieces too. I decided that's fine, because it's the same information they'll get.

Decision 4: count time in ticks, not milliseconds

The server runs the match at 50 ms per tick, and nothing in the rules reads the wall clock. Gravity is "fall one row every N ticks", with N shrinking as the level rises:

const gravityTicks = (level) => Math.max(1, Math.round(20 * Math.pow(0.82, level - 1)));
Enter fullscreen mode Exit fullscreen mode

That's one row per second at level 1, about four rows per second at level 8, and one row per tick (20 per second) at the maximum level of 15. Your level goes up every 8 lines or every 800 ticks (40 seconds), whichever is higher. That second rule exists because two careful players could otherwise stack safely for ever. The time-based ramp makes sure every match ends.

There's also a 500 ms lock delay (10 ticks). A successful move or rotation while the piece is resting on the stack resets the delay, up to 15 times, so you can slide a piece into place without stalling forever. A 1.2-second "Ready" period at the start ignores input.

Decision 5: make garbage the whole game

When a piece locks, the engine writes it into the board and drops full rows with a filter:

const kept = rows.filter((r) => r.includes('.'));
const cleared = ROWS - kept.length;
while (kept.length < ROWS) kept.unshift('.'.repeat(COLS).split(''));
Enter fullscreen mode Exit fullscreen mode

Then the attack:

  • Lines → garbage: 1 line sends 0, 2 send 1, 3 send 2, 4 send 4 ([0, 0, 1, 2, 4]).
  • Combo bonus for consecutive clearing locks: +1 on the 2nd and 3rd, +2 on the 4th and 5th, +3 after that.
  • Back-to-back four-line clears add +1.

The part I like most is cancelling. Incoming garbage doesn't land straight away. It waits in a pending queue (shown as a meter), and your own attack eats it first:

while (attack > 0 && p.pending.length) {
  const b = p.pending[0];
  const use = Math.min(attack, b.n);
  b.n -= use; attack -= use;
  if (b.n <= 0) p.pending.shift();
}
if (attack > 0) opp.pending.push({ n: attack, hole: Math.floor(rand(opp.holeRng) * COLS) });
Enter fullscreen mode Exit fullscreen mode

Pending garbage only rises when you lock a piece without clearing, and at most 8 rows at a time. Each batch is a set of rows with a single hole in the same column, so a well-placed I-piece can dig out several rows at once. Rows are pushed in from the bottom. If the row that gets pushed off the top wasn't empty, you've topped out.

Decision 6: let the server own everything

Inputs are tiny messages: move, rotate, soft, hard, hold. The server validates each one against the real board and replies "silently":

return { ok: true, silent: state.winner == null };
Enter fullscreen mode Exit fullscreen mode

Silent means "don't broadcast right now". The room's tick loop already sends state every 50 ms as a volatile message (one that's simply dropped if the connection is backed up). The exception is a move that ends the match, which is broadcast at once because the tick loop stops when someone wins.

Game over has three paths: a new piece can't spawn even one row higher, a piece locks entirely inside the hidden rows without clearing anything, or garbage pushes blocks off the top. If both players die on the same tick, it's a draw.

The client doesn't simulate any rules. It draws the latest state, works out the ghost piece locally, and handles input feel: 160 ms auto-repeat delay and a 45 ms repeat rate for held keys, swipe gestures on phones, and on-screen buttons. In Local vs mode, two people share one keyboard (WASD on one side, arrows on the other). The honest tradeoff: with no client-side prediction, a laggy connection makes movement feel slightly behind. Because the client never decides anything, though, there are no "I cleared that line on my screen" arguments.

Decision 7: a bot that plans once per piece

The computer opponent doesn't search ahead. When a new piece appears, it tries every rotation and column, hard-drops each into a copy of the board, and scores the result:

const WEIGHTS = { lines: 0.76, agg: -0.51, holes: -0.36, bump: -0.18, danger: -0.6 };
let score = w.lines * cleared + w.agg * f.agg + w.holes * f.holes + w.bump * f.bump;
if (f.maxH > 14) score += w.danger * (f.maxH - 14) * 4;
if (res.lockOut) score -= 1000;
Enter fullscreen mode Exit fullscreen mode

That's aggregate height, holes and bumpiness, the classic heuristic, plus a penalty for stacking near the top. Then it plays the plan out as real inputs, one at a time, through the same onAction a human uses. Difficulty changes how often it acts (every 7, 4 or 2 ticks), how often it picks a worse placement from its top few, how long it pauses at spawn, and whether it ever uses hold. On Hard it inputs every 100 ms and always takes its best placement. That's quick, but beatable if you send garbage early.

What I left out

No T-spin detection and no perfect-clear bonus. Each would be a small addition to lockPiece, and I may add T-spins if people ask. The rules have a small node:test suite covering the shared bag, movement and kicks, hold, garbage timing, top-outs and JSON-safe state.

If you want to see how it feels, play Block Drop Duel at https://mympgames.com/play/block-drop-duel against the computer, with a friend on one keyboard, or online with a room link. The rest of the 60+ free multiplayer games are at https://mympgames.com. I'd love to hear whether the garbage numbers feel fair.

Top comments (0)