Connect Four was the second game I added to mympgames, my free arcade of multiplayer browser games. Chess took me weeks. Connect Four took an evening, and the whole server-side rules file is still 86 lines. That small file taught me most of the patterns every other game on the site now follows, so I want to walk through it.

The rules, written down first

Before writing code I listed what the server actually has to enforce:

  1. The board is 7 columns by 6 rows.
  2. Players take turns. You can only act on your own turn.
  3. A move is "drop a disc in column N". The disc falls to the lowest empty cell.
  4. You can't drop into a full column.
  5. Four of your discs in a row (horizontal, vertical or either diagonal) wins.
  6. If the board fills with no winner, it's a draw.
  7. After the game ends, no more moves.

Every rule on that list maps to a line or two of code below.

State is plain data

const ROWS = 6; const COLS = 7; function createState() { return { board: Array.from({ length: ROWS }, () => Array(COLS).fill(null)), turn: 0, winner: null, winningCells: null, draws: false, }; } 

The board is a 2D array of null, 0 or 1 (the seat index of whoever owns the cell). Row 0 is the top. There are no classes and no methods on the state. That matters because the state has to be serialised to every player in the room after each move, and plain arrays and numbers survive JSON without any extra work.

Gravity is a reverse loop

function drop(board, col, player) { for (let r = ROWS - 1; r >= 0; r--) { if (board[r][col] == null) { board[r][col] = player; return r; } } return -1; } 

Start at the bottom row and walk up until you find an empty cell. Returning the row is the useful part: the win check needs to know exactly where the new disc landed. Returning -1 covers rule 4, the full column, without a separate check.

Win detection: only look around the last disc

The naive approach is to scan the whole board for four-in-a-row after every move. On a 42-cell board that's fine, but there's a simpler idea: a new win can only include the disc that was just played. So I only look outwards from that one cell.

function checkWin(board, row, col, player) { const dirs = [ [0, 1], // horizontal [1, 0], // vertical [1, 1], // diagonal down-right [1, -1], // diagonal down-left ]; for (const [dr, dc] of dirs) { const cells = [[row, col]]; for (const sign of [1, -1]) { let r = row + dr * sign; let c = col + dc * sign; while ( r >= 0 && r < ROWS && c >= 0 && c < COLS && board[r][c] === player ) { cells.push([r, c]); r += dr * sign; c += dc * sign; } } if (cells.length >= 4) return cells.slice(0, 4); } return null; } 

Four directions are enough because each one is walked both ways (sign of 1 and -1). Horizontal covers left and right, vertical covers up and down, and the two diagonals cover the other four. The loop collects matching cells until it hits an edge or a different colour.

Two details I like here:

  • It returns cells, not a boolean. The client uses winningCells to highlight the line that won. Players want to see why the game ended, especially when a sneaky diagonal finishes it.
  • slice(0, 4) and five in a row. If you drop a disc into the gap of X X _ X X, you get five. The array always starts with the dropped disc, then the cells in the positive direction, then the negative. Slicing to four still gives a valid winning line that includes the new disc. Highlighting four instead of five is a small tradeoff, but it keeps the UI consistent across games.

Worst case this checks a few dozen cells per move, no matter how full the board is.

One function decides every move

All the rules meet in onAction. Every game on the site exposes the same shape (createState, onAction, publicState), and the room server just calls it:

function onAction(state, playerIndex, action) { if (state.winner != null || state.draws) return { ok: false, error: 'Game over' }; if (playerIndex !== state.turn) return { ok: false, error: 'Not your turn' }; if (action.type !== 'drop') return { ok: false, error: 'Invalid action' }; const col = action.col; if (col < 0 || col >= COLS) return { ok: false, error: 'Invalid column' }; const row = drop(state.board, col, playerIndex); if (row < 0) return { ok: false, error: 'Column full' }; const win = checkWin(state.board, row, col, playerIndex); if (win) { state.winner = playerIndex; state.winningCells = win; } else if (state.board.every((r) => r.every((c) => c != null))) { state.draws = true; } else { state.turn = 1 - state.turn; } return { ok: true }; } 

Read it top to bottom and it's the rules list from earlier: game over, wrong turn, wrong action type, out-of-range column, full column, win, draw, next turn. The order matters. Validation comes before mutation, so a rejected move never half-changes the board.

The client never decides anything. It sends { type: 'drop', col: 3 } and waits. If someone opens devtools and sends a move out of turn, or column 99, the server answers with an error and the board doesn't change. That's the main reason I keep rules on the server for every multiplayer game, even simple ones.

Note that the turn only flips when the game continues. When someone wins, turn stays on the winner, which makes the "who won" UI trivial.

Sending state to the room

function publicState(state) { return { ...state, board: state.board.map((r) => [...r]) }; } 

Connect Four has no hidden information, so the public state is just a copy. In Battleship, the same function is where the opponent's ship positions get stripped out. Having the hook on every game, even when it does almost nothing, means I never forget it on the games where it matters.

The computer opponent is deliberately simple

When you play against the computer, the bot gets the same state and has to return a normal action that goes through the same onAction:

function connectFour(state, bot) { if (state.turn !== bot) return null; const cols = []; for (let c = 0; c < 7; c++) if (state.board[0][c] == null) cols.push(c); if (!cols.length) return null; // prefer center columns cols.sort((a, b) => Math.abs(a - 3) - Math.abs(b - 3)); return { type: 'drop', col: cols[0] }; } 

A column is open if its top cell is empty. The bot then prefers the centre, because centre discs take part in more possible lines. It doesn't look ahead, so it's beatable, which is honestly what most casual players want. A minimax search with alpha-beta pruning would fit in the same function signature if I ever want a hard mode, and because the bot can only send legal actions through onAction, a stronger bot couldn't cheat either.

What this file taught me

  • Make the rules a pure-ish module. Game files don't know about sockets, rooms or timers. That made them easy to test and easy to reuse for online rooms and the computer opponent.
  • Return errors instead of throwing. { ok: false, error } is cheap to send back to the client and easy to show as a toast.
  • Check only what changed. Looking around the last move is simpler and faster than scanning the board, and the same idea works for Gomoku-style games on bigger grids.
  • Keep the contract identical across games. With every game exposing the same three functions, the room server doesn't care whether it's running Connect Four or checkers.

If you want to see the rules in action, you can play Connect Four here against a friend or the computer, no download or sign-up needed. The rest of the 60+ free multiplayer games are at mympgames.com.