Skip to content
bymayanksinghPublic

About

๐ŸŽฎ It is a two-player connection game in which the players first choose a color and then take turns dropping one colored disc from the top into a seven-column, six-row vertically suspended grid. The pieces fall straight down, occupying the lowest available space within the column, user wins by forming row of four of same color

Topics

Resources

Code of conduct

Stars

22 stars

Watchers

4 watching

Forks

Latest commit

ย 

History

265 Commits

Folders and files

NameName
Last commit message
Last commit date
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Connect Four Logo

Connect Four

Production-Grade Connect 4 Engine, Multi-Algorithm AI Suite & Headless Visualizer

Python 3.9+ Tests Build License: MIT


๐Ÿ“– Overview

Connect 4 is a modernized, production-ready implementation of the classic vertical connection game, engineered for high performance, modularity, and algorithmic depth.

Originally conceived as a Pygame application by Mayank Singh, this repository integrates community PRs, academic research from Columbia University on Markov Decision Processes (MDPs), and production software engineering practices:

  • Decoupled Architecture: Domain rules, board state, AI engines, terminal CLI, and Pygame presentation are separated into dedicated modules under connect4/.
  • Multi-Modal AI Suite:
    • Random Agent: Uniform random sampling over legal open columns.
    • Heuristic Agent: Fast tactical 1-ply immediate win execution, threat blocking, and center preference.
    • Minimax Agent: Deep tree search with $\alpha\text{-}\beta$ pruning, center-first move ordering, and an Odd-Even strategy heuristic.
    • Dynamic Programming (MDP) Agent: Finite-horizon value iteration and exact linear system solving ($(I - \gamma P)^{-1} R$) over transition probability matrices.
  • Multi-Modal User Interfaces:
    • Pygame Desktop GUI: Smooth animations, theme customizer (Red/Yellow, Green/Violet, Neon/Dark Blue, Monochrome), sound effects, and runtime diagnostics panel.
    • Interactive ANSI Terminal: Unicode disc display (๐Ÿ”ด, ๐ŸŸก, โšช), full keyboard command parsing (undo, restart, quit), and 1-based indexing.
    • Headless Benchmarking: Automated headless tournament runner simulating AI vs AI matches with statistical reporting.
  • Configurable Dimensions & Win Conditions: Arbitrary grid sizes (e.g. Standard 7ร—6 Connect 4, Mini 4ร—3 Connect 3, Large 8ร—7 Connect 4, or Custom Nร—M).
  • Automated Visualization Pipeline: Export any board state directly to standalone SVG vector graphics or Graphviz DOT graphs.
  • 100% Automated Test Coverage: 38 unit and integration tests covering board mechanics, win detection, AI decision quality, CLI commands, and headless rendering.

๐ŸŽจ Visual Showcase

Gameplay & Active HUD Victory Celebration & Laser Main Menu & Customization
Connect 4 Gameplay Connect 4 Victory Celebration Connect 4 Modern Menu

๐Ÿค Community Pull Request Integration Audit

Every community pull request submitted to the repository has been audited, preserved, and elevated into the modern modular architecture:

PR # Author / Branch Original Contribution Modernized Production Implementation
#44 official-Auralin Columbia Univ. MDP Dynamic Programming & parameter sweep Modern MDP Agent (dp_agent.py), closed-form linear solver $(I - \gamma P)^{-1} R$, and scripts/param_sweep.py
#42 Pabloo22 Minimax agent with $\alpha\text{-}\beta$ pruning & Odd-Even heuristic Production Minimax engine (minimax.py) with parity evaluation and center-first move ordering
#39 adnansalik 1-ply tactical heuristic AI High-speed Heuristic Agent (heuristic_agent.py) for immediate win taking and threat blocking
#38 / #35 Xx-Ashutosh-xX / ajaykumarr123 Color themes (Violet, Yellow, darkBlue, gray, green, neonBlue) Modern theme system in config.py & live in-game cycling via key T or GUI theme picker
#36 / #33 KomalKalyan Interactive Start & Quit menu buttons and layout improvements Redesigned capsule buttons, animated drifting background discs in menu.py
#32 / #18 amanpalariya Support for arbitrary board dimensions and Connect-N Generalized GameBoard and BoardDimensions supporting 4ร—3 mini, 7ร—6 standard, 8ร—7 large
#28 amanpalariya Coin drop animation & board patterns Realistic gravity physics drop animation with micro-bounce & audio sync in renderer.py
#24 / #22 Satvinder31415 Test directory and basic win assertions Comprehensive 38-test suite in tests/ covering win conditions, ties, AI agents, CLI, and GUI
#14 Satvinder31415 Move undo bug fixes Stack-based undo/redo with board state integrity in game.py
#34 Cypre55 Hall of Fame section Contributor attribution and Hall of Fame recognized in documentation

๐Ÿ›๏ธ Architecture & Project Hierarchy

connect4/
โ”œโ”€โ”€ pyproject.toml              # PEP 517/621 packaging & pytest configurations
โ”œโ”€โ”€ setup.py                    # Setuptools package definition
โ”œโ”€โ”€ requirements.txt            # Core production dependencies (pygame, numpy, event-bus)
โ”œโ”€โ”€ requirements-dev.txt        # Development dependencies (pytest, pytest-cov, ruff)
โ”œโ”€โ”€ Makefile                    # Developer workflow automation
โ”œโ”€โ”€ connect4/                   # Main Python application package
โ”‚   โ”œโ”€โ”€ types.py                # Domain models, Enums (Player, GameMode, AIDifficulty)
โ”‚   โ”œโ”€โ”€ config.py               # Theme palettes, geometry constants, asset locations
โ”‚   โ”œโ”€โ”€ board.py                # Pure GameBoard logic, gravity, win checks & serialization
โ”‚   โ”œโ”€โ”€ game.py                 # Core game session controller, turns & undo/redo stack
โ”‚   โ”œโ”€โ”€ events.py               # Decoupled EventBus and message dataclasses
โ”‚   โ”œโ”€โ”€ cli.py                  # Terminal interactive mode, benchmark runner, JSON mode
โ”‚   โ”œโ”€โ”€ ai/                     # Artificial Intelligence engine package
โ”‚   โ”‚   โ”œโ”€โ”€ base.py             # Abstract Base Class for AI agents
โ”‚   โ”‚   โ”œโ”€โ”€ random_agent.py     # Random selection
โ”‚   โ”‚   โ”œโ”€โ”€ heuristic_agent.py  # Fast tactical win/block heuristic
โ”‚   โ”‚   โ”œโ”€โ”€ minimax.py          # Minimax with alpha-beta & Odd-Even heuristic
โ”‚   โ”‚   โ”œโ”€โ”€ dp_agent.py         # Dynamic Programming & linear algebra MDP solver
โ”‚   โ”‚   โ”œโ”€โ”€ game_state.py       # State space hashable representation for MDP
โ”‚   โ”‚   โ””โ”€โ”€ factory.py          # Unified AgentFactory
โ”‚   โ”œโ”€โ”€ gui/                    # Desktop presentation package
โ”‚   โ”‚   โ”œโ”€โ”€ app.py              # Main Pygame application loop & screen manager
โ”‚   โ”‚   โ”œโ”€โ”€ renderer.py         # Board rendering, animations & console panel
โ”‚   โ”‚   โ”œโ”€โ”€ menu.py             # Interactive buttons, state selectors & themes
โ”‚   โ”‚   โ””โ”€โ”€ assets.py           # Safe asset loader with procedural fallbacks
โ”‚   โ””โ”€โ”€ visualizer/             # Diagram and vector export pipeline
โ”‚       โ””โ”€โ”€ export.py           # ASCII, SVG vector, and Graphviz DOT exporters
โ”œโ”€โ”€ assets/                     # Media files (images, theme sprites, sounds)
โ”‚   โ”œโ”€โ”€ images/
โ”‚   โ””โ”€โ”€ sounds/
โ”œโ”€โ”€ tests/                      # Automated test suite (38 tests)
โ”‚   โ”œโ”€โ”€ conftest.py             # Headless fixtures
โ”‚   โ”œโ”€โ”€ test_board.py           # Board mechanics & serialization
โ”‚   โ”œโ”€โ”€ test_win_conditions.py  # Connect-N, diagonals, verticals, ties
โ”‚   โ”œโ”€โ”€ test_game_flow.py       # Turn switching, undo/redo, restart
โ”‚   โ”œโ”€โ”€ test_ai_agents.py       # Decision verification for all AI algorithms
โ”‚   โ”œโ”€โ”€ test_agent_factory.py   # Factory validation
โ”‚   โ”œโ”€โ”€ test_cli.py             # CLI parser and tournament tests
โ”‚   โ”œโ”€โ”€ test_visualizer.py      # SVG/DOT/ASCII export verification
โ”‚   โ””โ”€โ”€ test_gui_headless.py    # Headless GUI rendering tests
โ”œโ”€โ”€ scripts/                    # Developer tools & research scripts
โ”‚   โ”œโ”€โ”€ param_sweep.py          # MDP parameter sweep (gamma vs horizon)
โ”‚   โ”œโ”€โ”€ benchmark_ai.py         # AI tournament execution CLI
โ”‚   โ””โ”€โ”€ export_diagram.py       # Board diagram exporter
โ””โ”€โ”€ legacy/                     # Historical prototype archive
    โ””โ”€โ”€ v1_original/

