An Advanced Browser-Based Connect-4 Engine with a Non-Blocking Minimax AI, Web Worker Architecture, and Performance Benchmarking Capabilities
This repository presents a sophisticated, browser-based simulation of the classic two-player game Connect-4, architected to function as both a robust interactive experience and a computational research platform. The design is grounded in principles of algorithmic game theory and AI education, with a core innovation being the execution of a recursive minimax AI within a dedicated Web Worker thread. This architectural decision, orchestrated by a modular index.js
controller, completely decouples computationally intensive search operations from the main browser thread, thereby eliminating UI blocking and ensuring a seamlessly responsive user experience, even during deep computational searches.
Operating on a game board with a state-space complexity of approximately 4.53 trillion reachable positions, this project consciously situates itself within the fifty-year academic tradition of utilizing Connect-4 as a model system for evaluating combinatorial search algorithms. It serves as a model web-native research platform that mirrors the academic rigor and technical excellence characteristic of leading research institutions, providing a high-fidelity simulation, a robust tool for performance benchmarking, and an extensible pedagogical platform for computer science education.
- A modern web browser with comprehensive support for ECMAScript 6 (ES6) features and the Web Worker API.
- A local HTTP server is mandated for static asset delivery. This is a necessary condition for loading worker scripts due to cross-origin security policies enforced by modern browsers. Direct
file://
access is not supported.
-
Clone the Repository: Procure a local copy of the source code via Git.
git clone [https://github.com/CodeKunalTomar/Connect-4.git](https://github.com/CodeKunalTomar/Connect-4.git) cd Connect-4
-
Initiate a Local Server: Select a method appropriate for the local development environment.
# For systems with Python 3 installed python3 -m http.server 8000 # For legacy systems with Python 2 python -m SimpleHTTPServer 8000 # For environments with Node.js, using a common package npx live-server
-
Access the Application: Navigate a web browser to the server's address, typically
http://localhost:8000
.
A clean separation of concerns is maintained across the codebase, ensuring academic clarity, modularity, and extensibility. The introduction of index.js
as a central controller formalizes the communication protocol between the user interface (View) and the game engine (Model/Worker).
src/
├── connect-4.html # Semantic HTML5 structure, user controls, and minimal initialization scripts.
├── connect-4.css # Advanced CSS for visual styling, keyframe animations, and responsive media queries.
├── connect-4.js # Core game logic, AI implementation (minimax), and state evaluation; encapsulated to run exclusively inside the Web Worker.
├── index.js # Application orchestrator (Controller); manages UI event wiring, Web Worker lifecycle, and state synchronization.
└── assets/
├── board.png # Background board graphics.
├── p1-chip.png # Player 1 token sprite.
└── p2-chip.png # Player 2 token sprite.
The key architectural upgrade is the role of index.js
as an intermediary that manages the entire asynchronous handshake between user actions, UI updates, and AI computation. This decouples the user experience completely from the computational logic, a critical design pattern for modern, performant web applications.
Component | Role |
---|---|
connect-4.html |
Provides the Document Object Model (DOM) structure, user controls for difficulty selection (which corresponds to AI search depth), and the primary game interface. It serves as the static entry point for the application. |
connect-4.css |
Governs the responsive layout using modern CSS properties, manages all chip and board animations via keyframes and transitions, and defines an accessible, high-contrast color scheme compliant with WCAG standards. |
connect-4.js |
(Web Worker Context) Contains the pure, stateful logic of the game engine. This includes the board data structures, the recursive minimax AI implementation, win/tie detection algorithms, and available-move resolution. It runs entirely off the main thread, operating as a headless engine. |
index.js |
(Main Thread Controller) Acts as the application's central nervous system. It handles all user input events, manages game state transitions (e.g., from player turn to AI turn), spawns and communicates with the AI Worker via the postMessage /onmessage API, and marshals data to update the UI. |
- Concurrency Management: Spawns and manages a dedicated Web Worker, isolating all computationally intensive AI logic to a separate thread. This is the cornerstone of the application's performance architecture.
- Non-Blocking UI: Decouples UI event handling from the "hot path" of AI calculation. This results in zero blocking of the main thread, guaranteeing a 60fps experience even when the AI is performing a deep search.
- State Machine Implementation: Cleanly defines and manages UI state transitions for all playable events (e.g.,
game-in-progress
,game-over
,awaiting-input
), ensuring predictable application behavior. - User Feedback System: Centralizes the management of UI prompts (the "blurb" and "outlook" text fields) to provide clear, consistent feedback to the user about the game's status.
- Animation Orchestration: Handles the triggering of CSS animations and board updates in response to both AI- and player-initiated moves, ensuring visual and logical synchronization.
The AI utilizes a recursive Minimax algorithm with user-configurable depth. All search and computation steps are offloaded to the Worker, whose responses drive the main-thread UI updates via a formal, asynchronous message-passing protocol. This prevents the AI's "thinking" time from freezing the user interface.
// 1. A human player interacts with a column on the board.
// index.js captures the click event and sends the intended move to the worker for validation and state update.
worker.postMessage({ messageType: 'human-move', col: columnIndex });
// 2. Upon successful validation, the worker confirms the move, and it becomes the computer's turn.
// index.js requests an AI move from the worker, passing the user-selected difficulty (search depth).
worker.postMessage({ messageType: 'computer-move', maxDepth: userSelectedDepth });
// 3. The worker begins its recursive minimax search. This computation occurs entirely in the background thread.
// Upon finding the optimal move, the worker serializes the result and sends it back to the main thread.
// index.js listens for the completion event via its 'onmessage' handler.
worker.addEventListener('message', function(e) {
if (e.data.messageType === 'computer-move-done') {
// 4. Update the UI with the AI's move.
// This includes animating the chip drop into the correct column and checking for a win/tie condition.
handleAiMove(e.data.move);
}
});
This event-driven, asynchronous architecture ensures that all game events (start, win, tie, move, reset) are fully synchronized between the main thread (view) and the worker thread (model/controller) without ever compromising UI responsiveness.
Feature | Implementation Detail | Technical Implication |
---|---|---|
Game Board | 7x7 grid (a deliberate deviation from the standard 6x7) | Enlarges the state space and branching factor, presenting a unique and more complex challenge for the AI and altering the lines of play established in solved-game theory for the 6x7 board. |
Victory Condition | Formation of a contiguous line of four tokens (horizontal, vertical, or diagonal) | Evaluated via an efficient board scan algorithm that checks only relevant vectors from the last-placed piece, achieving O(1) complexity per move relative to board size. |
AI Opponent | Minimax with randomized tie-breaking | Provides a deterministic and strategically sound opponent, while the randomization of equally-scored moves prevents repetitive, predictable play patterns. |
Move Validation | Gravity-based column check and overflow prevention | Guarantees strict rule compliance and ensures the integrity of the game state by rejecting invalid moves before they are processed. |
Visual Feedback | CSS/JS-driven hover, drop, and winning-line highlight animations | Delivers real-time, responsive user interactions that provide clear visual cues about game state and potential moves, enhancing playability. |
The Web Worker architecture fundamentally changes the performance profile of the application from the user's perspective, separating raw computational throughput from perceived UI fluidity.
Implementation | Positions/sec (approx) | AI Depth Max | Platform | Main Thread Blocking | UI Responsiveness |
---|---|---|---|---|---|
This Project (Worker Arch.) | ~240,000 | 4 | Web (JS) | No | Always (60fps) |
Fhourstones (classic C) | 12,000,000 | 8+ | Desktop | N/A | N/A |
GameSolver.org (native C++) | >20,000,000 | 12 | Native/C++ | N/A | N/A |
- Memory Management: Each game state node created during the recursive search occupies approximately 200 bytes. Memory is safely managed within the transient worker stack. Since the worker operates in its own memory space, its allocations do not impact the main thread's performance. Upon completion of the search, the worker's memory is automatically garbage-collected, preventing memory leaks.
- Frame Rate Consistency: A consistent 60 frames per second is maintained at all times, regardless of AI difficulty. This is a direct result of the complete isolation of the main rendering thread from the AI's computational workload, a critical factor for positive Core Web Vitals and user satisfaction.
- Academic Tradition: This project continues the legacy of Allis, Allen, and Tromp, who established Connect-4 as a canonical problem for studying adversarial search, perfect play, and computational benchmarking. It takes their foundational work from the realm of native C/C++ into the modern, universally accessible web platform.
- Modern Architectural Edge: This may be considered a reference implementation of a web-based Connect-4 engine that achieves a seamless, academic-grade fusion of non-blocking AI and user experience. It serves as a practical demonstration of how to build performant, computationally intensive applications for the web.
- Pedagogical Platform: It serves as an excellent tool for demonstrating not only classical adversarial search (Minimax) but also modern web architecture. It provides a clear, inspectable example of critical concepts such as concurrency, Web Workers, asynchronous event handling, and the separation of concerns in application design.
Phase | Roadmap Milestone - | Status |
---|---|---|
Foundation | True Web Worker concurrency, modular index.js controller |
✅ Complete |
Algorithmic Optimization | Implement alpha-beta pruning, refactor to a bitboard state representation | ⏳ Next Up |
AI Extension | Integrate endgame tablebases, develop NN/MCTS hybrid agents | 📝 Planned |
Feature Expansion | Implement networked multiplayer, develop an adaptive benchmarking suite | 📝 Planned |
Research Platform | Design a plug-and-play AI module interface, add an analytics dashboard | 📝 Planned |
This project is licensed under the MIT License, granting broad permissions for academic, personal, and commercial use.
For academic use, please cite this work as follows:
@software{Tomar_Connect-4_2024_Web_Worker,
author = {Tomar, Kunal},
title = {{Connect-4: A Computational Game Theory Implementation with a Non-Blocking Web Worker Architecture}},
year = {2024},
publisher = {GitHub},
journal = {GitHub repository},
url = {[https://github.com/CodeKunalTomar/Connect-4](https://github.com/CodeKunalTomar/Connect-4)}
}
Built with a commitment to computational game theory and educational excellence.
⭐ Star this repo | 🍴 Fork | 💬 Discussions
“In the tradition of Fhourstones, advancing the art of web-based AI and game theory education.”