Connect Four
Connect Four against a heuristic computer player.
Overview
Connect Four is the classic vertical-stacking strategy game played on a 6-row, 7-column grid. Players alternate dropping discs into columns; the disc falls to the lowest empty cell in that column. The first player to form a horizontal, vertical, or diagonal line of four discs wins; if the board fills with no winner, the game is a draw.
This implementation pits you against a heuristic computer opponent that evaluates the board with a positional score function — favouring central columns, looking ahead a few plies, and blocking your three-in-a-rows. It plays a reasonable amateur game but does not play the proven first-player-wins endgame from theory, so a strong human can beat it consistently.
How it works
The disc drop is gravity-constrained: dropping into column c places the new disc in the lowest empty row of c, which simplifies move generation to "one move per non-full column". The win check looks at the four directions through the just-placed disc — horizontal, vertical, and both diagonals — and walks outwards counting consecutive same-colour discs.
The AI uses minimax with alpha-beta pruning to a configurable depth. The leaf evaluation rewards central columns (column 3 is part of more potential four-in-a-rows than any edge column), counts the open-ended threes and twos for each side, and applies large bonuses or penalties for immediate wins or losses. Increasing search depth makes the AI noticeably stronger at the cost of a longer think time per move.
Examples
- Opening in the centre column is theoretically optimal — every winning line in Connect Four passes through at least one cell of column 3.
- A "seven trap" places three discs in a row with two open ends; the opponent can only block one side, and the next move wins.
- The classic odd-even threat strategy notes that player one can force wins on odd rows (rows 1, 3, 5) and player two on even rows.
- A solved-game database proves that with perfect play, player one wins; this AI does not implement that solver, so realistic upsets happen.
FAQ
Who has the advantage with perfect play?
Player one wins with perfect play if they open in the centre column. Any other opening allows player two to force a draw or win.
Why does the AI sometimes ignore my obvious threat?
At lower search depths the AI can miss threats that develop more than a few moves ahead. Increase depth for stronger play.
Is there a way to undo a move?
This version plays straight through. Resign and restart if you want a do-over.
Can the game end in a draw?
Yes — if all 42 cells are filled with no four-in-a-row, the result is a draw.
Are diagonal wins counted both ways?
Yes. Both the slash and backslash diagonals are valid winning lines.