Video Demo: https://github.com/Alireza-njt/Connect-Four/releases/download/video/CS50.Python.Final.Project_Connect.4.with.Minimax.Alpha-Beta.Pruning.mp4
This project represents my final submission for Harvard's CS50 Introduction to Programming with Python course - a fully-functional Connect 4 implementation featuring an intelligent AI opponent. Designed for terminal/IDE environments, the game combines classic gameplay with modern artificial intelligence techniques.
The architecture draws inspiration from:
- Project 2 of CS50's AI course (Tic-Tac-Toe implementation)
- Traditional Minimax algorithm concepts
- Alpha-beta pruning optimizations
- Classic board game implementations
Initializes the game board as a 6x7 grid (standard Connect 4 dimensions) with all positions empty. The state is represented as a 2D list containing:
Redpieces (player/AI)Yellowpieces (player/AI)Emptyslots
Dynamically calculates all valid moves by:
- Scanning columns from bottom to top
- Identifying the first available empty slot
- Returning coordinates for valid moves
- Enforcing game rules (pieces fall to lowest available space)
Generates new game states by:
- Creating deep copies of the current state
- Validating move legality
- Applying player moves
- Preventing illegal state modifications
Implements victory detection through:
- Horizontal line checks (4-connected in rows)
- Vertical line checks (4-stacked in columns)
- Diagonal checks (both ascending and descending)
- Comprehensive board scanning
- Early termination when victory detected
Determines game conclusion by:
- Checking for any winning condition
- Verifying board fullness (draw condition)
- Providing immediate feedback for game over states
Quantifies game outcomes with:
- +1 for AI win
- -1 for player win
- 0 for draws/non-terminal states
- Supports Minimax evaluation
The intelligent core featuring:
- Depth-limited search (5-ply)
- Alpha-beta pruning optimization
- Recursive state evaluation
- Move prioritization
- Adaptive strategy based on game phase
Key obstacles overcome:
- State Representation: Efficient 2D list management
- Move Validation: Ensuring physical game rules
- AI Optimization: Balancing depth and performance
- Terminal Detection: Accurate game state evaluation
- User Interface: Clean terminal visualization
-
Visual Improvements:
- Colorama-powered colored output
- Pyfiglet ASCII art headers
- Formatted board display
-
Gameplay Features:
- Player color selection
- Turn-based alternation
- Win/draw detection
- Input validation
-
AI Capabilities:
- Competitive gameplay
- Strategic decision-making
- Performance optimization
- Run
python project.py - Select your preferred color (Red/Yellow)
- On your turn, enter a column number (1-7)
- Watch the AI respond with its move
- First to connect four wins!
Red always moves first (whether player or AI). The game continues until a player wins or the board fills completely (draw).
