Skip to content

A Connect 4 game built with Python and Pygame, featuring an AI opponent powered by the Minimax algorithm with alpha-beta pruning and iterative deepening.

Notifications You must be signed in to change notification settings

CooL-Legend/Connect4

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Connect 4 - Minimax AI

A Connect 4 game built with Python and Pygame, featuring an AI opponent powered by the Minimax algorithm with alpha-beta pruning and iterative deepening.

Features

  • Minimax AI with Alpha-Beta Pruning — Efficient game tree search with configurable depth
  • Iterative Deepening — Progressively deeper search for stronger play within time constraints
  • Transposition Table — Caches evaluated positions to avoid redundant computation
  • Heuristic Board Evaluation — Scores non-terminal positions based on threats, center control, and blocking potential
  • Two Game Modes:
    • AI vs AI — Watch two Minimax agents battle it out
    • AI vs Human — Play against the AI as Player 2 (Yellow)

Getting Started

Prerequisites

  • Python 3.8+
  • Pygame

Installation

pip install pygame

Running the Game

AI vs AI (default):

python main.py

AI vs Human:

python main.py --p2 human

Controls

Key / Action Description
Mouse click Drop a piece (Human mode, Player 2 only)
R Restart the game
Close window Quit

Project Structure

Connect4/
├── main.py              # Pygame GUI and game loop
├── engine_C4.py         # Game engine: state, legal moves, win detection, board evaluation
├── Minimax_agent.py     # Minimax agent with alpha-beta pruning and iterative deepening
└── README.md

How It Works

The game engine represents the board as a flat tuple of 42 cells (6 rows x 7 columns). Players are encoded as +1 (Red) and -1 (Yellow).

The Minimax agent searches the game tree using:

  1. Iterative Deepening — Searches depth 1, then 2, ..., up to max_depth, so the best move found so far is always available
  2. Alpha-Beta Pruning — Cuts off branches that can't influence the final decision, dramatically reducing the search space
  3. Heuristic Evaluation — At the depth limit, positions are scored by counting threats (2-in-a-row, 3-in-a-row), center column control, and blocking urgency
  4. Transposition Table — Memoizes evaluated states to skip duplicate subtrees

Player 1 (Red) uses depth 5 and Player 2 (Yellow) uses depth 4 by default.

About

A Connect 4 game built with Python and Pygame, featuring an AI opponent powered by the Minimax algorithm with alpha-beta pruning and iterative deepening.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages