Advanced Connect4 AI using Alpha-Beta Pruning with 7 Strategic Optimizations
An intelligent Connect4 game featuring a competitive AI agent powered by minimax algorithm with alpha-beta pruning and seven advanced optimization techniques. Play via terminal or interactive web interface with real-time decision visualization.
- Alpha-Beta Pruning: Reduces search complexity from O(b^d) to O(b^(d/2))
- 7 Strategic Optimizations: 9.76ร speedup over baseline minimax
- Dynamic Depth Adjustment: Adapts search depth (6-12) based on performance
- Real-time Decision Making: Average 2-4 second response time
- Human vs AI: Challenge the AI at various difficulty levels
- AI vs AI: Watch Minimax battle against MCTS or Bitboard variants
- Random Start: AI can start first or human can begin
- Terminal Mode: Classic command-line gameplay
- Web Interface: Modern Flask-powered UI with visual board and analytics
- Game Theory Visualization: See Sโ, TO-MOVE, ACTIONS, RESULT, IS-TERMINAL, UTILITY
- Decision Process: Column-by-column minimax score breakdown
- AI Optimizations: Real-time display of active optimization techniques
- Performance Metrics: Thinking time, search depth, and node statistics
Python 3.8+
Flask 3.0.0 (for web interface)
NumPy# Clone repository
git clone https://github.com/oguzhansarigol/connect4-ai-agent.git
cd connect4-ai-agent
# Install dependencies
pip install Flask==3.0.0 numpypython main.pypython app.py
# Open browser at http://localhost:5000connect4-ai-agent/
โ
โโโ connect4/
โ โโโ game.py # Game engine (board, rules, victory detection)
โ โโโ agent.py # Alpha-Beta AI with optimizations
โ โโโ agent_bitboard.py # Bitboard-optimized variant
โ โโโ mcts_agent.py # Monte Carlo Tree Search implementation
โ โโโ mcts_agent_v2.py # Enhanced MCTS with transposition table
โ
โโโ templates/
โ โโโ index.html # Web interface HTML
โ
โโโ static/
โ โโโ style.css # UI styling
โ โโโ script.js # Frontend logic
โ
โโโ main.py # Terminal game launcher
โโโ app.py # Flask web server
โโโ compare_all_algorithms.py # Algorithm benchmarking tool
โโโ test_pruning_efficiency.py # Pruning optimization tests
โโโ README.md
function ALPHA-BETA-MINIMAX(board, depth, alpha, beta, maximizing):
if depth = 0 or GAME-OVER(board):
return HEURISTIC-EVAL(board)
if maximizing:
for each valid_move:
score = ALPHA-BETA-MINIMAX(new_board, depth-1, alpha, beta, false)
alpha = MAX(alpha, score)
if alpha โฅ beta:
break # Pruning!
return alpha
else:
for each valid_move:
score = ALPHA-BETA-MINIMAX(new_board, depth-1, alpha, beta, true)
beta = MIN(beta, score)
if alpha โฅ beta:
break # Pruning!
return beta| Optimization | Impact | Description |
|---|---|---|
| Alpha-Beta Pruning | 60-80% node reduction | Eliminates unpromising branches |
| Move Ordering โญโญโญโญโญ | 30-50% speedup | Prioritizes winning/threat-blocking moves |
| Transposition Table โญโญโญโญ | 20-40% speedup | Caches previously evaluated positions |
| Threat Detection โญโญโญ | 25% better strategy | Penalizes opponent three-in-a-row |
| Killer Moves โญโญโญโญ | 15-20% pruning | Remembers cutoff-causing moves per depth |
| Evaluation Board โญโญ | Strategic positioning | Weights center/middle rows higher |
| Center Column Bonus โญโญโญ | Tactical advantage | +3 bonus for center pieces |
Combined Result: 9.76ร speedup (baseline: 1143ms โ optimized: 198ms)
| Configuration | Avg Nodes | Avg Time (ms) | Pruning Ratio | Improvement |
|---|---|---|---|---|
| Baseline | 8,951 | 1,143.2 | 45.5% | โ |
| Move Ordering | 1,682 | 393.1 | 63.3% | 5.32ร faster |
| Killer Moves | 1,215 | 293.6 | 65.9% | 7.37ร faster |
| Full Heuristics | 917 | 197.9 | 62.1% | 9.76ร faster |
Test conditions: 15 mid-game positions, depth=6
| Matchup | Result | Avg Time |
|---|---|---|
| Alpha-Beta D6 vs MCTS 10K | 100% - 0% | 0.87s vs 0.22s |
| Alpha-Beta D6 vs MCTS 50K | 100% - 0% | 0.83s vs 11.14s |
| Bitboard D10 vs MCTS 50K | 90% - 10% | 0.44s vs 8.04s |
| Alpha-Beta D6 vs Bitboard D10 | 100% - 0% | 0.52s vs 0.24s |
Key Finding: Deterministic alpha-beta with heuristics dominates stochastic MCTS even at 50,000 iterations.
# Default: Human starts (Red), AI is Yellow
python main.py
# Different game modes available through web interface-
Control Panel
- Toggle Developer Mode
- Adjust AI search depth (6-12)
- Choose game mode (I Start / AI Starts / Random)
-
Developer Mode Panels
- Game Theory Model: Formal game state representation
- Decision Process: Column evaluation scores
- AI Optimizations: Active optimization techniques
-
AI vs AI Battle Mode
- Minimax (Alpha-Beta) vs MCTS
- Watch automated gameplay
- Performance comparison
python test_pruning_efficiency.pyCompares baseline, move ordering, killer moves, and full heuristics configurations.
python compare_all_algorithms.pyRuns tournaments between Alpha-Beta, Bitboard, and MCTS variants.
- Board Size: 6 rows ร 7 columns
- Player Encoding: AI=1, Human=-1, Empty=0
- Coordinate System: (0,0) at bottom-left corner
score = evaluate_window(window) + center_bonus + evaluation_board_weight- Window Analysis: Scores 69 four-cell windows (24 horizontal, 21 vertical, 24 diagonal)
- Scoring Rules:
- Four AI pieces: +100
- Three AI pieces + empty: +5
- Two AI pieces + two empty: +2
- Opponent threats: -4 (three pieces), -100 (four pieces)
if thinking_time < 3.0s and rounds โฅ 3:
depth += 1 # Max: 12
elif thinking_time > 6.0s:
depth -= 1 # Min: 6AI_DEPTH_MIN = 6 # Minimum search depth
AI_DEPTH_MAX = 12 # Maximum search depth
AI_DEPTH_DEFAULT = 8 # Starting depth
TARGET_THINKING_TIME = 4.0 # Target response time (seconds)config = {
'enable_move_ordering': True,
'enable_killer_moves': True,
'enable_transposition_table': True,
'enable_threat_detection': True
}Convert opening theory into JSON format for instant optimal moves in the first 4-6 plies, eliminating early-game computation.
Add UI feature to visualize alpha-beta cutoffs during search, showing which branches were pruned and whyโenhancing demo transparency.
Rewrite performance-critical components (board manipulation, window evaluation, minimax recursion) in C++ for 10-50ร additional speedup, targeting depth-12-15 searches in 1-2 seconds.
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Oฤuzhan Sarฤฑgรถl - Initial work - oguzhansarigol
- Alpha-beta pruning algorithm based on Russell & Norvig's "Artificial Intelligence: A Modern Approach"
- Game theory formalization follows standard adversarial search framework
- Optimization techniques inspired by chess engine development (Stockfish, AlphaZero)
Project Link: https://github.com/oguzhansarigol/connect4-ai-agent
โญ Star this repo if you found it helpful!