On this page
Tetris is easy to write alone. Multiplayer Tetris is a different problem: several browsers have to agree on which pieces fall, punish each other in real time, and declare a winner, even when someone's connection drops in the middle of a round.
red-tetris is the 42 web project we built in a team of two: open the same room URL as a friend and race on the same pieces until one of you tops out. This article explains the ideas that make it work, with code from our repository, and lets you play a round against a bot, built on the same engine.
The game
Players join a room by opening /<room>/<name>. The first one in is the host and starts the round. Everyone then plays on their own board, with the same sequence of pieces. Clearing lines sends penalty lines to the others, and you can watch the outline of their boards rise. The last player standing wins.
- pieces sent over the network
- 0
- penalty lines for n cleared
- n − 1
- unit tests, all passing
- 111
- statement coverage
- 96.5%
The subject adds constraints that shaped the code: the client must be written without classes or this, the board must be drawn with CSS grid or flexbox (no canvas, no SVG), and the server must use classes for players, pieces and games.
Same pieces, none sent
The obvious design is for the server to send every piece to every player as the game goes. It works, but each piece then depends on a network round trip, and the server has to track where every player is in the sequence.
We used a simpler idea: when the round starts, the server sends one number, a seed. Every browser feeds it into the same pseudo-random generator, which always produces the same sequence from the same seed. So every player computes the same pieces, in the same order, without another message.
socket.on(ClientEvents.StartGame, () => {
const room = socketRoom.get(socket.id)
const game = room && manager.get(room)
if (!game) return
const player = game.players.get(socket.id)
if (!player?.isHost) return
const seed = Math.floor(Math.random() * 2 ** 31)
game.start(seed)
broadcastRoomState(game)
io.to(room).emit(ServerEvents.GameStarted, { seed })
})
The generator draws pieces in bags of seven: each bag is a shuffle of all seven shapes (a Fisher-Yates shuffle driven by the seed), so you never wait too long for a long bar:
export const nextSeed = (seed: number): number => (seed + 0x6d2b79f5) | 0
export const seedToFloat = (seed: number): number => {
let t = seed
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
export interface BagResult {
readonly bag: ReadonlyArray<TetrominoName>
readonly nextSeed: number
}
export const drawBag = (seed: number): BagResult => {
const bag = [...TETROMINO_NAMES]
let currentSeed = seed
for (let i = bag.length - 1; i > 0; i -= 1) {
currentSeed = nextSeed(currentSeed)
const j = Math.floor(seedToFloat(currentSeed) * (i + 1))
const tmp = bag[i]
bag[i] = bag[j]
bag[j] = tmp
}
return { bag, nextSeed: nextSeed(currentSeed) }
}
The server keeps the exact same algorithm in its Piece class, so it can always tell which piece is at which position:
export class Piece {
constructor(seed) {
this.seed = seed
this.bags = []
this.nextSeed = seed
}
ensureBagCount(count) {
while (this.bags.length < count) {
const { bag, nextSeed: updatedSeed } = drawBag(this.nextSeed)
this.bags.push(bag)
this.nextSeed = updatedSeed
}
}
nameAt(index) {
const bagIndex = Math.floor(index / TETROMINO_NAMES.length)
const withinBag = index % TETROMINO_NAMES.length
this.ensureBagCount(bagIndex + 1)
return this.bags[bagIndex][withinBag]
}
}
An engine of pure functions
On the client, the whole game is a set of pure functions: they take a state and return a new one, without changing anything. The board is an array of rows; a move is legal if the piece does not collide with the walls, the floor or a filled cell:
export const collides = (board: Board, matrix: Matrix, position: { x: number; y: number }): boolean => {
const height = board.length
const width = board[0]?.length ?? 0
for (let row = 0; row < matrix.length; row += 1) {
for (let col = 0; col < matrix[row].length; col += 1) {
if (matrix[row][col] === 0) continue
const boardX = position.x + col
const boardY = position.y + row
if (boardX < 0 || boardX >= width || boardY >= height) return true
if (boardY < 0) continue
if (board[boardY][boardX] !== null) return true
}
}
return false
}
Gravity is a tick: the piece falls one row, and when it lands it gets one extra tick before it locks, which leaves time to slide it under an overhang:
export const tick = (state: GameState): LockResult => {
if (state.active === null || state.status !== 'running') return { state, linesCleared: 0 }
if (state.isLocking) {
if (isPieceGrounded(state.board, state.active)) {
return lockActivePiece(state)
}
return { state: { ...state, isLocking: false }, linesCleared: 0 }
}
if (isPieceGrounded(state.board, state.active)) {
return { state: { ...state, isLocking: true }, linesCleared: 0 }
}
const moved = movePiece(state.board, state.active, 0, 1)
return { state: moved === null ? state : { ...state, active: moved }, linesCleared: 0 }
}
Locking merges the piece into the board, clears full lines, scores them and spawns the next piece:
const lockActivePiece = (state: GameState): LockResult => {
if (state.active === null) return { state, linesCleared: 0 }
const merged = mergePieceIntoBoard(state.board, state.active)
const clearedLines = findClearedLines(merged)
const board = clearLines(merged, clearedLines)
const level = levelForLines(state.linesClearedTotal)
const score = state.score + scoreForLines(clearedLines.length, level)
const linesClearedTotal = state.linesClearedTotal + clearedLines.length
return spawnNext({ ...state, board, active: null, score, linesClearedTotal }, clearedLines.length)
}
Rotation uses simple wall kicks: if the rotated piece doesn't fit, try it one and two cells to each side before giving up, so a piece against a wall can still turn:
export const rotatePiece = (board: Board, piece: ActivePiece): ActivePiece | null => {
const matrix = rotateMatrixCW(piece.matrix)
const kicks = [0, -1, 1, -2, 2]
for (const kick of kicks) {
const position = { x: piece.position.x + kick, y: piece.position.y }
if (!collides(board, matrix, position)) {
return {
...piece,
matrix,
position,
rotationIndex: (piece.rotationIndex + 1) % 4,
}
}
}
return null
}
Because nothing mutates, plugging the engine into Redux Toolkit is almost mechanical: each reducer calls one engine function. The seed from the server goes straight into createGameState:
started: (state, action: PayloadAction<{ seed: number; playerId: string }>) =>
withLocal(state, action.payload.playerId, createGameState(action.payload.seed)),
tickAdvanced: (state, action: PayloadAction<{ playerId: string }>) => {
if (state.local === null) return state
const result = tick(state.local)
return withLocal(state, action.payload.playerId, result.state, result.linesCleared)
},
movedLeft: (state, action: PayloadAction<{ playerId: string }>) => {
if (state.local === null) return state
return withLocal(state, action.payload.playerId, moveActive(state.local, -1, 0))
},
movedRight: (state, action: PayloadAction<{ playerId: string }>) => {
if (state.local === null) return state
return withLocal(state, action.payload.playerId, moveActive(state.local, 1, 0))
},
rotated: (state, action: PayloadAction<{ playerId: string }>) => {
if (state.local === null) return state
return withLocal(state, action.payload.playerId, rotateActive(state.local))
},
softDropped: (state, action: PayloadAction<{ playerId: string }>) => {
if (state.local === null) return state
return withLocal(state, action.payload.playerId, softDrop(state.local))
},
hardDropped: (state, action: PayloadAction<{ playerId: string }>) => {
if (state.local === null) return state
const result = hardDrop(state.local)
return withLocal(state, action.payload.playerId, result.state, result.linesCleared)
},
penaltyReceived: (state, action: PayloadAction<{ lines: number; playerId: string }>) => {
if (state.local === null) return state
return withLocal(state, action.payload.playerId, applyPenalty(state.local, action.payload.lines))
},
Penalties and spectrums
When a player clears n lines at once, every opponent receives n − 1 penalty lines: a single line sends nothing, four lines send three. The server does the arithmetic and relays it to the rest of the room:
socket.on(ClientEvents.LinesCleared, ({ lines }) => {
const room = socketRoom.get(socket.id)
const game = room && manager.get(room)
if (!game || typeof lines !== 'number') return
const penalty = Math.max(0, lines - 1)
if (penalty > 0) socket.to(room).emit(ServerEvents.PenaltyLines, { lines: penalty })
})
Penalty lines push the whole board up from the bottom:
export const addPenaltyLines = (board: Board, count: number): Board => {
if (count <= 0) return board
const width = board[0]?.length ?? BOARD_WIDTH
const penaltyRow = Array.from({ length: width }, () => 'PENALTY' as const)
const trimmed = board.slice(count)
const penaltyRows = Array.from({ length: count }, () => [...penaltyRow])
return [...trimmed, ...penaltyRows]
}
The subject says penalty lines are indestructible, so the line-clearing code skips rows made only of penalty blocks. They stay for the rest of the round:
export const findClearedLines = (board: Board): ReadonlyArray<number> =>
board.reduce<number[]>((acc, row, index) => {
const isFull = row.every((cell) => cell !== null)
const isIndestructiblePenalty = row.every((cell) => cell === 'PENALTY')
return isFull && !isIndestructiblePenalty ? [...acc, index] : acc
}, [])
You don't see your opponents' boards in full, only their spectrum: the height of each column. It is cheap to send, ten small numbers, and it is enough to see who is in trouble:
export const computeSpectrum = (board: Board, playerId: string): Spectrum => {
const width = board[0]?.length ?? BOARD_WIDTH
const heights = Array.from({ length: width }, (_, col) => {
const filledRowIndex = board.findIndex((row) => row[col] !== null)
return filledRowIndex === -1 ? 0 : board.length - filledRowIndex
})
return { playerId, heights }
}
Play a round
Here is the engine, copied from the repository into this page, with a bot as your opponent. Both boards are built from the same seed, so you both get the same pieces. Clear two or more lines at once to send penalties; the bot does the same to you.
Click Start, then play with the keyboard (or the buttons on a phone). The first board to top out loses.
Same seed, same sequence: piece number k is the same on both boards, whoever gets there first.
The bot's spectrum: all a real opponent would see of its board
penalty line (indestructible)where your piece will land← → move · ↑ rotate · ↓ soft drop · Space hard drop
The server is a referee
Since every browser plays its own game, the server never simulates Tetris. It is a referee: it manages rooms and players, hands out the seed, relays spectrums and penalties, and decides when a round is over. Joining is refused once a round has started, or if the name is already taken in that room:
socket.on(ClientEvents.JoinRoom, ({ room, playerName }) => {
if (typeof room !== 'string' || typeof playerName !== 'string') return
const game = manager.getOrCreate(room)
if (game.hasStarted()) {
socket.emit(ServerEvents.JoinRejected, { reason: 'already-started' })
return
}
if (game.hasPlayerNamed(playerName)) {
socket.emit(ServerEvents.JoinRejected, { reason: 'name-taken' })
return
}
game.addPlayer(socket.id, playerName)
socket.join(room)
socketRoom.set(socket.id, room)
broadcastRoomState(game)
})
When a player tops out, they are eliminated, and if only one player is left alive, the round ends with a winner. The same check runs when someone disconnects mid-round, and if the host leaves, the next player becomes host.
socket.on(ClientEvents.ToppedOut, () => {
const room = socketRoom.get(socket.id)
const game = room && manager.get(room)
if (!game) return
const winnerId = game.eliminate(socket.id)
io.to(room).emit(ServerEvents.PlayerEliminated, socket.id)
broadcastRoomState(game)
if (game.status === 'over') io.to(room).emit(ServerEvents.GameOver, { winnerId })
})
Testing it
Pure functions are a gift for testing: give the engine a board and a piece, check the board that comes back. The project has 111 unit tests in 24 files, all passing, with 96.5% statement coverage, run with Vitest.
Unit tests can't prove the whole protocol works, so a smoke test boots the real server, connects several clients with socket.io-client, and plays through full rounds: joining, starting, clearing every possible number of lines from zero to four, checking the penalties each opponent receives, and declaring the winner.
What I learned
- Send decisions, not data. One seed replaces a stream of pieces; ten column heights replace a full board. The less you send, the less can go wrong.
- Determinism is a feature you have to protect. The same generator must run on the server and in every browser, so it has to avoid anything that could differ between machines.
- Immutable state pays off. Pure functions made the engine easy to test, easy to plug into Redux, and easy to reuse here in a completely different page.
- A referee doesn't need to play. Keeping game logic in the clients kept the server small: rooms, seeds, relays and the end of the round.
About the project: red-tetris
A multiplayer Tetris built in a team of two: players open the same room URL and race on the same pieces, sending penalty lines to each other until one is left. A React and TypeScript client with a pure functional game engine, and a Node.js server with Express and Socket.IO.
- Team of 2
- 111 tests · 96% coverage
- Shared-seed sync
Built with
- React
- TypeScript
- Redux Toolkit
- Node.js
- Express
- Socket.IO
- Vite
- Vitest