โšก Quickstart & Installation

Option 1: Using uv (Recommended)

# Clone the repository
git clone https://github.com/bymayanksingh/connect4.git
cd connect4

# Create virtual environment and install dependencies
uv venv
source .venv/bin/activate
uv pip install -r requirements.txt -r requirements-dev.txt

Option 2: Using standard pip & make

python3 -m venv .venv
source .venv/bin/activate
make dev-install

๐ŸŽฎ How to Play

1. Graphical User Interface (Pygame)

Launch the graphical game with full menu support, board size selection, and theme customization:

python game.py
# or
python -m connect4 --gui

GUI Controls:

  • Mouse Movement: Move the disc preview over the desired column.
  • Left Click: Drop piece into the column.
  • Ctrl + Z: Undo last move (in Player vs AI mode, undos both moves).
  • R: Restart game session.
  • Esc: Return to Main Menu.

2. Interactive Terminal CLI

Play directly in your terminal with rich ANSI coloring and Unicode disc indicators:

# Human vs Human (PvP)
python -m connect4 --mode pvp

# Human vs AI (PvA) with Minimax AI
python -m connect4 --mode pva --ai hard

# Custom board dimensions (e.g. 8x7 Connect 4)
python -m connect4 --rows 7 --cols 8 --connect 4
โ•”โ•โ•โ•โ•ฆโ•โ•โ•โ•ฆโ•โ•โ•โ•ฆโ•โ•โ•โ•ฆโ•โ•โ•โ•ฆโ•โ•โ•โ•ฆโ•โ•โ•โ•—
โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘
โ• โ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฃ
โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘
โ• โ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฃ
โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘ ๐Ÿ”ด โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘
โ• โ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฃ
โ•‘ โšช โ•‘ โšช โ•‘ ๐ŸŸก โ•‘ ๐Ÿ”ด โ•‘ โšช โ•‘ โšช โ•‘ โšช โ•‘
โ• โ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฌโ•โ•โ•โ•ฃ
โ•‘ โšช โ•‘ ๐ŸŸก โ•‘ ๐Ÿ”ด โ•‘ ๐Ÿ”ด โ•‘ ๐ŸŸก โ•‘ โšช โ•‘ โšช โ•‘
โ•šโ•โ•โ•โ•ฉโ•โ•โ•โ•ฉโ•โ•โ•โ•ฉโ•โ•โ•โ•ฉโ•โ•โ•โ•ฉโ•โ•โ•โ•ฉโ•โ•โ•โ•
   1   2   3   4   5   6   7

Player 1 (Red) > 4

3. Headless AI Tournament Benchmarking

Run high-speed automated tournaments between any two AI engines:

python -m connect4 --benchmark --ai1 hard --ai2 easy -n 10
============================================================
         CONNECT 4 HEADLESS BENCHMARK TOURNAMENT
