From 29b1c8cbd20c59dfa2f06df65fca55faa5eb40d7 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 16 Feb 2026 09:05:58 +0000 Subject: [PATCH 1/5] Initial plan From c4ccf5f7830f4351a90c762c1966161db1b5b0ba Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 16 Feb 2026 09:08:20 +0000 Subject: [PATCH 2/5] Add comprehensive README.md explaining the codebase Co-authored-by: codervaruns <169798268+codervaruns@users.noreply.github.com> --- README.md | 433 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 433 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..0cbc7ec --- /dev/null +++ b/README.md @@ -0,0 +1,433 @@ +# Same Game + +A C++ implementation of the classic "Same Game" puzzle game with a graphical SDL2 interface and an intelligent computer opponent using advanced algorithms. + +## Table of Contents +- [Overview](#overview) +- [Game Rules](#game-rules) +- [Architecture](#architecture) +- [Key Features](#key-features) +- [Data Structures](#data-structures) +- [Algorithms](#algorithms) +- [File Structure](#file-structure) +- [Building and Running](#building-and-running) +- [Controls](#controls) +- [Technical Details](#technical-details) + +## Overview + +Same Game is a tile-matching puzzle game where the objective is to remove groups of same-colored tiles from a grid. This implementation features: + +- **Graphical User Interface**: Built with SDL2 and SDL2_ttf +- **Two-Player Mode**: User vs Computer with turn-based gameplay +- **Intelligent AI**: Computer opponent using Divide & Conquer, Dynamic Programming, and Minimax algorithms +- **Graph-Based Architecture**: Modern graph data structure for efficient tile management + +## Game Rules + +1. **Cluster Selection**: Click on a group of 2 or more adjacent tiles of the same color +2. **Scoring**: Points are awarded based on cluster size: `(size - 2)²` + - 2 tiles = 0 points + - 3 tiles = 1 point + - 4 tiles = 4 points + - 5 tiles = 9 points + - And so on... +3. **Gravity**: After removing a cluster: + - Tiles fall down to fill empty spaces (vertical gravity) + - Empty columns shift left (horizontal gravity) +4. **Turn-Based**: Players alternate turns (User starts first) +5. **Game End**: Game ends when no more valid moves exist (no clusters of 2+ tiles) +6. **Winner**: Player with the highest score wins + +## Architecture + +### High-Level Design + +``` +┌─────────────────────────────────────────────────────────┐ +│ main.cpp │ +│ ┌──────────────────────────────────────────────────┐ │ +│ │ SameGameGUI (SDL2 Interface) │ │ +│ │ - Window & Rendering │ │ +│ │ - User Input Handling │ │ +│ │ - Visual Feedback │ │ +│ └──────────────────┬───────────────────────────────┘ │ +│ │ │ +└─────────────────────┼───────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────┐ +│ SameGame.h / SameGame.cpp │ +│ ┌──────────────────────────────────────────────────┐ │ +│ │ Core Game Logic (SameGame Class) │ │ +│ │ │ │ +│ │ Graph Structure: │ │ +│ │ - vector nodes │ │ +│ │ - vector> nodeGrid │ │ +│ │ │ │ +│ │ Game State: │ │ +│ │ - Score tracking (user vs computer) │ │ +│ │ - Turn management │ │ +│ │ - Move validation │ │ +│ │ │ │ +│ │ Algorithms: │ │ +│ │ - BFS for cluster detection │ │ +│ │ - Gravity simulation │ │ +│ │ - AI decision making (D&C + DP + Minimax) │ │ +│ └──────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────┘ +``` + +## Key Features + +### 1. **Graph-Based Data Structure** +The game uses a graph representation instead of a traditional 2D array, providing: +- More intuitive tile connectivity +- Efficient neighbor queries through adjacency lists +- Flexibility for future non-rectangular grids +- Clear separation of position, color, and connectivity + +### 2. **Intelligent AI Opponent** +The computer opponent uses a combination of algorithms: + +- **Divide & Conquer**: Efficiently finds all clusters by recursively splitting the column range +- **Dynamic Programming**: Memoizes board states to avoid recalculating positions +- **Minimax with Negamax**: Looks ahead 3 moves to choose optimal plays +- **Pruning**: Only evaluates top 6 largest clusters to improve performance + +### 3. **Real-Time Visual Feedback** +- Hover highlighting shows potential clusters before clicking +- Cluster size and point preview +- Score tracking for both players +- Turn indicator +- Game over detection with winner announcement + +### 4. **Comprehensive Testing** +Includes a test suite (`test_graph.cpp`) that validates: +- Grid initialization +- Tile queries and state management +- Cluster detection algorithm +- Gravity mechanics +- Score calculation +- Turn-based gameplay + +## Data Structures + +### Node Structure +```cpp +struct Node { + int row; // Current row position + int col; // Current column position + char color; // Tile color ('G', 'W', 'R', 'B', 'Y') + bool active; // Whether tile is still in play + vector neighbors; // Indices of adjacent nodes +}; +``` + +### SameGame Class +```cpp +class SameGame { +private: + vector nodes; // All tiles as graph nodes + vector> nodeGrid; // Position → node index mapping + int rows, cols; // Grid dimensions + int score, moves; // Game state + bool isUserTurn; // Turn management + int userScore, computerScore; // Player scores + unordered_map dpMemo; // DP memoization cache + +public: + // Game state queries + char getTile(int row, int col); + bool isTileActive(int row, int col); + int getClusterSize(int row, int col); + + // Game actions + bool removeCluster(int row, int col); + bool hasMovesLeft(); + + // AI decision making + pair getBestMove(); +}; +``` + +## Algorithms + +### 1. Cluster Detection (BFS) +``` +Time Complexity: O(N) where N = number of tiles in cluster +Space Complexity: O(N) + +Algorithm: +1. Start from a tile position +2. Use queue to explore same-colored neighbors +3. Mark visited tiles to avoid duplicates +4. Return all tiles in connected component +``` + +### 2. Gravity Application +``` +Time Complexity: O(rows × cols) + +Vertical Gravity: +- For each column, move active tiles down +- Fill from bottom to top + +Horizontal Gravity: +- Shift non-empty columns to the left +- Compact the grid horizontally +``` + +### 3. Computer AI (Minimax with DP) +``` +Time Complexity: O(B^D) where B = branching factor, D = depth +Space Complexity: O(S) where S = number of unique board states + +Algorithm: +1. Get all available clusters +2. Sort by size (largest first) +3. For top N clusters: + a. Simulate the move + b. Recursively evaluate with lookahead + c. Use memoization to cache results + d. Restore board state +4. Choose move with best evaluation score +``` + +### 4. Board State Memoization +```cpp +string boardStateKey() { + // Creates unique string representation: + // Turn indicator + grid colors + // Example: "UGGWRWWWRWWWR" for user turn + string key = (isUserTurn ? 'U' : 'C'); + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + key += active ? color : '.'; + } + } + return key; +} +``` + +## File Structure + +``` +Same-Game/ +├── SameGame.h # Game logic class header +│ └── Defines Node structure and SameGame class interface +│ +├── SameGame.cpp # Game logic implementation +│ ├── Graph construction and management +│ ├── Cluster detection (BFS) +│ ├── Gravity simulation +│ ├── AI algorithms (D&C, DP, Minimax) +│ └── Game state management +│ +├── main.cpp # SDL2 GUI implementation +│ ├── SameGameGUI class +│ ├── Rendering and visual feedback +│ ├── User input handling +│ └── Game loop +│ +├── test_graph.cpp # Test suite +│ └── Validates graph implementation +│ +├── greedy.cpp # Original console version (deprecated) +│ └── Simple greedy algorithm implementation +│ +├── BUILD.md # Build instructions and prerequisites +├── GRAPH_STRUCTURE.md # Detailed graph implementation docs +├── build.sh / build.bat # Build scripts +└── README.md # This file (codebase documentation) +``` + +## Building and Running + +### Prerequisites +- C++17 compiler (g++ or MinGW) +- SDL2 library +- SDL2_ttf library + +### Installation (Windows/MSYS2) +```bash +# Install MSYS2 from https://www.msys2.org/ +# Open MSYS2 MinGW 64-bit terminal +pacman -S mingw-w64-x86_64-SDL2 mingw-w64-x86_64-SDL2_ttf +``` + +### Build Commands +```bash +# Build the game +g++ -std=c++17 -I. SameGame.cpp main.cpp -o SameGame.exe \ + -lmingw32 -lSDL2main -lSDL2 -lSDL2_ttf + +# Run the game +./SameGame.exe + +# Build tests +g++ -std=c++17 -I. SameGame.cpp test_graph.cpp -o test_graph + +# Run tests +./test_graph +``` + +### Using Build Scripts +```bash +# Linux/Mac +./build.sh + +# Windows +build.bat +``` + +## Controls + +| Input | Action | +|-------|--------| +| **Mouse Hover** | Highlight cluster under cursor | +| **Left Click** | Remove highlighted cluster (on user's turn) | +| **R Key** | Restart game with new random grid | +| **ESC Key** | Quit game | + +## Technical Details + +### Grid Configuration +- Default size: 6 rows × 8 columns +- 5 colors: Green (G), White (W), Red (R), Blue (Y), Yellow (Y) +- Random initialization using time-based seed + +### Display Configuration +```cpp +const int WINDOW_WIDTH = 750; +const int WINDOW_HEIGHT = 650; +const int TILE_SIZE = 80; +const int GRID_OFFSET_X = 80; +const int GRID_OFFSET_Y = 140; +``` + +### AI Configuration +```cpp +const Uint32 COMPUTER_MOVE_DELAY = 3000; // 3 seconds between moves +const int LOOK_AHEAD_DEPTH = 3; // Minimax depth +const int TOP_N_MOVES = 6; // Evaluate top 6 clusters +``` + +### Scoring Formula +```cpp +points = (clusterSize - 2)² + +Examples: +- 2 tiles: (2-2)² = 0 points +- 3 tiles: (3-2)² = 1 point +- 4 tiles: (4-2)² = 4 points +- 5 tiles: (5-2)² = 9 points +- 10 tiles: (10-2)² = 64 points +``` + +### Color Mapping +```cpp +'G' → Green (0, 200, 0) +'W' → White (255, 255, 255) +'R' → Red (200, 0, 0) +'B' → Blue (0, 0, 200) +'Y' → Yellow (200, 200, 0) +``` + +## Design Decisions + +### Why Graph-Based Structure? +The transition from a 2D array to a graph provides: + +1. **Better Abstraction**: Tiles are explicitly connected entities +2. **Efficient Queries**: O(1) neighbor access through adjacency lists +3. **Future-Proof**: Can support hexagonal or irregular grids +4. **Algorithm-Friendly**: Graph algorithms (BFS, DFS) apply naturally + +### Why Minimax for AI? +1. **Optimal Play**: Looks ahead to choose best moves +2. **Competitive**: Creates challenging opponent +3. **Balanced**: Not too easy, not unbeatable +4. **Demonstrative**: Shows AI game theory concepts + +### Why Turn-Based? +1. **Strategic Depth**: Players must think ahead +2. **Fair Competition**: Both players have equal opportunities +3. **Learning Tool**: Users can observe AI's strategies +4. **Game Flow**: Creates natural pause for observation + +## Performance Characteristics + +### Time Complexities +- **Cluster Detection**: O(C) where C = cluster size +- **Gravity Application**: O(R × C) where R×C = grid size +- **Move Validation**: O(N) where N = total tiles +- **AI Move Selection**: O(B^D) where B = branching factor, D = depth +- **Board State Hash**: O(R × C) + +### Space Complexities +- **Graph Storage**: O(N) for N tiles +- **Adjacency Lists**: O(4N) average (4 neighbors per tile) +- **DP Memoization**: O(S) where S = unique board states +- **BFS Queue**: O(C) for cluster detection + +## Testing + +The test suite validates: +- ✓ Grid initialization +- ✓ Tile queries (getTile, isTileActive) +- ✓ Cluster detection with various sizes +- ✓ Cluster removal and scoring +- ✓ Gravity mechanics (vertical and horizontal) +- ✓ getAllClusters functionality +- ✓ Game state (hasMovesLeft, reset) +- ✓ Turn-based gameplay +- ✓ Edge cases (invalid positions, single tiles) + +Run tests with: +```bash +./test_graph +``` + +Expected output: All tests should pass with "✓" marks. + +## Future Enhancements + +Potential improvements for the codebase: +1. **Difficulty Levels**: Adjustable AI depth and evaluation +2. **Undo/Redo**: Move history and backtracking +3. **Save/Load**: Game state persistence +4. **Statistics**: Track high scores and win rates +5. **Animations**: Smooth tile removal and gravity effects +6. **Sound Effects**: Audio feedback for moves +7. **Online Multiplayer**: Network play support +8. **Different Grid Sizes**: Configurable dimensions +9. **Power-ups**: Special tiles or abilities +10. **Campaign Mode**: Progressive difficulty levels + +## Contributing + +When contributing to this codebase: +1. Maintain the graph-based architecture +2. Add tests for new features +3. Update documentation +4. Follow existing code style +5. Ensure backward compatibility + +## License + +This is an educational project demonstrating: +- Graph data structures +- Game AI algorithms (Minimax, Dynamic Programming) +- SDL2 GUI programming +- Algorithm optimization techniques + +## Authors + +- **codervaruns** - Initial implementation and architecture + +## Acknowledgments + +- Classic Same Game for inspiration +- SDL2 library for graphics +- Graph theory and AI algorithms from computer science fundamentals From c652175710e8b73e8ad96d08915ebdb42c4d1b80 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 16 Feb 2026 09:09:13 +0000 Subject: [PATCH 3/5] Add quick reference codebase summary document Co-authored-by: codervaruns <169798268+codervaruns@users.noreply.github.com> --- CODEBASE_SUMMARY.md | 268 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 268 insertions(+) create mode 100644 CODEBASE_SUMMARY.md diff --git a/CODEBASE_SUMMARY.md b/CODEBASE_SUMMARY.md new file mode 100644 index 0000000..f395d41 --- /dev/null +++ b/CODEBASE_SUMMARY.md @@ -0,0 +1,268 @@ +# Codebase Summary - Same Game + +## Quick Overview +This is a C++ implementation of the classic Same Game puzzle with: +- **SDL2 GUI** for graphics +- **User vs Computer** gameplay +- **Graph-based** architecture +- **AI opponent** using Minimax + Dynamic Programming + +## Project Purpose +Educational game demonstrating: +1. Graph data structures in practice +2. Game AI algorithms (Minimax, DP, D&C) +3. SDL2 GUI development +4. Algorithm optimization techniques + +## Key Components + +### 1. Core Game Engine (`SameGame.h/cpp`) +**What it does**: Manages all game logic and state +- Graph-based tile representation +- Cluster detection using BFS +- Gravity simulation (vertical + horizontal) +- AI decision making with lookahead +- Turn-based gameplay management + +**Key Algorithm**: Minimax with DP memoization +``` +Look ahead 3 moves → Evaluate board states → Choose optimal move +``` + +### 2. GUI Layer (`main.cpp`) +**What it does**: Visual interface and user interaction +- SDL2 window and rendering +- Mouse hover preview with highlighting +- Click handling for moves +- Score and turn display +- Computer move animation (3 second delay) + +**Main Loop**: Event handling → State updates → Rendering (60 FPS) + +### 3. Graph Structure +**Why graphs instead of 2D arrays?** +- Explicit tile connectivity +- O(1) neighbor access via adjacency lists +- Future-proof for non-rectangular grids +- Natural fit for BFS/DFS algorithms + +**Structure**: +```cpp +Node { + row, col // Position + color // G/W/R/B/Y + active // Still in play? + neighbors[] // Adjacent node indices +} +``` + +## How It Works + +### Game Flow +``` +1. Initialize 6×8 random grid +2. User's turn: Click cluster → Remove → Gravity → Switch turn +3. Computer's turn: AI evaluates → Best move → Remove → Gravity → Switch turn +4. Repeat until no moves left +5. Highest score wins +``` + +### AI Decision Process +``` +1. Find all clusters (getAllClusters) +2. Sort by size (larger = better) +3. For top 6 clusters: + - Simulate move + - Recursively evaluate (3 moves deep) + - Use memoization for speed + - Undo simulation +4. Choose cluster with best score differential +``` + +### Gravity Mechanics +``` +Vertical: For each column, active tiles fall down +Horizontal: Empty columns shift left +Result: Compact grid with no gaps +``` + +## File Responsibilities + +| File | Purpose | Lines | Key Features | +|------|---------|-------|--------------| +| `SameGame.h` | Class interface | 96 | Node struct, SameGame class definition | +| `SameGame.cpp` | Game logic | 455 | BFS, gravity, AI algorithms, DP | +| `main.cpp` | GUI & rendering | 402 | SDL2 interface, user input, visuals | +| `test_graph.cpp` | Testing | 150+ | Validates all core functionality | +| `greedy.cpp` | Legacy | 157 | Original console version (deprecated) | + +## Code Statistics + +- **Total Lines**: ~1,100 (excluding tests) +- **Classes**: 2 (SameGame, SameGameGUI) +- **Algorithms**: 5+ (BFS, Minimax, DP, D&C, Gravity) +- **Data Structures**: Graph (nodes + adjacency lists) +- **Dependencies**: SDL2, SDL2_ttf + +## Architecture Patterns + +### 1. **Separation of Concerns** +- Game logic (SameGame) ↔ Presentation (SameGameGUI) +- No GUI code in game logic +- Game logic testable independently + +### 2. **Graph Representation** +- Nodes store state (position, color, active) +- Adjacency lists track connections +- Position mapping for O(1) lookups + +### 3. **State Management** +- Snapshot/restore for AI simulation +- Turn-based state tracking +- Score tracking per player + +### 4. **Algorithm Composition** +- D&C for cluster finding +- BFS for traversal +- DP for memoization +- Minimax for decision making + +## Performance Notes + +### Optimizations +✓ DP memoization prevents recalculation +✓ Top-N pruning limits search space +✓ Direct neighbor access via graph +✓ Board state hashing for quick lookup + +### Bottlenecks +⚠ AI evaluation depth limited to 3 moves +⚠ Minimax explores 6^3 = 216 states max +⚠ String-based board hashing (could use zobrist) + +## Testing Coverage + +Validated scenarios: +- ✓ Grid initialization +- ✓ Tile queries and state +- ✓ Cluster detection (various sizes) +- ✓ Gravity (vertical + horizontal) +- ✓ Scoring calculation +- ✓ Turn management +- ✓ Game ending conditions +- ✓ Edge cases + +Run: `./test_graph` + +## Common Operations + +### Add a New Color +1. Update `generateRandomGrid()` colors array +2. Add color case in `getColorForTile()` +3. Update documentation + +### Adjust AI Difficulty +```cpp +int lookDepth = 3; // Increase for harder +int limit = 6; // Evaluate more moves +``` + +### Change Grid Size +```cpp +generateRandomGrid(rows, cols); // In main() +``` + +### Modify Scoring +```cpp +int points = (clusterSize - 2) * (clusterSize - 2); // In removeCluster() +``` + +## Dependencies + +### Required Libraries +- **SDL2**: Window, rendering, events +- **SDL2_ttf**: Text rendering +- **C++17**: Modern C++ features + +### Installation (MSYS2) +```bash +pacman -S mingw-w64-x86_64-SDL2 mingw-w64-x86_64-SDL2_ttf +``` + +## Build & Run + +```bash +# Build game +g++ -std=c++17 -I. SameGame.cpp main.cpp -o SameGame.exe \ + -lmingw32 -lSDL2main -lSDL2 -lSDL2_ttf + +# Run +./SameGame.exe + +# Build tests +g++ -std=c++17 -I. SameGame.cpp test_graph.cpp -o test_graph + +# Run tests +./test_graph +``` + +## Design Philosophy + +### Why This Architecture? +1. **Educational**: Demonstrates multiple CS concepts +2. **Maintainable**: Clear separation of concerns +3. **Extensible**: Easy to add features +4. **Testable**: Logic isolated from UI +5. **Performant**: Optimized algorithms + +### Trade-offs Made +- **Simplicity vs Performance**: Chose readable code over micro-optimizations +- **Features vs Complexity**: Core gameplay over bells and whistles +- **AI Strength vs Speed**: Limited depth for responsive play +- **Portability vs Features**: Basic SDL2 for cross-platform support + +## Learning Outcomes + +By studying this codebase, you'll learn: +1. **Graph data structures** in practical application +2. **Game AI** using Minimax and Dynamic Programming +3. **SDL2** for game development +4. **Algorithm design** and optimization +5. **Software architecture** patterns +6. **C++17** modern features + +## Next Steps for Contributors + +### Easy Tasks +- Add sound effects +- Implement undo/redo +- Add high score persistence +- Create difficulty settings +- Add more color schemes + +### Medium Tasks +- Smooth animations +- Online multiplayer +- Save/load game state +- Campaign mode +- Power-ups system + +### Advanced Tasks +- Alpha-beta pruning for AI +- Neural network player +- 3D graphics +- Mobile port +- Competitive ranking system + +## Resources + +- **Full Documentation**: See `README.md` +- **Build Instructions**: See `BUILD.md` +- **Graph Details**: See `GRAPH_STRUCTURE.md` +- **Tests**: Run `test_graph` executable + +## Contact + +**Repository**: codervaruns/Same-Game +**Purpose**: Educational game development project +**Status**: Fully functional with comprehensive documentation From a122a6a3e821a34696b8045f2e380f00d5892fb2 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 16 Feb 2026 09:10:54 +0000 Subject: [PATCH 4/5] Add comprehensive code flow visualization document Co-authored-by: codervaruns <169798268+codervaruns@users.noreply.github.com> --- CODE_FLOW.md | 492 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 492 insertions(+) create mode 100644 CODE_FLOW.md diff --git a/CODE_FLOW.md b/CODE_FLOW.md new file mode 100644 index 0000000..ff8e7f0 --- /dev/null +++ b/CODE_FLOW.md @@ -0,0 +1,492 @@ +# Code Flow Visualization - Same Game + +This document provides visual representations of how the code flows through the Same Game application. + +## Table of Contents +- [Application Startup](#application-startup) +- [Game Loop](#game-loop) +- [User Move Flow](#user-move-flow) +- [Computer Move Flow](#computer-move-flow) +- [Cluster Removal Process](#cluster-removal-process) +- [Gravity Application](#gravity-application) +- [AI Decision Tree](#ai-decision-tree) +- [Data Flow](#data-flow) +- [Class Relationships](#class-relationships) + +## Application Startup + +``` +main() + │ + ├─► generateRandomGrid(6, 8) + │ └─► Returns: 6×8 grid with random colors (G/W/R/B/Y) + │ + ├─► SameGame game(initialGrid) + │ └─► Constructor + │ └─► reset(initialGrid) + │ ├─► buildGraph(initialGrid) + │ │ ├─► Create Node for each tile + │ │ ├─► Build nodeGrid mapping + │ │ └─► updateNeighbors() + │ │ └─► Set adjacency lists + │ └─► Initialize scores, turns, moves + │ + ├─► SameGameGUI gui(&game) + │ └─► Constructor (initialize SDL state) + │ + ├─► gui.init() + │ ├─► SDL_Init(SDL_INIT_VIDEO) + │ ├─► TTF_Init() + │ ├─► SDL_CreateWindow() + │ ├─► SDL_CreateRenderer() + │ └─► TTF_OpenFont() + │ + └─► gui.run() + └─► Enter main game loop... +``` + +## Game Loop + +``` +gui.run() - Main Game Loop (60 FPS) + │ + └─► while (!quit) + │ + ├─► SDL_PollEvent(&e) ───────────── Poll for events + │ │ + │ ├─► SDL_QUIT ──────────────────► quit = true + │ │ + │ ├─► SDL_MOUSEMOTION ───────────► handleMouseMove() + │ │ └─► screenToGrid() → getCluster() + │ │ + │ ├─► SDL_MOUSEBUTTONDOWN ───────► handleMouseClick() + │ │ └─► removeCluster() → check game over + │ │ + │ └─► SDL_KEYDOWN + │ ├─► R key ─────────────────► handleRestart() + │ └─► ESC key ───────────────► quit = true + │ + ├─► Computer Turn Logic ────────────── If !gameOver && !isUserTurn + │ └─► if (time >= 3 seconds) + │ └─► executeComputerMove() + │ └─► getBestMove() → removeCluster() + │ + ├─► render() ───────────────────────── Render frame + │ ├─► Clear screen + │ ├─► drawGrid() + │ ├─► drawUI() + │ └─► SDL_RenderPresent() + │ + └─► SDL_Delay(16) ──────────────────── ~60 FPS +``` + +## User Move Flow + +``` +User Clicks on Tile (row, col) + │ + └─► handleMouseClick(mouseX, mouseY) + │ + ├─► Check: gameOver? → return + ├─► Check: isUserTurn? → return if not + │ + ├─► screenToGrid(mouseX, mouseY) ────► (row, col) + │ + └─► game.removeCluster(row, col) + │ + ├─► detectClusterBFS(row, col) ──► Get cluster + │ │ + │ └─► BFS Algorithm + │ ├─► Start from (row, col) + │ ├─► Queue neighbors with same color + │ ├─► Mark visited + │ └─► Return cluster list + │ + ├─► Check: cluster.size() >= 2? ──► If not, return false + │ + ├─► Remove tiles ──────────────────► Mark nodes inactive + │ + ├─► Calculate score ───────────────► points = (size - 2)² + │ ├─► score += points + │ └─► userScore += points + │ + ├─► moves++ ───────────────────────► Increment move counter + │ + ├─► switchTurn() ──────────────────► isUserTurn = false + │ + └─► applyGravity() ────────────────► See gravity flow below +``` + +## Computer Move Flow + +``` +Computer's Turn (after 3 second delay) + │ + └─► executeComputerMove() + │ + └─► game.getBestMove() ───────────────► Returns (row, col) + │ + ├─► Clear DP memo + │ + ├─► getAllClusters() ─────────────► Get all valid clusters + │ │ + │ └─► For each active node: + │ └─► detectClusterBFS() → cluster + │ └─► If size >= 2, add to list + │ + ├─► Sort clusters (largest first) + │ + ├─► Evaluate top 6 clusters ──────► AI Decision Making + │ │ + │ └─► For each cluster: + │ │ + │ ├─► saveState() ──────────► Snapshot board + │ │ + │ ├─► removeCluster() ──────► Simulate move + │ │ + │ ├─► dpEvaluate(depth=3) ──► Recursive lookahead + │ │ │ + │ │ └─► Minimax Tree Search + │ │ ├─► Check memo cache + │ │ ├─► Get all clusters + │ │ ├─► Sort by size + │ │ ├─► Try top 3 moves + │ │ ├─► Recurse (depth - 1) + │ │ ├─► Min/Max selection + │ │ └─► Cache result + │ │ + │ ├─► Compare scores ────────► Track best move + │ │ + │ └─► restoreState() ────────► Undo simulation + │ + └─► Return best (row, col) + │ + └─► removeCluster(row, col) ──► Execute actual move +``` + +## Cluster Removal Process + +``` +removeCluster(row, col) + │ + ├─► detectClusterBFS(row, col) + │ │ + │ └─► BFS Traversal: + │ ┌──────────────────────────────────┐ + │ │ Queue: [(row,col)] │ + │ │ Visited: {} │ + │ │ Cluster: [] │ + │ └──────────────────────────────────┘ + │ │ + │ ├─► Pop (r,c) from queue + │ ├─► Add (r,c) to cluster + │ ├─► For each neighbor (up/right/down/left): + │ │ ├─► Check: same color? + │ │ ├─► Check: active? + │ │ ├─► Check: not visited? + │ │ └─► Add to queue + │ └─► Repeat until queue empty + │ + ├─► Validate: cluster.size() >= 2 + │ + ├─► Mark tiles inactive + │ └─► For each (r,c) in cluster: + │ └─► nodes[index].active = false + │ + ├─► Calculate score + │ └─► points = (size - 2)² + │ + ├─► Update player score + │ └─► If user turn: userScore += points + │ Else: computerScore += points + │ + ├─► Increment moves + │ + ├─► Switch turns + │ + └─► applyGravity() +``` + +## Gravity Application + +``` +applyGravity() + │ + ├─► PHASE 1: Vertical Gravity ────────────► Tiles fall down + │ │ + │ └─► For each column (j = 0 to cols-1): + │ │ + │ ├─► pos = rows - 1 (bottom) + │ │ + │ └─► For each row (i = rows-1 to 0): + │ │ + │ ├─► Get node at (i, j) + │ │ + │ └─► If node.active: + │ ├─► Move node to row 'pos' + │ ├─► Update nodeGrid[pos][j] + │ ├─► Update node.row = pos + │ └─► pos-- + │ + │ Result: Active tiles at bottom, gaps at top + │ + ├─► PHASE 2: Horizontal Gravity ──────────► Columns shift left + │ │ + │ ├─► col = 0 + │ │ + │ └─► For each column (j = 0 to cols-1): + │ │ + │ ├─► Check if column has any active tiles + │ │ + │ └─► If has tiles: + │ ├─► Move entire column to position 'col' + │ ├─► For each row: + │ │ ├─► Update nodeGrid[i][col] + │ │ └─► Update node.col = col + │ └─► col++ + │ + │ Result: No empty columns in the middle + │ + └─► updateNeighbors() ────────────────────► Rebuild adjacency + │ + └─► For each active node: + └─► Check 4 directions (up/right/down/left) + └─► Add active neighbors to adjacency list +``` + +## AI Decision Tree + +``` +getBestMove() - Computer AI Decision Process + │ + ├─► Get All Clusters + │ └─► Result: [(size:6,color:W,row:1,col:2), (size:4,color:G,row:0,col:0), ...] + │ + ├─► Sort by Size (descending) + │ └─► Result: [(6,W,1,2), (4,G,0,0), (3,R,2,3), (2,B,1,5), ...] + │ + ├─► Limit to Top 6 Clusters + │ └─► Pruning to reduce search space + │ + └─► Evaluate Each Cluster: + │ + For Cluster #1 (size 6): + │ + ├─► Save Current State + │ + ├─► Simulate Move + │ └─► Remove cluster → Apply gravity + │ + ├─► Evaluate Future (depth = 3) + │ │ + │ └─► dpEvaluate(3) + │ │ + │ ├─► Level 1 (User Turn): + │ │ ├─► Try user's best 3 moves + │ │ └─► Pick minimum score + │ │ + │ ├─► Level 2 (Computer Turn): + │ │ ├─► Try computer's best 3 moves + │ │ └─► Pick maximum score + │ │ + │ └─► Level 3 (User Turn): + │ ├─► Try user's best 3 moves + │ └─► Return minimum score + │ + ├─► Score = computerScore - userScore + │ + ├─► Restore State (undo simulation) + │ + └─► Track if best score + + Repeat for Clusters #2-6... + + Return cluster with highest score +``` + +## Data Flow + +``` +User Input → GUI Layer → Game Logic → Graph Structure + │ │ │ │ + │ │ │ └─► Node updates + │ │ │ + │ │ └─► Score/State updates + │ │ + │ └─► Visual feedback + │ + └─► Hover: Show cluster preview + Click: Execute move + +Computer AI → Game Logic → Graph Structure + │ │ │ + │ │ └─► Simulate moves + │ │ + │ └─► Evaluate positions + │ + └─► Choose best move → Execute + +Graph Updates → Gravity → Neighbor Updates + │ │ │ + │ │ └─► Rebuild adjacency lists + │ │ + │ └─► Compact grid + │ + └─► Mark nodes inactive +``` + +## Class Relationships + +``` +┌─────────────────────────────────────────────────────────┐ +│ main.cpp │ +│ │ +│ ┌───────────────────────────────────────────────────┐ │ +│ │ SameGameGUI │ │ +│ │ │ │ +│ │ Private: │ │ +│ │ - SDL_Window* window │ │ +│ │ - SDL_Renderer* renderer │ │ +│ │ - TTF_Font* font │ │ +│ │ - SameGame* game ───────────────────┐ │ │ +│ │ - hoveredCluster │ │ │ +│ │ - gameOver, gameWon │ │ │ +│ │ │ │ │ +│ │ Public: │ │ │ +│ │ + init() │ │ │ +│ │ + run() │ │ │ +│ │ + render() │ │ │ +│ │ + handleMouseMove() │ │ │ +│ │ + handleMouseClick() │ │ │ +│ │ + executeComputerMove() │ │ │ +│ └────────────────────────────────┬────────┘ │ │ +│ │ │ │ +│ │ Calls methods │ │ +│ │ │ │ +└───────────────────────────────────┼───────────────────┘ │ + │ │ + ▼ │ +┌─────────────────────────────────────────────────────────┘ +│ SameGame.h / SameGame.cpp +│ +│ ┌───────────────────────────────────────────────────┐ +│ │ SameGame │ +│ │ │ +│ │ Private: │ +│ │ - vector nodes ──────────────┐ │ +│ │ - vector> nodeGrid │ │ +│ │ - rows, cols │ │ +│ │ - score, moves │ │ +│ │ - isUserTurn │ │ +│ │ - userScore, computerScore │ │ +│ │ - dpMemo │ │ +│ │ │ │ +│ │ Private Methods: │ │ +│ │ - detectClusterBFS() │ │ +│ │ - applyGravity() │ │ +│ │ - buildGraph() │ │ +│ │ - updateNeighbors() │ │ +│ │ - dpEvaluate() │ │ +│ │ - saveState() / restoreState() │ │ +│ │ │ │ +│ │ Public Methods: │ │ +│ │ + getTile() │ │ +│ │ + isTileActive() │ │ +│ │ + getCluster() │ │ +│ │ + removeCluster() │ │ +│ │ + hasMovesLeft() │ │ +│ │ + getBestMove() ← AI │ │ +│ └────────────────────────────────────────┘ │ +│ │ +│ ┌───────────────────────────────────────────────────┘ +│ │ Node +│ │ +│ │ int row, col +│ │ char color +│ │ bool active +│ │ vector neighbors +│ └───────────────────────────────────────────────── +``` + +## Memory Layout + +``` +Graph Structure in Memory: + +nodes vector: +┌────────────────────────────────────────────────────┐ +│ [0] [1] [2] ... [47] │ +│ Node(0,0,G) Node(0,1,W) Node(0,2,R) Node │ +└────────────────────────────────────────────────────┘ + │ + └─► neighbors: [1, 8] (right and down) + +nodeGrid (6x8): +┌───┬───┬───┬───┬───┬───┬───┬───┐ +│ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ Row 0 +├───┼───┼───┼───┼───┼───┼───┼───┤ +│ 8 │ 9 │10 │11 │12 │13 │14 │15 │ Row 1 +├───┼───┼───┼───┼───┼───┼───┼───┤ +│16 │17 │18 │19 │20 │21 │22 │23 │ Row 2 +├───┼───┼───┼───┼───┼───┼───┼───┤ +│24 │25 │26 │27 │28 │29 │30 │31 │ Row 3 +├───┼───┼───┼───┼───┼───┼───┼───┤ +│32 │33 │34 │35 │36 │37 │38 │39 │ Row 4 +├───┼───┼───┼───┼───┼───┼───┼───┤ +│40 │41 │42 │43 │44 │45 │46 │47 │ Row 5 +└───┴───┴───┴───┴───┴───┴───┴───┘ + +After Gravity (example): +- Inactive nodes stay in nodes vector +- nodeGrid[i][j] = -1 for empty positions +- Active nodes repositioned, neighbors rebuilt +``` + +## Event Flow Timeline + +``` +Time Event Action +═══════════════════════════════════════════════════════════ +0ms Application Start Initialize SDL, create game +10ms First Render Display initial grid +15ms User hovers (1,2) Highlight white cluster (6 tiles) +200ms User clicks (1,2) Remove white cluster +201ms └─► detectClusterBFS Find 6 tiles +202ms └─► Mark inactive Set active=false for 6 nodes +203ms └─► Calculate score (6-2)² = 16 points +204ms └─► userScore += 16 User: 16, Computer: 0 +205ms └─► Switch turn isUserTurn = false +206ms └─► applyGravity Tiles fall, columns shift +210ms └─► Render update Show new board state +3210ms Computer's turn 3 second delay elapsed +3211ms └─► getBestMove AI evaluation starts +3215ms └─► getAllClusters Find 8 clusters +3216ms └─► Sort by size Largest first +3217ms └─► Evaluate top 6 Minimax with DP +3350ms └─► Return best (2,3) +3351ms └─► removeCluster(2,3) Execute AI move +3352ms └─► ... (same as user) Score, gravity, switch +3355ms └─► Render update Show AI's move +3356ms User's turn again User can click now +... +``` + +## Summary + +This visualization shows: +1. **Startup**: How the application initializes +2. **Game Loop**: Continuous event-render cycle +3. **Move Flow**: User and computer move execution +4. **Cluster Removal**: BFS-based tile matching +5. **Gravity**: Two-phase compaction algorithm +6. **AI**: Minimax decision tree with pruning +7. **Data Flow**: Information flow through layers +8. **Relationships**: How classes interact +9. **Memory**: Graph structure layout +10. **Timeline**: Real-time event sequence + +For more details, see: +- `README.md` - Full documentation +- `CODEBASE_SUMMARY.md` - Quick reference +- `GRAPH_STRUCTURE.md` - Graph implementation details +- Source code - `SameGame.h`, `SameGame.cpp`, `main.cpp` From 838b881026769adf99cc7bebdf682cbc5ad60dc4 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 16 Feb 2026 09:11:51 +0000 Subject: [PATCH 5/5] Add documentation index for easy navigation Co-authored-by: codervaruns <169798268+codervaruns@users.noreply.github.com> --- INDEX.md | 265 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 265 insertions(+) create mode 100644 INDEX.md diff --git a/INDEX.md b/INDEX.md new file mode 100644 index 0000000..99ef655 --- /dev/null +++ b/INDEX.md @@ -0,0 +1,265 @@ +# Documentation Index - Same Game Project + +Welcome to the Same Game project documentation! This index will guide you to the right documentation based on your needs. + +## 📚 Quick Navigation + +### For New Users: Start Here +**👉 [README.md](README.md)** - Comprehensive project documentation +- Overview of the game and features +- Complete architecture explanation +- Algorithms and data structures +- Building and running instructions +- Technical details and design decisions +- 433 lines | ~15 KB + +### For Quick Reference +**👉 [CODEBASE_SUMMARY.md](CODEBASE_SUMMARY.md)** - Quick reference guide +- High-level overview +- Key components at a glance +- File responsibilities +- Common operations +- Quick statistics +- 268 lines | ~7 KB + +### For Understanding Code Flow +**👉 [CODE_FLOW.md](CODE_FLOW.md)** - Visual flow diagrams +- Application startup sequence +- Game loop visualization +- User and computer move flows +- Cluster removal process +- Gravity application +- AI decision tree +- Memory layout diagrams +- Timeline of events +- 492 lines | ~22 KB + +### For Building the Project +**👉 [BUILD.md](BUILD.md)** - Build instructions +- Prerequisites and dependencies +- Installation steps (MSYS2/Manual) +- Compilation commands +- Run instructions +- Controls reference +- 38 lines | ~1 KB + +### For Graph Implementation Details +**👉 [GRAPH_STRUCTURE.md](GRAPH_STRUCTURE.md)** - Graph architecture +- Detailed graph structure explanation +- Transition from 2D array to graph +- Node structure and relationships +- Benefits of graph approach +- Testing information +- Backward compatibility notes +- 97 lines | ~3 KB + +## 🎯 Documentation by Use Case + +### "I want to understand what this project does" +Start with: **[README.md](README.md)** - Overview section + +### "I want to build and run the game" +Start with: **[BUILD.md](BUILD.md)** - Complete build guide + +### "I want to understand the code architecture" +Start with: **[CODEBASE_SUMMARY.md](CODEBASE_SUMMARY.md)** → **[CODE_FLOW.md](CODE_FLOW.md)** + +### "I want to understand the graph data structure" +Start with: **[GRAPH_STRUCTURE.md](GRAPH_STRUCTURE.md)** + +### "I want to modify or extend the code" +1. **[CODEBASE_SUMMARY.md](CODEBASE_SUMMARY.md)** - Understand components +2. **[CODE_FLOW.md](CODE_FLOW.md)** - See how data flows +3. **[GRAPH_STRUCTURE.md](GRAPH_STRUCTURE.md)** - Understand core structure +4. Source code - `SameGame.h`, `SameGame.cpp`, `main.cpp` + +### "I want to understand the AI algorithm" +1. **[README.md](README.md)** - Algorithms section +2. **[CODE_FLOW.md](CODE_FLOW.md)** - AI Decision Tree section +3. **[CODEBASE_SUMMARY.md](CODEBASE_SUMMARY.md)** - AI Decision Process +4. Source: `SameGame.cpp` - `getBestMove()` and `dpEvaluate()` + +### "I want to learn from this project" +Recommended reading order: +1. **[README.md](README.md)** - Overview and game rules +2. **[GRAPH_STRUCTURE.md](GRAPH_STRUCTURE.md)** - Data structure concepts +3. **[CODEBASE_SUMMARY.md](CODEBASE_SUMMARY.md)** - Architecture patterns +4. **[CODE_FLOW.md](CODE_FLOW.md)** - Implementation details +5. **[BUILD.md](BUILD.md)** - Try it yourself! + +### "I want to contribute" +Read in order: +1. **[CODEBASE_SUMMARY.md](CODEBASE_SUMMARY.md)** - Architecture overview +2. **[CODE_FLOW.md](CODE_FLOW.md)** - Understand data flow +3. **[README.md](README.md)** - Design philosophy & future enhancements +4. Review source code and tests + +## 📊 Documentation Statistics + +| Document | Lines | Size | Purpose | +|----------|-------|------|---------| +| README.md | 433 | 15 KB | Complete project guide | +| CODE_FLOW.md | 492 | 22 KB | Visual flow diagrams | +| CODEBASE_SUMMARY.md | 268 | 7 KB | Quick reference | +| GRAPH_STRUCTURE.md | 97 | 3 KB | Graph implementation | +| BUILD.md | 38 | 1 KB | Build instructions | +| **TOTAL** | **1,328** | **48 KB** | **Full documentation** | + +## 🔍 Key Topics Coverage + +### Architecture & Design +- **README.md** - High-level architecture diagrams +- **CODEBASE_SUMMARY.md** - Architecture patterns +- **CODE_FLOW.md** - Class relationships and data flow + +### Algorithms +- **README.md** - Algorithm descriptions with complexity +- **CODE_FLOW.md** - Visual algorithm flows +- **CODEBASE_SUMMARY.md** - Algorithm composition + +### Data Structures +- **GRAPH_STRUCTURE.md** - Detailed graph explanation +- **README.md** - Node structure and SameGame class +- **CODE_FLOW.md** - Memory layout visualization + +### Implementation Details +- **CODE_FLOW.md** - Step-by-step flows +- **CODEBASE_SUMMARY.md** - Code statistics +- **README.md** - Technical details section + +### Usage & Setup +- **BUILD.md** - Complete build guide +- **README.md** - Controls and configuration +- **CODEBASE_SUMMARY.md** - Common operations + +### Testing +- **GRAPH_STRUCTURE.md** - Test suite details +- **CODEBASE_SUMMARY.md** - Testing coverage +- **README.md** - Test validation + +## 🎓 Learning Path + +### Beginner (Just want to play) +``` +BUILD.md → Run the game → Enjoy! +``` + +### Intermediate (Want to understand) +``` +README.md → CODEBASE_SUMMARY.md → Try building → Read source code +``` + +### Advanced (Want to modify/contribute) +``` +All docs → Source code → Test suite → Make changes → Contribute +``` + +### Academic (Want to learn algorithms) +``` +README.md (Algorithms) → CODE_FLOW.md (AI Decision Tree) → +GRAPH_STRUCTURE.md → Source implementation → Experiment +``` + +## 📁 File Structure + +``` +Same-Game/ +├── Documentation/ +│ ├── INDEX.md ← You are here +│ ├── README.md ← Start here for overview +│ ├── CODEBASE_SUMMARY.md ← Quick reference +│ ├── CODE_FLOW.md ← Visual diagrams +│ ├── GRAPH_STRUCTURE.md ← Graph details +│ └── BUILD.md ← Build instructions +│ +├── Source Code/ +│ ├── SameGame.h ← Game logic header +│ ├── SameGame.cpp ← Game logic implementation +│ ├── main.cpp ← SDL2 GUI +│ └── greedy.cpp ← Original console version +│ +├── Testing/ +│ └── test_graph.cpp ← Test suite +│ +└── Build/ + ├── build.sh ← Linux/Mac build + ├── build.bat ← Windows build + └── build_output.txt ← Build logs +``` + +## 🚀 Quick Start Guide + +### Just want to play? +```bash +# See BUILD.md for full instructions +g++ -std=c++17 -I. SameGame.cpp main.cpp -o SameGame.exe \ + -lmingw32 -lSDL2main -lSDL2 -lSDL2_ttf +./SameGame.exe +``` + +### Want to understand the code? +1. Read **README.md** for overview +2. Read **CODEBASE_SUMMARY.md** for quick reference +3. Read **CODE_FLOW.md** for detailed flows +4. Explore source code with documentation as reference + +### Want to run tests? +```bash +g++ -std=c++17 -I. SameGame.cpp test_graph.cpp -o test_graph +./test_graph +``` + +## 💡 Tips for Reading Documentation + +1. **Don't read everything at once** - Use this index to find what you need +2. **Start broad, then go deep** - README → Summary → Detailed flows +3. **Use diagrams** - CODE_FLOW.md has extensive visualizations +4. **Cross-reference** - Documents link to each other +5. **Try the code** - Best way to understand is to run and modify it + +## 📝 Documentation Conventions + +- **Bold** for important terms and file names +- `Code font` for code, commands, and technical terms +- 👉 Arrows for recommended starting points +- ✓ Checkmarks for validated features +- ⚠ Warning symbols for important notes +- 📊 Tables for structured information +- 🎯 Emojis for visual navigation + +## 🤝 Contributing to Documentation + +When updating documentation: +1. Keep this INDEX.md updated with new files +2. Update cross-references between documents +3. Maintain consistent formatting +4. Add new sections to appropriate documents +5. Update statistics and line counts + +## 📧 Questions? + +If documentation is unclear: +1. Check if another document covers the topic +2. Review source code comments +3. Run the test suite for examples +4. Open an issue for documentation improvements + +## 🎉 Summary + +You now have access to **1,328 lines** of comprehensive documentation covering: +- ✅ Complete project overview +- ✅ Architecture and design patterns +- ✅ Algorithm explanations with visuals +- ✅ Data structure details +- ✅ Code flow diagrams +- ✅ Build and test instructions +- ✅ Quick reference guides +- ✅ Learning paths for all levels + +**Choose your path above and start exploring!** 🚀 + +--- + +*Last Updated: 2026-02-16* +*Documentation Version: 1.0* +*Project: Same Game - C++ Implementation*