Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 87 additions & 21 deletions Connect-4.css
Original file line number Diff line number Diff line change
Expand Up @@ -55,51 +55,117 @@ h2 {
border-radius: 8px;
}

/* Setup Panel - Mode Selection */
.setup-panel h2 {
margin-bottom: 12px;
text-align: center;
}

.mode-select {
display: flex;
gap: 10px;
margin-bottom: 0;
}

.mode-btn {
flex: 1;
padding: 15px 10px;
background-color: rgba(255, 255, 255, 0.1);
border: 2px solid #666;
border-radius: 8px;
color: #ccc;
cursor: pointer;
transition: all 0.3s ease;
text-align: center;
font-family: "Doppio One", sans-serif;
font-size: 14px;
}

.mode-btn:hover {
background-color: rgba(255, 255, 255, 0.2);
border-color: #999;
}

.mode-btn.selected {
background-color: #593f6b;
border-color: #fff;
color: #fff;
}

.mode-btn .icon {
font-size: 24px;
display: block;
margin-bottom: 5px;
}

.mode-btn:focus {
outline: none;
Copy link

Copilot AI Dec 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing outline on focus creates an accessibility issue for keyboard users who need visual indication of which element has focus. Consider using a custom focus style instead of removing it entirely.

Suggested change
outline: none;
outline: none;
box-shadow: 0 0 0 3px #fff, 0 0 8px 2px #593f6b;
border-color: #fff;

Copilot uses AI. Check for mistakes.
}

/* Timer Panel */
.timer-panel {
display: flex;
flex-direction: column;
gap: 10px;
padding: 15px;
gap: 8px;
padding: 12px;
}

.timer {
padding: 15px;
padding: 12px;
background-color: rgba(255, 255, 255, 0.1);
border-radius: 8px;
font-family: "Doppio One", monospace;
text-align: center;
border: 2px solid transparent;
transition: all 0.3s ease;
display: flex;
justify-content: space-between;
align-items: center;
}

.timer-label {
font-size: 14px;
color: #aaa;
font-family: "Doppio One", sans-serif;
}

.timer-value {
font-size: 24px;
font-family: "Courier New", monospace;
color: #fff;
font-weight: bold;
}

.timer.active {
border-color: #4CAF50;
box-shadow: 0 0 15px rgba(76, 175, 80, 0.5);
background-color: rgba(76, 175, 80, 0.2);
box-shadow: 0 0 10px rgba(76, 175, 80, 0.4);
background-color: rgba(76, 175, 80, 0.15);
}

.timer.active .timer-label {
color: #4CAF50;
}

.timer.warning {
border-color: #f44336;
background-color: rgba(244, 67, 54, 0.2);
animation: pulse 1s infinite;
border-color: #ff9800;
background-color: rgba(255, 152, 0, 0.15);
}

@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.6; }
.timer.warning .timer-value {
color: #ff9800;
}

