Skip to content

Commit 46cd58c

Browse files
Merge pull request #3 from CodeKunalTomar/copilot/remove-difficulty-system
Add Two Game Modes and Cumulative Chess-Style Timers
2 parents 061c609 + 3118672 commit 46cd58c

File tree

5 files changed

+385
-125
lines changed

5 files changed

+385
-125
lines changed

Connect-4.css

Lines changed: 87 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -55,51 +55,117 @@ h2 {
5555
border-radius: 8px;
5656
}
5757

58+
/* Setup Panel - Mode Selection */
59+
.setup-panel h2 {
60+
margin-bottom: 12px;
61+
text-align: center;
62+
}
63+
64+
.mode-select {
65+
display: flex;
66+
gap: 10px;
67+
margin-bottom: 0;
68+
}
69+
70+
.mode-btn {
71+
flex: 1;
72+
padding: 15px 10px;
73+
background-color: rgba(255, 255, 255, 0.1);
74+
border: 2px solid #666;
75+
border-radius: 8px;
76+
color: #ccc;
77+
cursor: pointer;
78+
transition: all 0.3s ease;
79+
text-align: center;
80+
font-family: "Doppio One", sans-serif;
81+
font-size: 14px;
82+
}
83+
84+
.mode-btn:hover {
85+
background-color: rgba(255, 255, 255, 0.2);
86+
border-color: #999;
87+
}
88+
89+
.mode-btn.selected {
90+
background-color: #593f6b;
91+
border-color: #fff;
92+
color: #fff;
93+
}
94+
95+
.mode-btn .icon {
96+
font-size: 24px;
97+
display: block;
98+
margin-bottom: 5px;
99+
}
100+
101+
.mode-btn:focus {
102+
outline: none;
103+
}
104+
58105
/* Timer Panel */
59106
.timer-panel {
60107
display: flex;
61108
flex-direction: column;
62-
gap: 10px;
63-
padding: 15px;
109+
gap: 8px;
110+
padding: 12px;
64111
}
65112

66113
.timer {
67-
padding: 15px;
114+
padding: 12px;
68115
background-color: rgba(255, 255, 255, 0.1);
69116
border-radius: 8px;
70-
font-family: "Doppio One", monospace;
71-
text-align: center;
72117
border: 2px solid transparent;
73118
transition: all 0.3s ease;
119+
display: flex;
120+
justify-content: space-between;
121+
align-items: center;
122+
}
123+
124+
.timer-label {
125+
font-size: 14px;
126+
color: #aaa;
127+
font-family: "Doppio One", sans-serif;
128+
}
129+
130+
.timer-value {
131+
font-size: 24px;
132+
font-family: "Courier New", monospace;
133+
color: #fff;
134+
font-weight: bold;
74135
}
75136

76137
.timer.active {
77138
border-color: #4CAF50;
78-
box-shadow: 0 0 15px rgba(76, 175, 80, 0.5);
79-
background-color: rgba(76, 175, 80, 0.2);
139+
box-shadow: 0 0 10px rgba(76, 175, 80, 0.4);
140+
background-color: rgba(76, 175, 80, 0.15);
141+
}
142+
143+
.timer.active .timer-label {
144+
color: #4CAF50;
80145
}
81146

82147
.timer.warning {
83-
border-color: #f44336;
84-
background-color: rgba(244, 67, 54, 0.2);
85-
animation: pulse 1s infinite;
148+
border-color: #ff9800;
149+
background-color: rgba(255, 152, 0, 0.15);
86150
}
87151

