[update] Progressive difficulty, demo fixes, and background docs.

This commit is contained in:
2026-03-06 22:14:25 +01:00
parent 8a776dfae5
commit da63f05ac3
7 changed files with 414 additions and 575 deletions
+62 -71
View File
@@ -1,95 +1,86 @@
# Connect Four: ESP32-C3 LED Edition
# 🕹️ Connect 4 AI: Master Edition (v2.0)
A hardware-based Connect Four game featuring an 8x8 NeoPixel matrix, a strategic Minimax AI, and a dynamic "Attract Mode" for public display.
## How the Program Works
The program is built as a **Finite State Machine (FSM)**.
It manages the game flow by transitioning between distinct states based on user input, game outcomes, or inactivity timers.
### 1. Game States
- **Menu**: Displays stylized Roman numerals (**I** or **II**) to select between Single Player or Two Player modes.
- **Game Play**: The main loop handles the real-time gravity of falling discs, encoder tracking for column selection, and the hand-off between the human and the AI.
- **Game Over**: Triggered when a win or draw is detected. It "locks" the board, dims the background discs to 15% intensity, and flashes the winning line.
- **Demo Mode**: Triggered after 60 seconds of inactivity. The AI plays against itself to act as a visual "attract mode."
### 2. Win Detection Logic
To ensure 100% accuracy, the program performs a synchronous, multi-directional scan of the 7x6 grid after every single move.
It checks for four matching non-zero values in the following patterns:
- **Horizontal**: `[column] [row]` to `[column + 3] [row]`
- **Vertical**: `[column] [row]` to `[column] [row + 3]`
- **Diagonal Up**: `[column] [row]` to `[column + 3] [row + 3]`
- **Diagonal Down**: `[column] [row]` to `[column + 3] [row - 3]`
A high-performance, feature-rich Connect 4 implementation for the ESP32-C3. This version features a "living" AI that evolves as you play, human-like movement animations, and a robust win-detection engine.
---
## The AI: Strategic Minimax
## 🛠 Hardware Configuration
The computer opponent uses the **Minimax Algorithm**, a classic artificial intelligence method for zero-sum games.
### 🔌 Pin Mapping (Lolin C3 Mini)
### 1. Look-Ahead (Depth Search)
| Component | ESP32-C3 Pin | Function |
| :------------------- | :----------- | :--------------- |
| **NeoPixel Matrix** | `GPIO 4` | Data Input (DIN) |
| **Rotary Encoder A** | `GPIO 0` | Directional CLK |
| **Rotary Encoder B** | `GPIO 1` | Directional DT |
| **Encoder Button** | `GPIO 2` | Selection (SW) |
The AI does not just look at the current board; it simulates the game **6 to 8 moves into the future**.
It explores a "tree" of possibilities: _"If I play here, and the player plays there, then I can play here..."_
### 📐 Physical Layout
### 2. Alpha-Beta Pruning
The project is optimized for an 8x8 NeoPixel Matrix (65mm x 67mm).
Because searching millions of possibilities would be too slow for a microcontroller, we use **Alpha-Beta Pruning**.
This allows the AI to "prune" (ignore) branches of the game tree that are mathematically
guaranteed to be worse than moves it has already found, significantly speeding up the calculation.
### 3. Immediate Threat Reaction
To prevent the AI from being "distracted" by deep strategies while missing a simple win or loss,
we implemented a high-priority **Reaction Scanner**:
- **Kill Move**: If the AI can win in exactly one move, it takes it immediately.
- **Block Move**: If the player is one move away from winning (3-in-a-row), the AI identifies the threat and blocks it regardless of the Minimax score.
### 4. Controlled Randomness (Demo Mode)
To keep the Demo Mode interesting for spectators, the AI has a 25% chance to ignore the "perfect" move and pick a random column.
This ensures that every demo game is unique and not a repetitive loop of the same strategy.
- **Row 0:** Interaction & AI Decision Visualization.
- **Row 1:** Static Blue UI border.
- **Rows 2-7:** Active $7 \times 6$ game board.
- **Status Column:** Far right column (Index 7) manages UI framing and "Glow" effects.
---
## Technical Specifications
## 🧠 Advanced AI & Logic Features
### Hardware Pins (Lolin C3 Mini)
### 1. Progressive Difficulty (Evolution Mode)
| Component | Pin | Function |
| :---------- | :-- | :--------------------------------------- |
| **LED_PIN** | 4 | WS2812B NeoPixel Data |
| **ENC_A** | 0 | Rotary Encoder Phase A |
| **ENC_B** | 1 | Rotary Encoder Phase B |
| **ENC_SW** | 2 | Switch (Includes 50ms Software Debounce) |
To keep the game challenging and the CPU efficient, the AI search depth (Ply) scales as the board fills.
### NeoPixel Grid Layout
- **Formula:** $DynamicPly = BasePly + \lfloor \frac{DiscsOnBoard}{7} \rfloor$
- **Benefit:** The AI is "casual" in the opening but becomes a "Grandmaster" in the endgame when tactical precision is vital.
The 8x8 matrix is mapped as follows:
### 2. Intelligent Win Detection & Flashing
- **Play Area**: 7 columns (0-6) by 6 rows (0-5).
- **Boundaries**: Row 1 and Column 7 are lit in **Blue** to mark the board limits.
- **Indicators**: The top-right pixel (7,0) pulses in the computer's color while it is "thinking."
- **Glowing Frame**: During Demo mode, the blue borders pulse with a white "glow" effect using a `beat8` sine wave to indicate autonomous play.
The win-engine has been refactored to prevent "color ghosting."
- **Winner Locking:** The `scanBoard()` function returns the specific ID of the winner (1 for Yellow, 2 for Red).
- **Flashing Accuracy:** The final animation uses this ID to ensure the winning 4-in-a-row flashes in the **correct player's color**, regardless of whose turn it was when the game ended.
### 3. Smart Watchdog (Tiered Timeout)
The game respects your "thinking time" by using a tiered idle-timeout system:
- **Menu/Finished State:** Standard timeout (e.g., 60s).
- **Playing State:** **Double Timeout** (e.g., 120s). This gives human players more time to analyze complex boards before the game auto-resets to Demo Mode.
### 4. Strategic Blunder Injection
To ensure Demo Mode doesn't end in an infinite loop of draws, a 20% "Blunder Chance" is injected. This forces the AI to occasionally make a human-like mistake, creating openings for a definitive winner.
---
## Controls & Interaction
## 📖 Code Architecture & Modules
- **Rotate Encoder**: Move the cursor (top row) to select a column.
- **Press Encoder Button**: Drop a disc.
- **Full Column Warning**: If you attempt to play in a full column, the selection disc will blink rapidly, and the move will be ignored.
- **Reset**: After a game ends, press the button once to return to the Menu.
### 🔄 State Machine
## Build Flags (platformio.ini)
The core loop manages five distinct states:
Tweak the game performance without changing the source code:
1. **MENU:** Mode selection and board reset.
2. **PLAYING:** Active turn-based logic with gravity-accelerated drop animations.
3. **FINISHED_WIN:** Locks the winner ID and flashes the winning segment.
4. **FINISHED_DRAW:** Blinks the entire board to signify a stalemate.
5. **DEMO:** Auto-plays with randomized difficulty (Ply 3-6) and mandatory blunder logic.
- `IDLE_TIMEOUT`: Time (ms) before Demo Mode starts.
- `DEMO_RESET_PAUSE`: Delay (ms) between games in Demo Mode.
- `DEBOUNCE_DELAY`: Sensitivity of the encoder button.
- `BRIGHTNESS`: Global brightness of the NeoPixels.
### 🌐 Web Administration Portal
Accessible via the **"Connect4-Config"** AP at `192.168.4.1`.
- **Base Ply:** Sets the starting difficulty level.
- **Brightness:** Global LED intensity (0-255).
- **Evolution Toggle:** Turn on/off the progressive difficulty scaling.
- **Blunder Toggle:** Allow the AI to make mistakes during Human-vs-AI matches.
---
## 🛠 Installation
1. **Environment:** Use VS Code with the **PlatformIO** extension.
2. **Dependencies:** `FastLED`, `Encoder`, `Preferences`.
3. **Build Flag:** Define your WiFi password in `platformio.ini`: `-D WIFI_PASSWORD=\"your_password\"`.
4. **Flash:** Upload to your ESP32-C3 and enjoy the ultimate desktop Connect 4 experience.