.timer-label {
font-size: 14px;
color: #aaa;
margin-bottom: 5px;
.timer.critical {
border-color: #f44336;
background-color: rgba(244, 67, 54, 0.15);
animation: pulse-critical 0.5s infinite;
}

.timer-value {
font-size: 32px;
color: #fff;
font-weight: bold;
.timer.critical .timer-value {
color: #f44336;
}

@keyframes pulse-critical {
0%, 100% { opacity: 1; }
50% { opacity: 0.7; }
}

/* Start Panel */
Expand Down
18 changes: 18 additions & 0 deletions Connect-4.js
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,9 @@ self.addEventListener('message', function(e) {
case 'human-move':
makeHumanMove(e.data.col);
break;
case 'player2-move':
makePlayer2Move(e.data.col);
break;
case 'computer-move':
makeComputerMove(e.data.maxDepth);
break;
Expand Down Expand Up @@ -340,6 +343,21 @@ function makeHumanMove(col) {
});
}

function makePlayer2Move(col) {
// coords is undefined if the move is invalid (column is full)
const coords = currentGameState.makeMove(2, col);
const isWin = currentGameState.isWin();
const winningChips = currentGameState.winningChips;
const isBoardFull = currentGameState.isBoardFull();
self.postMessage({
messageType: 'player2-move-done',
coords: coords,
isWin: isWin,
winningChips: winningChips,
isBoardFull: isBoardFull
});
}

function makeComputerMove(maxDepth) {
let col;
let isWinImminent = false;
Expand Down
79 changes: 44 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,16 @@
---
## I. Abstract

OptiConnect is a challenging, browser-based Connect-4 experience featuring a **single elite AI opponent** and **chess-style countdown timers**. This game combines sophisticated AI algorithms with time pressure to create an engaging, competitive experience that tests both strategic thinking and decision-making under time constraints.
OptiConnect is a challenging, browser-based Connect-4 experience featuring **two game modes** (VS AI and Two-Player) with **chess-style cumulative timers**. This game combines sophisticated AI algorithms with time pressure to create an engaging, competitive experience that tests both strategic thinking and decision-making under time constraints.

The game features:
- **Two Game Modes**: Challenge the Elite AI or play against a friend locally with Two-Player mode
- **Elite AI Opponent**: A powerful AI using depth-9 minimax search with alpha-beta pruning, transposition tables, and positional heuristics - designed to win approximately 80% of games against human players
- **Chess-Style Timers**: Each player starts with 5 minutes and gains a 5-second increment after each move, creating urgency and excitement
- **Chess-Style Cumulative Timers**: Each player starts with 2 minutes total time that counts down during their turns, creating intense time pressure
- **Non-Blocking Architecture**: All AI computation runs in a Web Worker thread, ensuring smooth 60fps UI performance
- **Advanced Optimizations**: Bitboard representation, Zobrist hashing, center-column move ordering, and opening book

The AI is calibrated to be challenging yet beatable, encouraging players to improve their analytical skills through repeated play. Can you be among the 20% who defeat the elite AI?
In VS AI mode, the AI is calibrated to be challenging yet beatable, encouraging players to improve their analytical skills through repeated play. Can you be among the 20% who defeat the elite AI?

---
## II. Local Deployment Protocol
Expand Down Expand Up @@ -83,18 +84,19 @@ The key architectural upgrade is the role of `index.js` as an intermediary that

| Component | Role |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`index.html`** | Provides the Document Object Model (DOM) structure, timer displays, Start Game button, 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, styles the timer displays with active/warning states, and defines an accessible, high-contrast color scheme. |
| **`Connect-4.js`** | **(Web Worker Context)** Contains the pure, stateful logic of the game engine. This includes the board data structures, the elite AI implementation with depth-9 minimax search, win/tie detection algorithms, position evaluation, move ordering, and opening book. It runs entirely off the main thread. |
| **`index.js`** | **(Main Thread Controller)** Acts as the application's central nervous system. It handles all user input events, manages timer state and countdown logic, controls game state transitions, spawns and communicates with the AI Worker via the `postMessage`/`onmessage` API, and updates the UI. |
| **`index.html`** | Provides the Document Object Model (DOM) structure, game mode selection (VS AI / Two-Player), timer displays, Start Game button, 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, styles the game mode selection and timer displays with active/warning/critical states, and defines an accessible, high-contrast color scheme. |
| **`Connect-4.js`** | **(Web Worker Context)** Contains the pure, stateful logic of the game engine. This includes the board data structures, the elite AI implementation with depth-9 minimax search, win/tie detection algorithms, position evaluation, move ordering, and opening book. It runs entirely off the main thread and handles both human and AI moves. |
| **`index.js`** | **(Main Thread Controller)** Acts as the application's central nervous system. It handles game mode selection, all user input events, manages timer state and countdown logic, controls game state transitions, spawns and communicates with the AI Worker via the `postMessage`/`onmessage` API, and updates the UI. |

### Key Features:
- **Two Game Modes**: VS AI (Human vs Elite AI) and Two-Player (local multiplayer on same device)
- **Elite AI**: Fixed depth-9 minimax search with alpha-beta pruning, transposition tables, center-column move ordering, opening book, and positional heuristics for an ~80% win rate
- **Chess-Style Timers**: 5-minute initial time with 5-second increment per move, creating time pressure and urgency
- **Timer States**: Active highlighting (green glow), warning state (red with pulse animation when <30 seconds), and timeout detection
- **Chess-Style Cumulative Timers**: 2-minute total time per player that counts down only during their turns (no increment)
- **Timer States**: Active highlighting (green glow), warning state (orange at ≤30 seconds), critical state (red with fast pulse at ≤10 seconds), and timeout detection
- **Concurrency Management:** Spawns and manages a dedicated Web Worker, isolating all computationally intensive AI logic to a separate thread
- **Non-Blocking UI:** Decouples UI event handling from AI calculation, guaranteeing 60fps experience even during deep search
- **State Machine Implementation:** Cleanly manages UI and timer state transitions for all playable events
- **State Machine Implementation:** Cleanly manages UI and timer state transitions for all playable events including mode selection
- **Animation Orchestration:** Handles triggering of CSS animations and board updates while properly pausing timers during animations

---
Expand All @@ -113,51 +115,58 @@ The AI is designed to be highly challenging, winning approximately 80% of games
- **Iterative Deepening**: Searches progressively deeper, using best moves from shallower searches to improve move ordering

### Timer System:
- **Initial Time**: 5 minutes (300 seconds) per player
- **Increment**: +5 seconds added after each move (Fischer-style)
- **Warning Threshold**: Timer turns red and pulses when below 30 seconds
- **Initial Time**: 2 minutes (120 seconds) per player
- **Cumulative Timer**: Time counts down only during your turn, stops when opponent's turn begins (no increment)
- **Warning Threshold**: Timer turns orange when below 30 seconds
- **Critical Threshold**: Timer turns red and pulses rapidly when below 10 seconds
- **Timeout Detection**: Game ends immediately if either player's time reaches zero
- **Pause on Animation**: Timers automatically pause during chip drop animations and game-over state

### Game Modes:
- **VS AI Mode**: Human (Player 1 - Red) plays against the Elite AI (Player 2 - Yellow). Human always moves first. AI uses depth-9 search for challenging gameplay.
- **Two-Player Mode**: Local multiplayer where two players share the same device. Player 1 (Red) vs Player 2 (Yellow). Player 1 always moves first.

### Protocol Example (`index.js` orchestrates):
```javascript
// 1. Game starts - reset timers to 5:00 each
startGame() → playerTime = 300, aiTime = 300
// 1. Player selects mode (VS AI or Two-Player) and clicks Start Game
// Game starts - reset timers to 2:00 each
startGame() → player1Time = 120, player2Time = 120

// 2. Player's turn begins - start player timer
startHumanTurn() → startTimer('player')
// 2. Player 1's turn begins - start player 1 timer
startHumanTurn() → startTimer(1)

// 3. Player makes move - stop timer, add 5s increment, drop chip
// 3. Player 1 makes move - stop timer, drop chip
worker.postMessage({ messageType: 'human-move', col: columnIndex });
→ stopTimer() → addIncrement('player') → playerTime += 5
→ stopTimer() // Timer preserves remaining time

// 4. AI's turn begins - start AI timer with elite search depth
startComputerTurn() → startTimer('ai')
// 4a. In VS AI Mode - AI's turn begins
startComputerTurn() → startTimer(2)
→ worker.postMessage({ messageType: 'computer-move', maxDepth: 9 });

// 5. AI completes move - stop timer, add 5s increment
worker.addEventListener('message', function(e) {
if (e.data.messageType === 'computer-move-done') {
stopTimer() → addIncrement('ai') → aiTime += 5
}
});
// 4b. In Two-Player Mode - Player 2's turn begins
startPlayer2Turn() → startTimer(2)
→ worker.postMessage({ messageType: 'player2-move', col: columnIndex });

// 5. Move completes - stop timer
stopTimer() // Timer preserves remaining time

// 6. Timer hits zero - game ends immediately
if (playerTime <= 0) → endGame('timeout-player')
if (aiTime <= 0) → endGame('timeout-ai')
if (player1Time <= 0) → endGame('timeout-p1')
if (player2Time <= 0) → endGame('timeout-p2')
```

---
## VI. Game Mechanics and Features

| Feature | Implementation Detail | Technical Implication |
| --------------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Game Modes** | VS AI (Human vs Elite AI) and Two-Player (local multiplayer) | Flexible gameplay that accommodates solo challenge against AI or local competitive play between two humans. Both modes use the same timer system and game rules. |
| **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 efficient bitboard operations that check win conditions in O(1) time per move using bitwise AND operations. |
| **Elite AI Opponent** | Fixed depth-9 minimax with advanced optimizations | Provides a highly challenging opponent with ~80% win rate, encouraging repeated play and skill development. Uses alpha-beta pruning, transposition tables, and positional heuristics. |
| **Chess-Style Timers** | 5:00 initial + 5s increment per move | Creates time pressure and urgency. Timers highlight active player (green glow), show warning when low (red pulse), and end game on timeout. Pauses during animations. |
| **Elite AI Opponent** | Fixed depth-9 minimax with advanced optimizations | Provides a highly challenging opponent with ~80% win rate in VS AI mode, encouraging repeated play and skill development. Uses alpha-beta pruning, transposition tables, and positional heuristics. |
| **Chess-Style Cumulative Timers** | 2:00 total time per player (counts down during turn) | Creates intense time pressure with no time back. Timers show active player (green glow), warning at ≤30s (orange), critical at ≤10s (red pulse), and end game on timeout. Pauses during animations. |
| **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, winning-line highlights, and timer states | Delivers real-time, responsive user interactions with clear visual cues about game state, time pressure, and potential moves. |
| **Visual Feedback** | CSS/JS-driven mode selection, hover, drop, winning-line highlights, and timer states | Delivers real-time, responsive user interactions with clear visual cues about game mode, game state, time pressure, and potential moves. |

---
## VII. Performance & Benchmarking
Expand Down Expand Up @@ -191,9 +200,9 @@ This implementation now includes three major algorithmic optimizations that sign
---
## VIII. Historical & Educational Context
- **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.
- **Modern Twist:** While maintaining academic rigor, OptiConnect adds a competitive gaming layer with a challenging elite AI and chess-style time pressure, making it both educational and engaging.
- **Modern Twist:** While maintaining academic rigor, OptiConnect adds a competitive gaming layer with two game modes (VS AI and Two-Player) and chess-style cumulative time pressure, making it both educational and engaging.
- **Pedagogical Platform:** Demonstrates classical adversarial search (Minimax with Alpha-Beta pruning), modern web architecture, advanced optimization techniques (bitboards, transposition tables, Zobrist hashing), and real-time timer management. Provides a clear example of **concurrency, Web Workers, asynchronous event handling, bit manipulation, position caching, and separation of concerns** in application design.
- **Game Design Philosophy:** The fixed elite AI (no difficulty selection) and timer system create a pure competitive experience that encourages skill development, similar to chess training against a strong engine with time controls.
- **Game Design Philosophy:** The two game modes with cumulative timers create both competitive and casual play experiences. VS AI mode offers a pure competitive challenge against a strong engine, while Two-Player mode enables local multiplayer fun with the same time pressure mechanics.

---
## IX. Roadmap
Expand All @@ -202,7 +211,7 @@ This implementation now includes three major algorithmic optimizations that sign
| ----------------------------- | ---------------------------------------- | ----------- |
| **Foundation** | True Web Worker concurrency, modular `index.js` controller | ✅ **Complete** |
| **Algorithmic Optimization** | Alpha-beta pruning, bitboard representation, transposition table with Zobrist hashing | ✅ **Complete** |
| **Elite AI & Timers** | Fixed depth-9 elite AI, chess-style timers (5:00 + 5s increment), remove difficulty selection | ✅ **Complete** |
| **Game Modes & Timers** | Two game modes (VS AI, Two-Player), fixed depth-9 elite AI, chess-style cumulative timers (2:00 per player) | ✅ **Complete** |
| **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** |
Expand Down
Loading