============================================================
Agent 1 (Player 1 - Red):    P1 (hard)
Agent 2 (Player 2 - Yellow): P2 (easy)
Board size:                  7x6 (Connect 4)
Matches scheduled:           10
------------------------------------------------------------
Game  1/10: P1 WIN  in  9 moves (0.385s)
Game  2/10: P1 WIN  in  9 moves (0.381s)
...
------------------------------------------------------------
                     FINAL RESULTS
------------------------------------------------------------
Agent 1 (hard) Wins: 10 (100.0%)
Agent 2 (easy) Wins: 0 (0.0%)
Draws:                   0 (0.0%)
Avg Moves per Match:     9.0
Total Wall-Clock Time:   3.821s (0.382s/game)
============================================================

4. Vector SVG & Graphviz Diagram Export

Export any board state into vector SVG or Graphviz DOT format:

# Export board state on game over
python -m connect4 --export-svg docs/board.svg --export-dot docs/board.dot

# Or run the export script
python scripts/export_diagram.py --svg docs/board.svg --dot docs/board.dot
Connect Four Vector Board

๐Ÿง  AI Algorithms & Theoretical Foundations

1. Markov Decision Process (MDP) & Linear Algebra Solver

Connect 4 is formalized as a zero-sum, deterministic MDP $(S, A, T, R, \gamma)$:

  • State space ($S$): Board configurations $(r \times c)$ and turn indicator $t \in {0, 1}$.
  • Action space ($A(s)$): Legal open columns.
  • Transition ($T(s, a)$): Deterministic gravity drop $s' = T(s, a)$.
  • Reward ($R$): $+200$ for win, $-200$ for loss, $0$ for draw, $-0.01$ step cost.

Under stationary policy $\pi$, the Bellman expectation equation:

$$V^{\pi} = R^{\pi} + \gamma P^{\pi} V^{\pi}$$

is rearranged into a solvable linear system:

$$(I - \gamma P^{\pi}) V^{\pi} = R^{\pi} \implies V^{\pi} = (I - \gamma P^{\pi})^{-1} R^{\pi}$$

DPAgent enumerates reachable states within horizon $H$, builds the transition matrix $P$, and computes exact values using numpy.linalg.solve.

Run parameter sweeps over discount factor $\gamma$ and horizon $H$:

python scripts/param_sweep.py

2. Minimax with $\alpha\text{-}\beta$ Pruning & Odd-Even Strategy

MinimaxAgent explores the game tree up to depth 5 with:

  • Alpha-Beta Pruning: Prunes branches that cannot influence the final decision.
  • Center-First Move Ordering: Prioritizes central columns to trigger earlier $\alpha\text{-}\beta$ cutoffs.
  • Odd-Even Heuristic: Incorporates parity theoryโ€”favoring odd-row control for Player 1 and even-row control for Player 2.

๐Ÿงช Testing & Quality Assurance

The codebase includes 38 automated tests verifying:

  • Core board mechanics, gravity, full-column rejection, bounds safety.
  • Complete win conditions (horizontal, vertical, both diagonals, Connect-N generalizations, tie games).
  • AI decision-making (immediate wins, defensive blocks, center preference, linear algebra solver).
  • CLI commands, headless tournament execution, and JSON output.
  • Headless Pygame surface generation and rendering.

Run all tests via:

make test
# or
pytest -v
============================= test session starts ==============================
tests/test_agent_factory.py ....                                         [ 10%]
tests/test_ai_agents.py ......                                           [ 27%]
tests/test_board.py ........                                             [ 48%]
tests/test_cli.py .                                                      [ 51%]
tests/test_dp_agent_tiny.py .                                            [ 54%]
tests/test_game_flow.py .....                                            [ 67%]
tests/test_gui_headless.py ..                                            [ 72%]
tests/test_visualizer.py ....                                            [ 83%]
tests/test_win_conditions.py ......                                      [100%]
============================== 38 passed in 14.33s =============================

๐Ÿ“„ License

This project is licensed under the MIT License. Original implementation by Mayank Singh. MDP research contributions by Bobby Veihman (Columbia University).

About

๐ŸŽฎ It is a two-player connection game in which the players first choose a color and then take turns dropping one colored disc from the top into a seven-column, six-row vertically suspended grid. The pieces fall straight down, occupying the lowest available space within the column, user wins by forming row of four of same color

Topics

Resources

Code of conduct

Stars

22 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages