[refactor] Game log, persistence, demo mode, indicator LED, and documentation.

This commit is contained in:
2026-03-15 15:30:58 +01:00
parent b5d696bf30
commit f489442cb5
5 changed files with 560 additions and 233 deletions
+2 -1
View File
@@ -3,4 +3,5 @@
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
.vscode/settings.json
.vscode/settings.json
CLAUDE.md
+88 -40
View File
@@ -1,69 +1,117 @@
# 🕹️ Connect 4 AI: How the Brain Works
To create a competitive Connect 4 experience on a small microcontroller, the game uses a mix of mathematical strategy and "shortcuts" to play like a human master.
---
# Connect 4 AI: How the Computer Thinks
## 1. The Virtual Board
The computer sees the board as a grid of numbers. It uses a **7-column by 6-row** map where:
The computer doesn't see colored discs on a grid. It sees a table of numbers:
- **0** = Empty space
- **1** = Yellow (Human Player)
- **2** = Red (Computer AI)
- **1** = Yellow disc
- **2** = Red disc
Every time a disc is dropped, a "Scan" function checks every possible direction (horizontal, vertical, and diagonal) to see if anyone has reached four in a row.
The board has 7 columns and 6 rows. After every move, a scan function checks all directions (horizontal, vertical, and both diagonals) to see if anyone has four in a row.
---
## 2. What is a "Ply"?
## 2. Thinking Ahead (The "What If?" Engine)
A **ply** is one move by one player. If the AI is set to ply 6, it looks 6 individual moves into the future. Since players alternate turns, ply 6 means the AI considers 3 of its own moves and 3 of the opponent's moves.
The AI doesn't just look at the current board; it plays out thousands of "What if?" scenarios in its head.
More plies = stronger play, but takes longer to calculate. On the ESP32-C3, ply 4 is nearly instant, ply 6 takes about a second, and ply 8-10 can take several seconds. The AI shows a pulsing light while it is thinking.
### The Minimax Strategy
## 3. The Minimax Strategy
The AI uses a strategy called **Minimax**. It assumes that you will play your absolute best move, and it tries to find the move that leaves you with the worst possible outcome. It "maximizes" its own advantage while "minimizing" yours.
### The basic idea
### Alpha-Beta Pruning (The Shortcut)
Imagine you are playing Connect 4 against a friend. Before you drop your disc, you think: "If I put my disc here, what will my friend do? And then what would I do after that?"
Calculating every possible move in Connect 4 would take hours. To make the AI fast, it uses **Pruning**. If the AI starts calculating a move and realizes its definitely worse than a move it already found, it "prunes" (deletes) that entire branch of thought and moves on. This allows it to ignore up to 90% of useless moves.
That is exactly what the computer does, except it checks **every** possible move, not just a few.
---
### Two players, two goals
## 3. Scoring System (The AIs Instincts)
The AI calls the two players **Max** (itself) and **Min** (you):
Since the computer can't always see to the very end of the game, it uses a scoring system to guess which positions are strongest:
- **Max** wants the highest possible score (the AI winning).
- **Min** wants the lowest possible score (you winning).
- **Speed Matters:** The AI is rewarded more for a win that happens soon than a win that takes a long time. This gives it a "killer instinct" to end the game as quickly as possible.
- **The Center is King:** The AI is programmed to prefer the middle column. Mathematically, the center column is involved in the most possible winning combinations, so the AI fights to control it early in the game.
The AI assumes you will always make your best move. It doesn't hope you'll make a mistake.
---
### A simple example
## 4. Being Responsive (Interrupt Handling)
Imagine there are only 3 columns left and the AI can look 2 moves ahead. It builds a tree like this:
Your game runs on an **ESP32-C3**, which is a single-tasking processor. Normally, if the AI spends 2 seconds thinking, the buttons would feel "broken" or "frozen" until it finishes.
```
AI's turn (Max - pick the highest)
/ | \
col 2 col 3 col 4
/ \ / \ / \
Your turn (Min - pick the lowest)
... ... ... ... ... ...
+5 -3 +2 +8 -1 +4
```
We solve this with two clever tricks:
1. After column 2: you would pick the move scoring -3 (lowest = best for you).
2. After column 3: you would pick the move scoring +2.
3. After column 4: you would pick the move scoring -1.
1. **Mid-Thought Checks:** Every few milliseconds of calculation, the AI "pauses" for a microsecond to see if you have pressed the button.
2. **Instant Exit:** If it detects you pressed the button while it was thinking, it abandons all calculations immediately and jumps back to the main menu.
The AI compares -3, +2, and -1, and picks column 3 because +2 is the best it can guarantee.
---
### Scoring
## 5. Summary of an AI Move
The AI assigns scores to board positions:
When it is the computer's turn, it follows these steps in a split second:
- **+1000 or more:** The AI wins. A faster win gets a higher score, so the AI goes for the quickest victory.
- **-1000 or less:** The opponent wins. A faster loss gets a more negative score, so the AI fights hardest against immediate threats.
- **0:** Nobody has won and the search depth ran out. The position is neutral.
1. **Check for Lethal:** Can I win right now? If yes, take it.
2. **Check for Danger:** Can the human win on their next move? If yes, block it.
3. **Search:** Look at the middle columns first, then the edges.
4. **Prune:** Throw away bad moves immediately to save time.
5. **Act:** Choose the move that leads to the quickest victory.
This scoring is why the AI has "killer instinct" - it doesn't just try to win, it tries to win as fast as possible.
---
## 4. Alpha-Beta Pruning: The Smart Shortcut
## 📚 References & Further Reading
### The problem
- [The Mathematical Solution to Connect 4](https://en.wikipedia.org/wiki/Connect_Four#Mathematical_solution)
- [How the Minimax Algorithm Works](https://en.wikipedia.org/wiki/Minimax)
- [Understanding Alpha-Beta Pruning](https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning)
Looking ahead 8 plies in Connect 4 means exploring millions of board positions. Even a fast microcontroller can't check them all in a reasonable time.
### The solution
**Alpha-Beta pruning** is a way to skip branches of the tree that can't possibly change the final decision.
Think of it like shopping for a birthday present. You visit Shop A and find a nice toy for 10 euros. Then you go to Shop B. The first item you see costs 15 euros, and you notice everything else in Shop B is even more expensive. You don't need to check every item in Shop B - you already know Shop A is better. You leave Shop B and save time.
The AI does the same thing:
- **Alpha** is the best score the AI (Max) has found so far. Think of it as "I already know I can do at least this well."
- **Beta** is the best score the opponent (Min) has found so far. Think of it as "The opponent already knows they can limit me to at most this."
When the AI is exploring a branch and discovers that the score can never beat what it already has (beta <= alpha), it **prunes** (cuts off) that entire branch. It skips all remaining moves in that branch because they can't change the outcome.
### How much does it help?
In practice, pruning lets the AI skip 50-90% of the positions it would otherwise need to check. This is why the column order matters - the AI checks the center column first (column 3), then works outward. Good moves tend to be near the center, so checking them first leads to better pruning and faster search.
## 5. The Three-Phase Move Strategy
Before running the expensive minimax search, the AI takes two quick shortcuts:
1. **Can I win right now?** The AI tries placing its disc in each column. If any column completes four in a row, it takes that move immediately. No need to think further.
2. **Can my opponent win next turn?** The AI checks if the opponent could win by playing in any column. If so, it blocks that column. Missing this would be a fatal mistake.
3. **Deep search.** Only if there are no immediate wins or threats does the AI run the full minimax search with alpha-beta pruning.
This three-phase approach makes the AI both fast (instant reactions to obvious moves) and smart (deep strategic thinking when needed).
## 6. Demo Mode: Asymmetric Skill
In demo mode, two AI players play against each other. To make the games interesting (rather than always ending in a draw), each player is randomly assigned a different search depth. One player might look 5 moves ahead while the other only looks 3 moves ahead. The stronger player can find winning setups that the weaker one misses, leading to exciting games with real winners. Who gets the advantage is randomized each game.
## 7. Responsive Controls
The ESP32-C3 is a single-core processor. When the AI is thinking, it could block all input for several seconds. Two techniques keep the game responsive:
1. **Mid-search button checks:** During the minimax search, the AI periodically checks whether the player has pressed the button. If so, it immediately abandons the search.
2. **Abort flag:** A global flag (`abortAi`) propagates through all levels of the recursive search. Once set, every level of the search returns immediately, unwinding the entire calculation in microseconds.
## Further Reading
- [Connect Four - Mathematical Solution (Wikipedia)](https://en.wikipedia.org/wiki/Connect_Four#Mathematical_solution)
- [Minimax Algorithm (Wikipedia)](https://en.wikipedia.org/wiki/Minimax)
- [Alpha-Beta Pruning (Wikipedia)](https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning)
+100 -26
View File
@@ -1,10 +1,10 @@
# 🕹️ Connect 4 AI: Grandmaster Edition (v2.5)
# Connect 4 - ESP32
A high-performance Connect 4 implementation for the ESP32-C3 (RISC-V). This version features a "Killer Instinct" AI, human-like animations, and a real-time interrupt system.
A Connect 4 game with AI for the ESP32-C3 (Lolin C3 Mini), using an 8x8 NeoPixel LED matrix and rotary encoder.
## 🛠 Hardware Configuration
## Hardware
### 🔌 Pin Mapping (Lolin C3 Mini)
### Pin Mapping (Lolin C3 Mini)
| Component | ESP32-C3 Pin | Function |
| :------------------- | :----------- | :------------------- |
@@ -13,38 +13,112 @@ A high-performance Connect 4 implementation for the ESP32-C3 (RISC-V). This vers
| **Rotary Encoder B** | `GPIO 1` | Directional DT |
| **Encoder Button** | `GPIO 2` | Selection/Abort (SW) |
### 📐 Physical Layout
### LED Matrix Layout
- **Game Board:** 7 Columns x 6 Rows.
- **Top Row (Row 0):** Interaction row (Selection & AI Thinking pulse).
- **UI Border:** Row 1 and Column 7 (Blue frame, toggleable via `SHOW_BORDER`).
- **Coordinate Formula:** $Index = (y \times 8) + x$
The 8x8 matrix (64 LEDs) is used as follows:
---
```
Row 0: [ col0 ] [ col1 ] [ col2 ] [ col3 ] [ col4 ] [ col5 ] [ col6 ] [ indicator ]
Row 1: [ ---- ] [ ---- ] [ ---- ] [ ---- ] [ ---- ] [ ---- ] [ ---- ] [ border ]
Row 2-7:[ game board: 7 columns x 6 rows ] [ border ]
```
## 🧠 Advanced AI Features
- **Row 0 (columns 0-6):** Interaction row. Shows the current column selection cursor and AI thinking animation (pulsing disc).
- **Row 0 (column 7):** Game mode indicator LED (dim). Yellow = player is yellow vs AI, Red = player is red vs AI, Blue = two player, Off = demo.
- **Row 1 + Column 7:** Blue border frame (toggleable via `SHOW_BORDER` build flag). Glows softly during demo and finished states.
- **Rows 2-7, Columns 0-6:** The 7x6 game board. Yellow and Red discs.
- **LED index formula:** `index = (y * 8) + x`
### 1. Offense-Priority Strategy
## Game Modes
The AI follows a strict 3-phase move evaluation:
Use the rotary encoder to select a mode, press the button to start:
1. **Lethal:** If the AI can connect four this turn, it takes the win immediately.
2. **Defensive:** If the human player has a lethal move, the AI blocks it.
3. **Strategic:** If no immediate wins exist, it runs a deep Minimax search.
1. **Player vs AI (Yellow)** - Player plays yellow (first move), AI plays red.
2. **Player vs AI (Red)** - AI plays yellow (first move), player plays red.
3. **Two Player** - Two humans alternate turns. Yellow goes first.
### 2. High-Priority Interrupts
### Demo Mode
The AI's single-core RISC-V processor is kept responsive via an "Abort Flag." Pressing the button or turning the encoder during an AI calculation (Demo or Playing) immediately kills the recursion and returns the user to the Menu.
When idle (no input for the configured timeout), the board enters demo mode where two AI players play against each other automatically. To make games more interesting, the two demo players are assigned different skill levels (asymmetric ply depths), so games frequently end in a win rather than a draw. Press the button or turn the encoder to exit demo mode and return to the menu.
### 3. Evolution Mode
### Animations
AI difficulty scales dynamically: $DynamicPly = BasePly + \lfloor \frac{DiscsOnBoard}{7} \rfloor$.
- **Disc drop:** Discs fall from the top with accelerating speed.
- **Column movement:** Discs slide across the top row to the selected column.
- **AI thinking:** The disc in the selected column pulses while the AI calculates.
- **Win:** The winning four discs flash while the rest of the board dims. Displayed for 30 seconds.
- **Draw:** All discs blink on and off.
---
## WiFi Admin Interface
## 🛠 Installation & Build
The ESP32 creates a WiFi access point:
1. **Environment:** VS Code with PlatformIO.
2. **Dependencies:** `FastLED`, `Encoder`, `Preferences`.
3. **Build Flags:** - `-D SHOW_BORDER=1` (Enables blue frame)
- `-D SHOW_BORDER=0` (Full-screen board mode)
- **Network:** `Connect4-Config`
- **Password:** Configured via `WIFI_PASSWORD` build flag (default: `youlose4`)
- **Admin page:** Connect to the network and open `http://192.168.4.1`
### Settings (via web interface)
| Setting | Description |
| :--------------- | :------------------------------------------------------- |
| **Base AI Ply** | Search depth for the AI (1-10). Higher = stronger. |
| **Brightness** | LED brightness (0-255). |
| **Idle Timeout** | Seconds of inactivity before demo mode starts. |
| **Blunders** | Reserved for future use. |
| **Evolution** | Progressive difficulty: AI gets stronger as game goes on.|
Settings are saved to flash (NVS) and persist across reboots.
### Game Log
The web interface shows a log of the last N games (configurable via `MAX_GAME_LOG` build flag). Each entry shows the game type, AI level, winner, and the sequence of columns played. Games where a player beats the computer are highlighted in red. The game log is persisted to flash and survives reboots.
## Build & Upload
Requires [PlatformIO](https://platformio.org/) CLI or VS Code with PlatformIO extension.
```bash
# Build
pio run
# Upload to board
pio run --target upload
# Monitor serial output
pio device monitor
```
### Dependencies
- [FastLED](https://github.com/FastLED/FastLED) >= 3.6.0 - LED control
- [Encoder](https://github.com/PaulStoffregen/Encoder) >= 1.4.4 - Rotary encoder input
- Preferences (built-in) - Persistent settings storage
- WiFi / WebServer (built-in) - Admin interface
### Build Flags
All configurable parameters are defined as `-D` flags in `platformio.ini`:
| Flag | Default | Description |
| :--------------------- | :------ | :--------------------------------------------- |
| `LED_PIN` | `4` | GPIO pin for NeoPixel data line |
| `ENC_A` | `0` | GPIO pin for encoder CLK |
| `ENC_B` | `1` | GPIO pin for encoder DT |
| `ENC_SW` | `2` | GPIO pin for encoder button |
| `SENSITIVITY` | `4` | Encoder steps per detent (higher = less sensitive) |
| `SHOW_BORDER` | `1` | Show blue border frame (0 = off, 1 = on) |
| `DEFAULT_LOOK_AHEAD` | `8` | Default AI search depth (plies) |
| `DEFAULT_BRIGHTNESS` | `25` | Default LED brightness (0-255) |
| `DEFAULT_IDLE_TIMEOUT` | `45` | Seconds before demo mode activates |
| `MAX_GAME_LOG` | `5` | Number of games stored in the game log |
| `WIFI_PASSWORD` | `youlose4` | Password for the WiFi access point |
## Project Structure
```
src/main.cpp Single-file application (all game logic, AI, LED, web server)
platformio.ini Build configuration, pin mappings, and tunable parameters
README.md This file - technical and practical information
Background information.md How the AI works (suitable for all ages)
CLAUDE.md AI assistant project context
```
+1
View File
@@ -19,6 +19,7 @@ build_flags =
-D DEFAULT_LOOK_AHEAD=8
-D DEFAULT_BRIGHTNESS=25
-D DEFAULT_IDLE_TIMEOUT=45
-D MAX_GAME_LOG=100
-D WIFI_PASSWORD=\"youlose4\"
lib_deps =
fastled/FastLED @ ^3.6.0
+369 -166
View File
@@ -10,7 +10,7 @@
#endif
#ifndef SENSITIVITY
#define SENSITIVITY 4
#define SENSITIVITY 4
#endif
#define LED_PIN 4
@@ -19,8 +19,13 @@
#define ENC_SW 2
#define NUM_LEDS 64
#ifndef MAX_GAME_LOG
#define MAX_GAME_LOG 5
#endif
const int COLS = 7;
const int ROWS = 6;
const int colOrder[] = {3, 2, 4, 1, 5, 0, 6};
CRGB leds[NUM_LEDS];
Encoder myEnc(ENC_A, ENC_B);
@@ -32,122 +37,191 @@ bool winMask[NUM_LEDS];
enum State { MENU, PLAYING, AI_TURN, FINISHED_WIN, FINISHED_DRAW, DEMO };
State gameState = MENU;
int8_t menuMode = 0;
int8_t menuMode = 0;
int8_t currentPlayer = 1;
int8_t winnerPlayer = 0;
int8_t winnerPlayer = 0;
int8_t activeCol = 3;
long oldEncPos = -999;
uint32_t lastActivityTime = 0;
uint32_t demoResetTimer = 0;
uint32_t globalInputCooldown = 0;
uint8_t demoPly = 4;
uint8_t demoPly[2] = {4, 4};
bool abortAi = false;
bool lastButtonState = HIGH;
bool lastButtonState = HIGH;
uint8_t current_look_ahead = 6;
uint8_t current_brightness = 30;
uint32_t current_idle_timeout_ms = 60000;
bool blunder_enabled = false;
bool progressive_difficulty = false;
uint8_t currentLookAhead = 6;
uint8_t currentBrightness = 30;
uint32_t currentIdleTimeoutMs = 60000;
bool blunderEnabled = false;
bool progressiveDifficulty = false;
uint8_t aiBrightness = 0;
bool aiFadeUp = true;
struct GameEntry {
char type;
uint8_t level;
char winner;
String moves;
};
GameEntry gameLog[MAX_GAME_LOG];
uint8_t gameLogCount = 0;
String currentMoves = "";
int8_t gameMenuMode = 0;
uint8_t gameLevel = 0;
// --- Prototypes ---
CRGB playerColor(int8_t player);
int getIdx(int x, int y);
void resetBoard();
void drawBorder(CRGB color);
void logGame(int8_t winner);
void saveGameLog();
void loadGameLog();
void drawStaticUI();
void renderBoard();
void showMenu();
int getFirstEmptyRow(int col);
bool isBoardFull();
int8_t scanBoard();
int getDynamicPly();
int8_t scanBoard();
bool checkGameEnd();
void updateThinkingVisuals(int8_t pColor, int8_t column);
void animateDrop(int col, int player);
void moveDiscToCol(int startCol, int targetCol, int player, int speed);
int minimax(int depth, int alpha, int beta, bool isMax, int8_t aiP, int8_t huP, int8_t rootCol);
void performAiMove(int8_t aiP);
void showMenu();
int getDynamicPly();
void randomizeDemoPlies();
void handleRoot();
void handleSave();
void handleMenu(long newPos, bool pressed);
void handlePlaying(long newPos, bool pressed);
void handleAiTurn();
void handleDemo();
void handleFinished();
// --- Helpers ---
CRGB playerColor(int8_t player) {
return (player == 1) ? CRGB::Yellow : CRGB::Red;
}
int getIdx(int x, int y) { return (y * 8) + x; }
void resetBoard() {
memset(board, 0, sizeof(board));
winnerPlayer = 0;
}
void drawBorder(CRGB color) {
for (int x = 0; x < 7; x++) leds[getIdx(x, 1)] = color;
for (int y = 1; y < 8; y++) leds[getIdx(7, y)] = color;
}
void logGame(int8_t winner) {
char type = (gameMenuMode == 0) ? 'Y' : (gameMenuMode == 1) ? 'R' : '2';
char winChar = (winner == 1) ? 'Y' : (winner == 2) ? 'R' : 'D';
GameEntry entry = { type, gameLevel, winChar, currentMoves };
if (gameLogCount < MAX_GAME_LOG) { gameLog[gameLogCount++] = entry; }
else { for (int i = 0; i < MAX_GAME_LOG - 1; i++) gameLog[i] = gameLog[i + 1]; gameLog[MAX_GAME_LOG - 1] = entry; }
saveGameLog();
}
void saveGameLog() {
prefs.putUChar("glc", gameLogCount);
for (int i = 0; i < gameLogCount; i++) {
String val = String(gameLog[i].type) + ":" + String(gameLog[i].level) + ":" + String(gameLog[i].winner) + ":" + gameLog[i].moves;
prefs.putString(("g" + String(i)).c_str(), val);
}
}
void loadGameLog() {
gameLogCount = prefs.getUChar("glc", 0);
if (gameLogCount > MAX_GAME_LOG) gameLogCount = MAX_GAME_LOG;
for (int i = 0; i < gameLogCount; i++) {
String val = prefs.getString(("g" + String(i)).c_str(), "");
if (val.length() < 5) { gameLogCount = i; break; }
gameLog[i].type = val.charAt(0);
int sep1 = val.indexOf(':', 2);
gameLog[i].level = val.substring(2, sep1).toInt();
gameLog[i].winner = val.charAt(sep1 + 1);
gameLog[i].moves = val.substring(sep1 + 3);
}
}
void randomizeDemoPlies() {
uint8_t strong = random(4, 6);
uint8_t weak = random(2, 4);
if (random(2) == 0) { demoPly[0] = strong; demoPly[1] = weak; }
else { demoPly[0] = weak; demoPly[1] = strong; }
}
// --- Display ---
void drawStaticUI() {
FastLED.clear();
#if SHOW_BORDER == 1
CRGB borderColor = CRGB::Blue;
if (gameState == DEMO || gameState >= 3) {
if (gameState == DEMO || gameState == FINISHED_WIN || gameState == FINISHED_DRAW) {
uint8_t glow = beat8(15);
borderColor = blend(CRGB::Blue, CRGB::White, glow / 4);
}
for (int x = 0; x < 7; x++) leds[getIdx(x, 1)] = borderColor;
for (int y = 1; y < 8; y++) leds[getIdx(7, y)] = borderColor;
drawBorder(borderColor);
#endif
}
void renderBoard() {
drawStaticUI();
if (gameState == PLAYING || gameState == AI_TURN) {
CRGB indicator = (menuMode == 0) ? CRGB::Yellow : (menuMode == 1) ? CRGB::Red : CRGB::Blue;
indicator.nscale8(25);
leds[getIdx(7, 0)] = indicator;
}
for (int c = 0; c < COLS; c++) {
for (int r = 0; r < ROWS; r++) {
if (board[c][r] == 1) leds[getIdx(c, 7 - r)] = CRGB::Yellow;
if (board[c][r] == 2) leds[getIdx(c, 7 - r)] = CRGB::Red;
if (board[c][r] != 0) leds[getIdx(c, 7 - r)] = playerColor(board[c][r]);
}
}
}
void showMenu() {
FastLED.clear();
#if SHOW_BORDER == 1
drawBorder(CRGB::Blue);
#endif
CRGB pCol = (menuMode == 1) ? CRGB::Red : CRGB::Yellow;
if (menuMode < 2) {
for (int y = 3; y <= 6; y++) leds[getIdx(3, y)] = pCol;
leds[getIdx(2, 3)] = pCol; leds[getIdx(4, 3)] = pCol;
leds[getIdx(2, 6)] = pCol; leds[getIdx(4, 6)] = pCol;
} else {
for (int y = 3; y <= 6; y++) { leds[getIdx(2, y)] = CRGB::Yellow; leds[getIdx(4, y)] = CRGB::Red; }
leds[getIdx(1, 3)] = CRGB::Yellow; leds[getIdx(3, 3)] = CRGB::Yellow;
leds[getIdx(1, 6)] = CRGB::Yellow; leds[getIdx(3, 6)] = CRGB::Yellow;
leds[getIdx(3, 3)] = CRGB::Red; leds[getIdx(5, 3)] = CRGB::Red;
leds[getIdx(3, 6)] = CRGB::Red; leds[getIdx(5, 6)] = CRGB::Red;
}
FastLED.show();
}
// --- Game logic ---
int getFirstEmptyRow(int col) {
for (int r = 0; r < ROWS; r++) if (board[col][r] == 0) return r;
return -1;
}
bool isBoardFull() {
for (int c = 0; c < COLS; c++) if (board[c][ROWS-1] == 0) return false;
for (int c = 0; c < COLS; c++) if (board[c][ROWS - 1] == 0) return false;
return true;
}
int getDynamicPly() {
if (!progressive_difficulty && gameState != DEMO) return current_look_ahead;
if (!progressiveDifficulty && gameState != DEMO) return currentLookAhead;
int count = 0;
for (int c = 0; c < COLS; c++) for (int r = 0; r < ROWS; r++) if (board[c][r] != 0) count++;
return constrain(current_look_ahead + (count / 7), 1, 10);
}
void updateThinkingVisuals(int8_t pColor, int8_t column) {
static uint32_t lastCycle = 0;
if (millis() - lastCycle < 20) return;
lastCycle = millis();
if (aiFadeUp) { aiBrightness += 25; if (aiBrightness >= 230) aiFadeUp = false; }
else { aiBrightness -= 25; if (aiBrightness <= 25) aiFadeUp = true; }
for (int x = 0; x < COLS; x++) leds[getIdx(x, 0)] = CRGB::Black;
CRGB aiColor = (pColor == 1) ? CRGB(CRGB::Yellow) : CRGB(CRGB::Red);
aiColor.nscale8(aiBrightness);
leds[getIdx(column, 0)] = aiColor;
FastLED.show();
}
void animateDrop(int col, int player) {
int targetRow = getFirstEmptyRow(col);
if (targetRow == -1) return;
for (int r = 5; r >= targetRow; r--) {
renderBoard();
leds[getIdx(col, 7 - r)] = (player == 1) ? CRGB::Yellow : CRGB::Red;
FastLED.show();
delay(max(10, 60 - (5 - r) * 10));
}
board[col][targetRow] = player;
}
void moveDiscToCol(int startCol, int targetCol, int player, int speed) {
int current = startCol;
CRGB colr = (player == 1) ? CRGB::Yellow : CRGB::Red;
while (current != targetCol && !abortAi) {
if (gameState == DEMO && digitalRead(ENC_SW) == LOW) { abortAi = true; break; }
leds[getIdx(current, 0)] = CRGB::Black;
current += (targetCol > current) ? 1 : -1;
renderBoard();
leds[getIdx(current, 0)] = colr;
FastLED.show();
delay(speed);
}
activeCol = targetCol;
return constrain(currentLookAhead + (count / 7), 1, 10);
}
int8_t scanBoard() {
@@ -167,9 +241,73 @@ int8_t scanBoard() {
return 0;
}
bool checkGameEnd() {
winnerPlayer = scanBoard();
if (winnerPlayer != 0) {
if (gameState != DEMO) logGame(winnerPlayer);
gameState = FINISHED_WIN;
demoResetTimer = millis();
lastActivityTime = millis();
return true;
}
if (isBoardFull()) {
if (gameState != DEMO) logGame(0);
gameState = FINISHED_DRAW;
demoResetTimer = millis();
lastActivityTime = millis();
return true;
}
return false;
}
// --- Animation ---
void updateThinkingVisuals(int8_t pColor, int8_t column) {
static uint32_t lastCycle = 0;
if (millis() - lastCycle < 20) return;
lastCycle = millis();
if (aiFadeUp) { aiBrightness += 25; if (aiBrightness >= 230) aiFadeUp = false; }
else { aiBrightness -= 25; if (aiBrightness <= 25) aiFadeUp = true; }
for (int x = 0; x < COLS; x++) leds[getIdx(x, 0)] = CRGB::Black;
CRGB aiColor = playerColor(pColor);
aiColor.nscale8(aiBrightness);
leds[getIdx(column, 0)] = aiColor;
FastLED.show();
}
void animateDrop(int col, int player) {
int targetRow = getFirstEmptyRow(col);
if (targetRow == -1) return;
if (gameState != DEMO) currentMoves += String(col);
for (int r = 5; r >= targetRow; r--) {
renderBoard();
leds[getIdx(col, 7 - r)] = playerColor(player);
FastLED.show();
delay(max(10, 60 - (5 - r) * 10));
}
board[col][targetRow] = player;
}
void moveDiscToCol(int startCol, int targetCol, int player, int speed) {
int current = startCol;
CRGB colr = playerColor(player);
while (current != targetCol && !abortAi) {
if (gameState == DEMO && digitalRead(ENC_SW) == LOW) { abortAi = true; break; }
leds[getIdx(current, 0)] = CRGB::Black;
current += (targetCol > current) ? 1 : -1;
renderBoard();
leds[getIdx(current, 0)] = colr;
FastLED.show();
delay(speed);
}
activeCol = targetCol;
}
// --- AI ---
int minimax(int depth, int alpha, int beta, bool isMax, int8_t aiP, int8_t huP, int8_t rootCol) {
if (gameState == DEMO && digitalRead(ENC_SW) == LOW) { abortAi = true; return 0; }
if (depth >= current_look_ahead - 1) updateThinkingVisuals(aiP, rootCol);
if (depth >= currentLookAhead - 1) updateThinkingVisuals(aiP, rootCol);
else yield();
if (abortAi) return 0;
@@ -178,14 +316,13 @@ int minimax(int depth, int alpha, int beta, bool isMax, int8_t aiP, int8_t huP,
if (win == huP) return -1000 - depth;
if (depth == 0 || isBoardFull()) return 0;
int colOrder[] = {3, 2, 4, 1, 5, 0, 6};
int best = isMax ? -10000 : 10000;
for (int c : colOrder) {
if (abortAi) return 0;
int r = getFirstEmptyRow(c);
if (r != -1) {
board[c][r] = isMax ? aiP : huP;
int score = minimax(depth - 1, alpha, beta, !isMax, aiP, huP, (depth == current_look_ahead ? c : rootCol));
int score = minimax(depth - 1, alpha, beta, !isMax, aiP, huP, (depth == currentLookAhead ? c : rootCol));
board[c][r] = 0;
if (isMax) { if (score > best) best = score; if (best > alpha) alpha = best; }
else { if (score < best) best = score; if (best < beta) beta = best; }
@@ -199,10 +336,10 @@ void performAiMove(int8_t aiP) {
abortAi = false;
int huP = (aiP == 1) ? 2 : 1;
int bestScore = -30000; int bestCol = 3;
int originalPly = current_look_ahead;
current_look_ahead = (gameState == DEMO) ? demoPly : getDynamicPly();
int originalPly = currentLookAhead;
currentLookAhead = (gameState == DEMO) ? demoPly[aiP - 1] : getDynamicPly();
for (int c=0; c<COLS; c++) {
for (int c = 0; c < COLS; c++) {
int r = getFirstEmptyRow(c);
if (r != -1) {
board[c][r] = aiP; if (scanBoard() == aiP) { board[c][r]=0; bestCol=c; goto finalizeMove; }
@@ -210,144 +347,210 @@ void performAiMove(int8_t aiP) {
board[c][r] = 0;
}
}
for (int c : {3, 2, 4, 1, 5, 0, 6}) {
for (int c : colOrder) {
if (abortAi) goto finalizeMove;
int r = getFirstEmptyRow(c);
if (r != -1) {
board[c][r] = aiP;
int score = minimax(current_look_ahead, -30000, 30000, false, aiP, huP, c);
int score = minimax(currentLookAhead, -30000, 30000, false, aiP, huP, c);
board[c][r] = 0;
if (score > bestScore) { bestScore = score; bestCol = c; }
}
}
finalizeMove:
current_look_ahead = originalPly;
currentLookAhead = originalPly;
if (!abortAi) { moveDiscToCol(activeCol, bestCol, aiP, 80); if (!abortAi) { delay(100); animateDrop(bestCol, aiP); } }
}
// --- Web handlers ---
void handleRoot() {
String html = "<html><head><meta name='viewport' content='width=device-width, initial-scale=1'><style>body{font-family:sans-serif;background:#121212;color:white;text-align:center;} .card{background:#222;padding:25px;border-radius:15px;display:inline-block;margin-top:20px;} input{width:100%;padding:10px;margin:10px 0;border-radius:5px;border:none;}</style></head><body><h1>Connect 4 Admin</h1><div class='card'><form action='/save' method='POST'>";
html += "Base AI Ply:<input type='number' name='ply' value='" + String(current_look_ahead) + "'>Brightness:<input type='number' name='br' value='" + String(current_brightness) + "'>Idle Timeout (s):<input type='number' name='idle' value='" + String(current_idle_timeout_ms / 1000) + "'>";
html += "Blunders: <input type='checkbox' name='blunder' " + String(blunder_enabled ? "checked" : "") + "><br>Evolution: <input type='checkbox' name='evolve' " + String(progressive_difficulty ? "checked" : "") + "><br><br><input type='submit' value='Save Settings' style='background:#28a745;color:white;'></form></div></body></html>";
String html = "<html><head><meta name='viewport' content='width=device-width, initial-scale=1'>"
"<style>"
"body{font-family:sans-serif;background:#121212;color:white;text-align:center;}"
".card{background:#222;padding:25px;border-radius:15px;display:inline-block;margin-top:20px;}"
"input{width:100%;padding:10px;margin:10px 0;border-radius:5px;border:none;}"
"table{width:100%;} th,td{padding:4px;}"
"</style></head><body>"
"<h1>Connect 4 Admin</h1>"
"<div class='card'><form action='/save' method='POST'>";
html += "Base AI Ply:<input type='number' name='ply' value='" + String(currentLookAhead) + "'>";
html += "Brightness:<input type='number' name='br' value='" + String(currentBrightness) + "'>";
html += "Idle Timeout (s):<input type='number' name='idle' value='" + String(currentIdleTimeoutMs / 1000) + "'>";
html += "Blunders: <input type='checkbox' name='blunder' " + String(blunderEnabled ? "checked" : "") + "><br>";
html += "Evolution: <input type='checkbox' name='evolve' " + String(progressiveDifficulty ? "checked" : "") + "><br><br>";
html += "<input type='submit' value='Save Settings' style='background:#28a745;color:white;'>";
html += "</form></div>";
html += "<div class='card' style='margin-top:15px;text-align:left;'><h3 style='text-align:center;'>Game Log</h3>";
if (gameLogCount == 0) {
html += "<p style='text-align:center;'>No games played yet.</p>";
} else {
html += "<table><tr><th>Type</th><th>Lvl</th><th>Winner</th><th>Moves</th></tr>";
for (int i = gameLogCount - 1; i >= 0; i--) {
bool playerWon = gameLog[i].type != '2' && gameLog[i].type == gameLog[i].winner;
html += playerWon ? "<tr style='color:#ff4444;'>" : "<tr>";
html += "<td>" + String(gameLog[i].type) + "</td>";
html += "<td>" + String(gameLog[i].level) + "</td>";
html += "<td>" + String(gameLog[i].winner) + "</td>";
html += "<td>" + gameLog[i].moves + "</td></tr>";
}
html += "</table>";
}
html += "</div></body></html>";
server.send(200, "text/html", html);
}
void handleSave() {
if (server.hasArg("ply")) { current_look_ahead = server.arg("ply").toInt(); prefs.putUChar("ply", current_look_ahead); }
if (server.hasArg("br")) { current_brightness = server.arg("br").toInt(); FastLED.setBrightness(current_brightness); prefs.putUChar("br", current_brightness); }
if (server.hasArg("idle")) { current_idle_timeout_ms = server.arg("idle").toInt() * 1000; prefs.putUInt("idle", current_idle_timeout_ms / 1000); }
blunder_enabled = server.hasArg("blunder"); prefs.putBool("blunder", blunder_enabled);
progressive_difficulty = server.hasArg("evolve"); prefs.putBool("evolve", progressive_difficulty);
if (server.hasArg("ply")) { currentLookAhead = server.arg("ply").toInt(); prefs.putUChar("ply", currentLookAhead); }
if (server.hasArg("br")) { currentBrightness = server.arg("br").toInt(); FastLED.setBrightness(currentBrightness); prefs.putUChar("br", currentBrightness); }
if (server.hasArg("idle")) { currentIdleTimeoutMs = server.arg("idle").toInt() * 1000; prefs.putUInt("idle", currentIdleTimeoutMs / 1000); }
blunderEnabled = server.hasArg("blunder"); prefs.putBool("blunder", blunderEnabled);
progressiveDifficulty = server.hasArg("evolve"); prefs.putBool("evolve", progressiveDifficulty);
server.sendHeader("Location", "/"); server.send(303);
}
void showMenu() {
FastLED.clear();
#if SHOW_BORDER == 1
for (int x = 0; x < 7; x++) leds[getIdx(x, 1)] = CRGB::Blue;
for (int y = 1; y < 8; y++) leds[getIdx(7, y)] = CRGB::Blue;
#endif
CRGB pCol = (menuMode == 1) ? CRGB::Red : CRGB::Yellow;
if (menuMode < 2) { for (int y = 3; y <= 6; y++) leds[getIdx(3, y)] = pCol; leds[getIdx(2, 3)] = pCol; leds[getIdx(4, 3)] = pCol; leds[getIdx(2, 6)] = pCol; leds[getIdx(4, 6)] = pCol; }
else { for (int y = 3; y <= 6; y++) { leds[getIdx(2, y)] = CRGB::Yellow; leds[getIdx(4, y)] = CRGB::Red; } leds[getIdx(1, 3)] = CRGB::Yellow; leds[getIdx(3, 3)] = CRGB::Yellow; leds[getIdx(1, 6)] = CRGB::Yellow; leds[getIdx(3, 6)] = CRGB::Yellow; leds[getIdx(3, 3)] = CRGB::Red; leds[getIdx(5, 3)] = CRGB::Red; leds[getIdx(3, 6)] = CRGB::Red; leds[getIdx(5, 6)] = CRGB::Red; }
FastLED.show();
// --- State handlers ---
void handleMenu(long newPos, bool pressed) {
if (millis() > globalInputCooldown) {
if (newPos != oldEncPos) { menuMode = (newPos % 3 + 3) % 3; oldEncPos = newPos; showMenu(); }
if (pressed) {
resetBoard();
currentMoves = "";
gameMenuMode = menuMode;
gameLevel = currentLookAhead;
currentPlayer = 1;
if (menuMode == 1) gameState = AI_TURN;
else gameState = PLAYING;
globalInputCooldown = millis() + 500;
}
}
}
void handlePlaying(long newPos, bool pressed) {
if (newPos != oldEncPos) { activeCol = (newPos % 7 + 7) % 7; oldEncPos = newPos; lastActivityTime = millis(); }
renderBoard();
leds[getIdx(activeCol, 0)] = playerColor(currentPlayer);
FastLED.show();
if (pressed) {
int row = getFirstEmptyRow(activeCol);
if (row != -1) {
animateDrop(activeCol, currentPlayer);
if (!checkGameEnd()) {
if (menuMode < 2) gameState = AI_TURN;
else currentPlayer = (currentPlayer == 1) ? 2 : 1;
}
lastActivityTime = millis();
}
}
}
void handleAiTurn() {
int8_t aiP = (menuMode == 0) ? 2 : 1;
performAiMove(aiP);
if (abortAi) { gameState = MENU; showMenu(); return; }
if (!checkGameEnd()) {
gameState = PLAYING;
currentPlayer = (aiP == 1) ? 2 : 1;
}
lastActivityTime = millis();
}
void handleDemo() {
renderBoard(); FastLED.show(); delay(300);
performAiMove(currentPlayer);
if (abortAi) { gameState = MENU; showMenu(); globalInputCooldown = millis() + 600; lastButtonState = LOW; return; }
if (!checkGameEnd()) {
currentPlayer = (currentPlayer == 1) ? 2 : 1;
}
}
void handleFinished() {
static uint32_t lastFlash = 0;
static bool toggle = true;
if (millis() - lastFlash > 300) {
lastFlash = millis();
toggle = !toggle;
renderBoard();
for (int i = 0; i < NUM_LEDS; i++) {
#if SHOW_BORDER == 1
if (leds[i] == CRGB::Blue) continue;
#endif
if (gameState == FINISHED_WIN) {
if (winMask[i]) leds[i] = toggle ? playerColor(winnerPlayer) : CRGB::Black;
else { CRGB c = leds[i]; c.nscale8(60); leds[i] = c; }
} else if (gameState == FINISHED_DRAW) {
if (!toggle) leds[i] = CRGB::Black;
}
}
FastLED.show();
}
if (millis() - demoResetTimer > 30000) {
resetBoard();
randomizeDemoPlies();
gameState = DEMO;
demoResetTimer = 0;
lastActivityTime = millis();
}
}
// --- Main ---
void setup() {
prefs.begin("c4-game", false);
current_look_ahead = prefs.getUChar("ply", 8); current_brightness = prefs.getUChar("br", 25);
current_idle_timeout_ms = prefs.getUInt("idle", 60) * 1000; blunder_enabled = prefs.getBool("blunder", false);
progressive_difficulty = prefs.getBool("evolve", false);
FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS); FastLED.setBrightness(current_brightness);
pinMode(ENC_SW, INPUT_PULLUP); WiFi.softAP("Connect4-Config", "12345678");
server.on("/", handleRoot); server.on("/save", HTTP_POST, handleSave); server.begin();
lastActivityTime = millis(); showMenu();
currentLookAhead = prefs.getUChar("ply", 8);
currentBrightness = prefs.getUChar("br", 25);
currentIdleTimeoutMs = prefs.getUInt("idle", 60) * 1000;
blunderEnabled = prefs.getBool("blunder", false);
progressiveDifficulty = prefs.getBool("evolve", false);
loadGameLog();
FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(currentBrightness);
pinMode(ENC_SW, INPUT_PULLUP);
WiFi.softAP("Connect4-Config", WIFI_PASSWORD);
server.on("/", handleRoot);
server.on("/save", HTTP_POST, handleSave);
server.begin();
lastActivityTime = millis();
showMenu();
}
void loop() {
server.handleClient();
long rawPos = myEnc.read();
long newPos = rawPos / SENSITIVITY;
long newPos = rawPos / SENSITIVITY;
bool currentButton = digitalRead(ENC_SW);
bool pressed = false;
if (currentButton == LOW && lastButtonState == HIGH) { if (millis() > globalInputCooldown) pressed = true; }
lastButtonState = currentButton;
// Interrupt check
if ((newPos != oldEncPos || pressed) && (gameState >= 3 || gameState == DEMO)) {
abortAi = true; memset(board, 0, sizeof(board)); winnerPlayer = 0;
// Interrupt: return to menu from finished/demo states
if ((newPos != oldEncPos || pressed) && (gameState == FINISHED_WIN || gameState == FINISHED_DRAW || gameState == DEMO)) {
abortAi = true;
resetBoard();
for (int i = 0; i < 10; i++) { fadeToBlackBy(leds, NUM_LEDS, 50); FastLED.show(); delay(15); }
gameState = MENU; showMenu(); oldEncPos = newPos; lastActivityTime = millis();
globalInputCooldown = millis() + 600; return;
globalInputCooldown = millis() + 600;
return;
}
// Idle watchdog logic (Added specific exemption for FINISHED state)
if (gameState != DEMO && (gameState < 3)) {
if (millis() - lastActivityTime > current_idle_timeout_ms) {
gameState = DEMO; memset(board, 0, sizeof(board)); currentPlayer = 1; return;
// Idle timeout: enter demo mode
if (gameState != DEMO && gameState != FINISHED_WIN && gameState != FINISHED_DRAW) {
if (millis() - lastActivityTime > currentIdleTimeoutMs) {
resetBoard();
randomizeDemoPlies();
gameState = DEMO;
currentPlayer = 1;
return;
}
}
if (gameState == MENU) {
if (millis() > globalInputCooldown) {
if (newPos != oldEncPos) { menuMode = (newPos % 3 + 3) % 3; oldEncPos = newPos; showMenu(); }
if (pressed) { memset(board, 0, sizeof(board)); if (menuMode == 1) { currentPlayer = 1; gameState = AI_TURN; } else { currentPlayer = 1; gameState = PLAYING; } globalInputCooldown = millis() + 500; }
}
}
else if (gameState == PLAYING) {
if (newPos != oldEncPos) { activeCol = (newPos % 7 + 7) % 7; oldEncPos = newPos; lastActivityTime = millis(); }
renderBoard(); leds[getIdx(activeCol, 0)] = (currentPlayer == 1) ? CRGB::Yellow : CRGB::Red; FastLED.show();
if (pressed) {
int row = getFirstEmptyRow(activeCol);
if (row != -1) {
animateDrop(activeCol, currentPlayer);
winnerPlayer = scanBoard();
if (winnerPlayer != 0) { gameState = FINISHED_WIN; demoResetTimer = millis(); lastActivityTime = millis(); }
else if (isBoardFull()) { gameState = FINISHED_DRAW; demoResetTimer = millis(); lastActivityTime = millis(); }
else { if (menuMode < 2) { gameState = AI_TURN; } else { currentPlayer = (currentPlayer == 1) ? 2 : 1; } }
lastActivityTime = millis();
}
}
}
else if (gameState == AI_TURN) {
int8_t aiP = (menuMode == 0) ? 2 : 1; performAiMove(aiP);
if (abortAi) { gameState = MENU; showMenu(); return; }
winnerPlayer = scanBoard();
if (winnerPlayer != 0) { gameState = FINISHED_WIN; demoResetTimer = millis(); lastActivityTime = millis(); }
else if (isBoardFull()) { gameState = FINISHED_DRAW; demoResetTimer = millis(); lastActivityTime = millis(); }
else { gameState = PLAYING; currentPlayer = (aiP == 1) ? 2 : 1; }
lastActivityTime = millis();
switch (gameState) {
case MENU: handleMenu(newPos, pressed); break;
case PLAYING: handlePlaying(newPos, pressed); break;
case AI_TURN: handleAiTurn(); break;
case DEMO: handleDemo(); break;
case FINISHED_WIN:
case FINISHED_DRAW: handleFinished(); break;
}
else if (gameState == DEMO) {
renderBoard(); FastLED.show(); delay(300); performAiMove(currentPlayer);
if (abortAi) { gameState = MENU; showMenu(); return; }
winnerPlayer = scanBoard();
if (winnerPlayer != 0) { gameState = FINISHED_WIN; demoResetTimer = millis(); lastActivityTime = millis(); }
else if (isBoardFull()) { gameState = FINISHED_DRAW; demoResetTimer = millis(); lastActivityTime = millis(); }
else { currentPlayer = (currentPlayer == 1) ? 2 : 1; }
}
else { // FINISHED state (WIN/DRAW)
static uint32_t lastFlash = 0; static bool toggle = true;
if (millis() - lastFlash > 300) {
lastFlash = millis(); toggle = !toggle; renderBoard();
for (int i = 0; i < NUM_LEDS; i++) {
#if SHOW_BORDER == 1
if (leds[i] == CRGB::Blue) continue;
#endif
if (gameState == FINISHED_WIN) {
if (winMask[i]) leds[i] = toggle ? (winnerPlayer == 1 ? CRGB::Yellow : CRGB::Red) : CRGB::Black;
else { CRGB c = leds[i]; c.nscale8(60); leds[i] = c; }
} else if (gameState == FINISHED_DRAW) { if (!toggle) leds[i] = CRGB::Black; }
}
FastLED.show();
}
// RECENT FIX: Prolonged display time for win (30 seconds)
if (millis() - demoResetTimer > 30000) {
memset(board, 0, sizeof(board));
gameState = DEMO;
demoResetTimer = 0;
lastActivityTime = millis(); // Refresh watchdog
}
}
}
}