88-
@keyframes pulse {
89-
0%, 100% { opacity: 1; }
90-
50% { opacity: 0.6; }
152+
.timer.warning .timer-value {
153+
color: #ff9800;
91154
}
92155

93-
.timer-label {
94-
font-size: 14px;
95-
color: #aaa;
96-
margin-bottom: 5px;
156+
.timer.critical {
157+
border-color: #f44336;
158+
background-color: rgba(244, 67, 54, 0.15);
159+
animation: pulse-critical 0.5s infinite;
97160
}
98161

99-
.timer-value {
100-
font-size: 32px;
101-
color: #fff;
102-
font-weight: bold;
162+
.timer.critical .timer-value {
163+
color: #f44336;
164+
}
165+
166+
@keyframes pulse-critical {
167+
0%, 100% { opacity: 1; }
168+
50% { opacity: 0.7; }
103169
}
104170

105171
/* Start Panel */

Connect-4.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,9 @@ self.addEventListener('message', function(e) {
308308
case 'human-move':
309309
makeHumanMove(e.data.col);
310310
break;
311+
case 'player2-move':
312+
makePlayer2Move(e.data.col);
313+
break;
311314
case 'computer-move':
312315
makeComputerMove(e.data.maxDepth);
313316
break;
@@ -340,6 +343,21 @@ function makeHumanMove(col) {
340343
});
341344
}
342345

346+
function makePlayer2Move(col) {
347+
// coords is undefined if the move is invalid (column is full)
348+
const coords = currentGameState.makeMove(2, col);
349+
const isWin = currentGameState.isWin();
350+
const winningChips = currentGameState.winningChips;
351+
const isBoardFull = currentGameState.isBoardFull();
352+
self.postMessage({
353+
messageType: 'player2-move-done',
354+
coords: coords,
355+
isWin: isWin,
356+
winningChips: winningChips,
357+
isBoardFull: isBoardFull
358+
});
359+
}
360+
343361
function makeComputerMove(maxDepth) {
344362
let col;
345363
let isWinImminent = false;

README.md

Lines changed: 44 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,16 @@
1818
---
1919
## I. Abstract
2020

21-
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.
21+
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.
2222

2323
The game features:
24+
- **Two Game Modes**: Challenge the Elite AI or play against a friend locally with Two-Player mode
2425
- **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
25-
- **Chess-Style Timers**: Each player starts with 5 minutes and gains a 5-second increment after each move, creating urgency and excitement
26+
- **Chess-Style Cumulative Timers**: Each player starts with 2 minutes total time that counts down during their turns, creating intense time pressure
2627
- **Non-Blocking Architecture**: All AI computation runs in a Web Worker thread, ensuring smooth 60fps UI performance
2728
- **Advanced Optimizations**: Bitboard representation, Zobrist hashing, center-column move ordering, and opening book
2829

29-
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?
30+
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?
3031

3132
---
3233
## II. Local Deployment Protocol
@@ -83,18 +84,19 @@ The key architectural upgrade is the role of `index.js` as an intermediary that
8384
8485
| Component | Role |
8586
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
86-
| **`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. |
87-
| **`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. |
88-
| **`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. |
89-
| **`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. |
87+
| **`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. |
88+
| **`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. |
89+
| **`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. |
90+
| **`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. |
9091

9192
### Key Features:
93+
- **Two Game Modes**: VS AI (Human vs Elite AI) and Two-Player (local multiplayer on same device)
9294
- **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
93-
- **Chess-Style Timers**: 5-minute initial time with 5-second increment per move, creating time pressure and urgency
94-
- **Timer States**: Active highlighting (green glow), warning state (red with pulse animation when <30 seconds), and timeout detection
95+
- **Chess-Style Cumulative Timers**: 2-minute total time per player that counts down only during their turns (no increment)
96+
- **Timer States**: Active highlighting (green glow), warning state (orange at ≤30 seconds), critical state (red with fast pulse at ≤10 seconds), and timeout detection
9597
- **Concurrency Management:** Spawns and manages a dedicated Web Worker, isolating all computationally intensive AI logic to a separate thread
9698
- **Non-Blocking UI:** Decouples UI event handling from AI calculation, guaranteeing 60fps experience even during deep search
97-
- **State Machine Implementation:** Cleanly manages UI and timer state transitions for all playable events
99+
- **State Machine Implementation:** Cleanly manages UI and timer state transitions for all playable events including mode selection
98100
- **Animation Orchestration:** Handles triggering of CSS animations and board updates while properly pausing timers during animations
99101

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

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

125+
### Game Modes:
126+
- **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.
127+
- **Two-Player Mode**: Local multiplayer where two players share the same device. Player 1 (Red) vs Player 2 (Yellow). Player 1 always moves first.
128+
122129
### Protocol Example (`index.js` orchestrates):
123130
```javascript
124-
// 1. Game starts - reset timers to 5:00 each
125-
startGame() → playerTime = 300, aiTime = 300
131+
// 1. Player selects mode (VS AI or Two-Player) and clicks Start Game
132+
// Game starts - reset timers to 2:00 each
133+
startGame() → player1Time = 120, player2Time = 120
126134
127-
// 2. Player's turn begins - start player timer
128-
startHumanTurn() → startTimer('player')
135+
// 2. Player 1's turn begins - start player 1 timer
136+
startHumanTurn() → startTimer(1)
129137
130-
// 3. Player makes move - stop timer, add 5s increment, drop chip
138+
// 3. Player 1 makes move - stop timer, drop chip
131139
worker.postMessage({ messageType: 'human-move', col: columnIndex });
132-
stopTimer() → addIncrement('player') → playerTime += 5
140+
→ stopTimer() // Timer preserves remaining time
133141
134-
// 4. AI's turn begins - start AI timer with elite search depth
135-
startComputerTurn() → startTimer('ai')
142+
// 4a. In VS AI Mode - AI's turn begins
143+
startComputerTurn() → startTimer(2)
136144
→ worker.postMessage({ messageType: 'computer-move', maxDepth: 9 });
137145
138-
// 5. AI completes move - stop timer, add 5s increment
139-
worker.addEventListener('message', function(e) {
140-
if (e.data.messageType === 'computer-move-done') {
141-
stopTimer() → addIncrement('ai') → aiTime += 5
142-
}
143-
});
146+
// 4b. In Two-Player Mode - Player 2's turn begins
147+
startPlayer2Turn() → startTimer(2)
148+
→ worker.postMessage({ messageType: 'player2-move', col: columnIndex });
149+
150+
// 5. Move completes - stop timer
151+
stopTimer() // Timer preserves remaining time
144152
145153
// 6. Timer hits zero - game ends immediately
146-
if (playerTime <= 0) → endGame('timeout-player')
147-
if (aiTime <= 0) → endGame('timeout-ai')
154+
if (player1Time <= 0) → endGame('timeout-p1')
155+
if (player2Time <= 0) → endGame('timeout-p2')
148156
```
149157
150158
---
151159
## VI. Game Mechanics and Features
152160
153161
| Feature | Implementation Detail | Technical Implication |
154162
| --------------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
163+
| **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. |
155164
| **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. |
156165
| **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. |
157-
| **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. |
158-
| **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. |
166+
| **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. |
167+
| **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. |
159168
| **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. |
160-
| **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. |
169+
| **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. |
161170
162171
---
163172
## VII. Performance & Benchmarking
@@ -191,9 +200,9 @@ This implementation now includes three major algorithmic optimizations that sign
191200
---
192201
## VIII. Historical & Educational Context
193202
- **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.
194-
- **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.
203+
- **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.
195204
- **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.
196-
- **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.
205+
- **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.
197206
198207
---
199208
## IX. Roadmap
@@ -202,7 +211,7 @@ This implementation now includes three major algorithmic optimizations that sign
202211
| ----------------------------- | ---------------------------------------- | ----------- |
203212
| **Foundation** | True Web Worker concurrency, modular `index.js` controller | ✅ **Complete** |
204213
| **Algorithmic Optimization** | Alpha-beta pruning, bitboard representation, transposition table with Zobrist hashing | ✅ **Complete** |
205-
| **Elite AI & Timers** | Fixed depth-9 elite AI, chess-style timers (5:00 + 5s increment), remove difficulty selection | ✅ **Complete** |
214+
| **Game Modes & Timers** | Two game modes (VS AI, Two-Player), fixed depth-9 elite AI, chess-style cumulative timers (2:00 per player) | ✅ **Complete** |
206215
| **AI Extension** | Integrate endgame tablebases, develop NN/MCTS hybrid agents | 📝 **Planned** |
207216
| **Feature Expansion** | Implement networked multiplayer, develop an adaptive benchmarking suite | 📝 **Planned** |
208217
| **Research Platform** | Design a plug-and-play AI module interface, add an analytics dashboard | 📝 **Planned** |

0 commit comments

Comments
 (0)