An open API service indexing awesome lists of open source software.

https://github.com/daniel-pittman/rubiks-cube-solver

A repository detailing my attempt to "vibe code" a graphical Rubik's Cube solver with different LLMs
https://github.com/daniel-pittman/rubiks-cube-solver

ai-collaboration claude-code cli flask opengl pyside6 python rubiks-cube solver three-js

Last synced: about 12 hours ago
JSON representation

A repository detailing my attempt to "vibe code" a graphical Rubik's Cube solver with different LLMs

Awesome Lists containing this project

README

          


Rubik's Cube Solver β€” A Human-AI Collaboration Case Study

# Rubik's Cube Solver

**A Case Study in Human-AI Collaborative Software Development**

[![CI](https://github.com/daniel-pittman/rubiks-cube-solver/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/daniel-pittman/rubiks-cube-solver/actions/workflows/ci.yml)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![GitHub release](https://img.shields.io/github/v/release/daniel-pittman/rubiks-cube-solver)](https://github.com/daniel-pittman/rubiks-cube-solver/releases)

---

## πŸ“– Table of Contents

- [What Is This Project?](#-what-is-this-project)
- [The AI Development Story](#-the-ai-development-story)
- [Quick Start](#-quick-start)
- [Features](#-features)
- [Architecture](#-architecture)
- [What We Learned](#-what-we-learned)
- [Development Journey](#-development-journey)
- [Technical Details](#-technical-details)
- [Contributing](#-contributing)
- [License](#-license)

---

## 🎯 What Is This Project?

This is a **fully-functional Rubik's Cube solver** with three different interfaces (command-line, web, and desktop), built **entirely through conversation with Claude Code**, Anthropic's AI coding assistant.

**The goal?** To explore what's possible when humans and AI collaborate on complex software development, and to document the process so others can learn from it.

### Key Facts

- **100% of code generated by AI** (Claude Code)
- **Zero lines written directly by human** (except this README update!)
- **Complete working application** with 3D visualization, solving algorithms, and multiple UIs
- **Full documentation** of every prompt, decision, and iteration
- **Production-quality code** meeting professional standards (9.07/10 pylint score, 28 passing tests)

This project serves as a **real-world case study** for:
- What LLMs can do well (and where they struggle)
- How to effectively guide AI coding assistants
- The balance between AI capability and human direction
- Building production-quality software through natural language

---

## πŸ€– The AI Development Story

### What Went Well

**βœ… Algorithm Implementation**
- Claude Code successfully implemented complex cube mechanics using matrix transformations
- Built a plugin-based solver architecture with IDDFS (Iterative Deepening Depth-First Search)
- Created accurate 3D visualizations using Three.js and OpenGL

**βœ… Multiple UI Paradigms**
- Command-line interface with ANSI colors and interactive REPL
- Web interface with real-time WebSocket communication
- Desktop application with hardware-accelerated OpenGL rendering

**βœ… Code Quality & Testing**
- 28 comprehensive unit and integration tests (all passing)
- Consistent 9.0+ pylint scores throughout development
- Clean architecture with proper separation of concerns

**βœ… Documentation**
- Self-documenting code with comprehensive docstrings
- Detailed inline comments explaining complex logic
- Configuration files with explanatory headers

### Where Human Guidance Was Critical

**🧠 Architecture Decisions**
- Choosing the plugin-based solver system
- Deciding on the hybrid face-clicking + camera-dragging interaction model
- Structuring the project into phases (Core β†’ Solver β†’ CLI β†’ Web β†’ Desktop)

**🧠 Problem-Solving**
- Debugging cube rotation mechanics (initial implementation had incorrect edge cycling)
- Fixing animation timing issues (colors updating before vs. after animations)
- Resolving OpenGL context issues with face click detection

**🧠 UX Design**
- Making the desktop app non-blocking by moving solver to background thread
- Implementing "smart drag detection" to distinguish clicks from camera movements
- Choosing accessible color contrasts (WCAG AA compliance)

### What Didn't Work (At First)

**❌ Initial Cube Implementation**
- First attempt at cube moves had incorrect edge cycling for 5 out of 6 moves
- Required complete rewrite following proven matrix transformation approach
- **Lesson**: Start with proven approaches for complex algorithms

**❌ Animation Synchronization**
- Multiple attempts needed to get cube colors updating at the right time during animations
- Issue: Understanding when to save state (before move) vs. when to animate (after move)
- **Lesson**: State management in animations requires careful sequencing

**❌ Face Click Detection**
- Initial OpenGL picking implementation caused GLError (invalid operation)
- Root cause: Calling glReadPixels outside rendering context
- **Lesson**: Framework constraints (like OpenGL contexts) need explicit handling

### The Process

Development followed an **incremental, phase-based approach**:

1. **Phase 1**: Core cube mechanics (505 lines, 32 tests)
2. **Phase 2**: Solver system with plugin architecture (664 lines)
3. **Phase 3**: CLI interface with colored terminal (650+ lines)
4. **Phase 4**: Web interface with 3D visualization
5. **Phase 5**: Desktop application with OpenGL rendering

Each phase was completed **100%** before moving to the next. When bugs were found, we went back and fixed them properly rather than moving forward with technical debt.

---

## πŸš€ Quick Start

### Prerequisites

**You need Python installed.** Here's how to check and install:

```bash
# Check if Python is installed (need 3.11 or higher)
python3 --version

# If not installed:
# - macOS: Install from python.org or use `brew install python3`
# - Linux: `sudo apt install python3` or `sudo yum install python3`
# - Windows: Download from python.org and run installer
```

### Installation & Running

**The easiest way: Use the launcher script**

```bash
# Clone the repository
git clone https://github.com/daniel-pittman/rubiks-cube-solver.git
cd rubiks-cube-solver

# Run the launcher (handles everything automatically!)
./run_app.sh
```

The launcher will:
1. Create a Python virtual environment
2. Install all dependencies
3. Show you a menu to choose which interface to run

**Menu options:**
1. **CLI** - Command-line interface with colored cube display
2. **Web** - Flask server with 3D visualization (opens browser to localhost:5001)
3. **Desktop** - PySide6 application with OpenGL 3D rendering
4. **Tests** - Run all 28 unit tests to verify everything works

### Manual Installation (Alternative)

```bash
# Create virtual environment
python3 -m venv venv

# Activate it
source venv/bin/activate # On Windows: venv\Scripts\activate

# Install the project. Pick the extras you need:
# .[web] β€” Flask + Socket.IO for the web interface
# .[desktop] β€” PySide6 + PyOpenGL for the desktop interface
# .[all] β€” both web and desktop runtime extras
# .[dev] β€” linters + pytest (add this if you'll be contributing)
pip install -e ".[all]"

# Run specific interface
python -m solver.cli # Command-line
python -m solver.flask_app # Web (then open localhost:5001)
python -m solver.desktop_app # Desktop GUI
```

---

## ✨ Features

### 🧊 Core Functionality

- **Accurate Cube Mechanics**: Matrix-based state using proven transformation approach
- **IDDFS Solver**: Finds optimal solutions for scrambled cubes (depth 5-8)
- **Plugin Architecture**: Extensible solver system for future algorithms
- **Move Notation**: Standard Western notation (R, L, U, D, F, B, primes, doubles)
- **State Management**: Save and restore scrambled states for solution replay

### πŸ–₯️ Command-Line Interface

```
> scramble 5
🎲 Scrambling cube with 5 moves...
Moves: R U' F D L

> solve
🧠 Solving cube...
Solution found: L' D' F' U R'
[Step-by-step playback with colored visualization]

> help
[Comprehensive interactive help system]
```

**Features**:
- Colored ANSI terminal output (cross-platform)
- Interactive REPL with command history
- Manual move execution or sequence input
- Step-by-step solution visualization
- Undo/redo functionality

### 🌐 Web Interface

**Launch**: `python -m solver.flask_app` β†’ Open `http://localhost:5001`

**Interactive 3D Controls**:
- **Left-click face**: Clockwise rotation
- **Right-click face**: Counter-clockwise
- **Ctrl/Cmd+Click**: 180Β° rotation
- **Drag background**: Rotate camera view
- **Scroll**: Zoom in/out
- **Auto-rotate button**: Continuous rotation for viewing
- **Reset camera**: Return to default angle

**Features**:
- Real-time 3D cube with Three.js
- Smart drag detection (knows click vs drag)
- Live move history panel
- Solution generation and playback
- Save/restore scrambled states
- WebSocket real-time updates
- Mobile-responsive touch controls

### πŸ–ΌοΈ Desktop Application

**Launch**: `python -m solver.desktop_app`

**Features**:
- Hardware-accelerated OpenGL rendering
- Interactive face clicking (same controls as web)
- Smooth rotation animations with easing
- Background solver thread (UI stays responsive)
- Solution playback dialog with manual controls
- Camera orbit controls

---

## πŸ—οΈ Architecture

### Project Structure

```
solver/
β”œβ”€β”€ core/ # Core cube logic
β”‚ β”œβ”€β”€ cube.py # Cube implementation (505 lines)
β”‚ β”œβ”€β”€ solver.py # Solver interface (186 lines)
β”‚ β”œβ”€β”€ solvers/ # Plugin system
β”‚ β”‚ β”œβ”€β”€ base_solver.py # Abstract base (232 lines)
β”‚ β”‚ └── iddfs_solver.py # IDDFS algorithm (246 lines)
β”‚ └── tests/ # 28 unit tests
β”‚ β”œβ”€β”€ test_cube.py
β”‚ β”œβ”€β”€ test_cube_comprehensive.py
β”‚ └── test_scramble.py
β”œβ”€β”€ cli/ # Command-line interface
β”‚ β”œβ”€β”€ cli_app.py # Interactive CLI (650+ lines)
β”‚ └── __main__.py # Entry point
β”œβ”€β”€ web/ # Web interface
β”‚ β”œβ”€β”€ static/
β”‚ β”‚ β”œβ”€β”€ css/styles.css # Responsive styling
β”‚ β”‚ └── js/
β”‚ β”‚ β”œβ”€β”€ cube3d.js # Three.js visualization
β”‚ β”‚ β”œβ”€β”€ socket-client.js # WebSocket sync
β”‚ β”‚ β”œβ”€β”€ ui-controls.js # Interactive controls
β”‚ β”‚ └── app.js # Main app logic
β”‚ └── templates/
β”‚ └── index.html # Single-page app
β”œβ”€β”€ desktop/ # Desktop application
β”‚ β”œβ”€β”€ cube_gl_widget.py # OpenGL 3D widget
β”‚ └── __init__.py
β”œβ”€β”€ flask_app.py # Flask + SocketIO server
β”œβ”€β”€ desktop_app.py # PySide6 main window
└── tests/ # Integration tests
└── test_solver_integration.py
```

### Technology Stack

| Component | Technology |
|-----------|-----------|
| **Backend** | Python 3.11+, Flask, Flask-SocketIO |
| **Frontend** | Vanilla JavaScript, Three.js, Socket.IO |
| **Desktop** | PySide6 (Qt6), PyOpenGL |
| **Core Logic** | NumPy for array operations |
| **Testing** | pytest (28 tests, 100% pass rate) |
| **Code Quality** | black, isort, autoflake, pylint (9.07/10) |
| **Version Control** | Git with pre-commit hooks |

### Key Design Patterns

1. **Plugin Architecture**: Solvers register themselves; runtime selection
2. **State Preservation**: Save cube state before solving for replay
3. **Event-Driven UI**: WebSocket for web, Qt signals for desktop
4. **Hybrid Interaction**: Seamless blending of face clicks + camera controls
5. **Background Processing**: Threading for solver to keep UI responsive

---

## πŸŽ“ What We Learned

### About AI-Assisted Development

**LLMs Excel At:**
- Implementing well-defined algorithms from specifications
- Generating boilerplate and repetitive code structures
- Writing comprehensive tests and documentation
- Following consistent code styles and patterns
- Applying design patterns (plugins, facades, etc.)

**Humans Are Essential For:**
- High-level architecture decisions
- Debugging subtle interaction issues
- UX design and accessibility considerations
- Recognizing when to restart vs. iterate
- Deciding when "good enough" is actually good enough

**The Sweet Spot:**
- Human provides vision, direction, and judgment
- AI implements, tests, and documents
- Human reviews, guides refinement, and maintains quality bar
- Iterative back-and-forth until solution emerges

### About Rubik's Cube Solvers

**Technical Insights:**
- Matrix transformations are cleaner than position tracking
- Edge cycling is the tricky part (not face rotation)
- IDDFS works well for small scrambles (5-8 moves)
- State explosion makes depth >10 impractical without heuristics
- Animation timing requires careful state management

**UX Insights:**
- Hybrid click+drag mode feels more natural than mode switching
- Accessibility (color contrast, keyboard support) matters
- Background processing is critical for complex solvers
- Solution playback needs manual controls, not just auto-play

---

## πŸ“š Development Journey

This project was built through **~300+ conversational exchanges** over several sessions. Key milestones:

### Phase 1: Core Cube (September 2025)
- Initial attempt had incorrect edge cycling
- Complete rewrite using matrix transformation approach
- 32 unit tests, all moves validated mathematically
- **Learning**: Start with proven approaches for complex algorithms

### Phase 2: Solver System (September 2025)
- Designed plugin architecture for extensibility
- Implemented IDDFS optimal solver
- Created solver registry and auto-selection
- **Learning**: Good architecture pays off later

### Phase 3: CLI Interface (September 2025)
- Rich terminal UI with ANSI colors
- Interactive REPL with command history
- Cross-platform compatibility handling
- **Learning**: User experience matters even in CLI

### Phase 4: Web Interface (September 2025)
- Multiple iterations on interaction model
- Discovered hybrid click+drag approach
- Fixed animation synchronization issues
- **Learning**: UX iteration is essential, even with AI

### Phase 5: Desktop Application (October 2025)
- Implemented hardware-accelerated OpenGL rendering
- Solved UI freezing with background threads
- Fixed OpenGL context issues with face clicking
- **Learning**: Framework constraints require explicit handling

### Phase 6: Post-Launch Features (October 2025+)
- **Scramble Reveal**: Show scramble sequence in competition format
- Copy to clipboard functionality
- Spoiler text in move log (click-to-reveal)
- Responsive design refinements
- **Learning**: Rapid feature iteration based on user feedback

**Complete development log**: See [conversation_summary/](conversation_summary/) for every prompt and response organized by phase.

---

## πŸ”¬ Technical Details

### Cube Representation

Uses 3D NumPy array: `stickers[6 faces][3 rows][3 columns]`

```python
# Each face is a 3x3 grid of colors
stickers[Face.U] = [[W, W, W],
[W, W, W],
[W, W, W]]
```

**Color Scheme** (Western/WCA standard):
- White (U) ↔ Yellow (D)
- Red (R) ↔ Orange (L)
- Green (F) ↔ Blue (B)

### Move Execution

Standard notation: `R`, `L`, `U`, `D`, `F`, `B`
- Prime (`'`): Counter-clockwise
- Double (`2`): 180Β°

Implementation:
1. Rotate the face itself (`np.rot90`)
2. Cycle edge pieces between adjacent faces
3. Reverse appropriate edges for correct orientation

### IDDFS Solver

**Algorithm**: Iterative Deepening Depth-First Search
- Searches depth 1, then 2, then 3, etc.
- Guarantees optimal solution (fewest moves)
- Practical limit: depth 8 (~5-10 seconds)

**Optimization**: Prunes redundant moves (e.g., no `R` after `R'`)

### Web Architecture

**Client-Server Communication**:
```
Browser (Three.js) ←→ SocketIO ←→ Flask ←→ Cube Core
```

**State Sync**:
1. User action (click, scramble, solve)
2. Client emits WebSocket event
3. Server updates cube state
4. Server broadcasts state to all clients
5. Clients update 3D visualization

### Testing Strategy

**28 Tests covering**:
- Individual move correctness (6 tests)
- Mathematical properties (3 tests)
- Scramble validity (7 tests)
- Solver integration (6 tests)
- Edge cases (6 tests)

**Run tests**: `./run_app.sh` β†’ Select option 4

---

## 🀝 Contributing

This project welcomes contributions! Areas of interest:

### Enhancement Ideas
- **Additional Solvers**: Implement A*, IDA*, or Kociemba's algorithm
- **Performance**: Optimize IDDFS with pattern databases
- **Features**: Cube timer, move counter, solution comparison
- **UI/UX**: Improved animations, themes, tutorials

### Development Setup

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Run `./run_python_formatters.sh` (must score β‰₯9.0/10)
5. Run tests: `pytest solver/ -v`
6. Submit pull request

**Code Standards**:
- Black formatting (auto-applied)
- Pylint score β‰₯9.0
- Type hints where helpful
- Comprehensive docstrings
- Unit tests for new functionality

---

## πŸ“– Additional Documentation

- **[CLAUDE.md](CLAUDE.md)**: Instructions for continuing development with Claude Code
- **[DEVELOPMENT_JOURNAL.md](DEVELOPMENT_JOURNAL.md)**: Retrospective from Claude's perspective with technical architecture and lessons learned
- **[conversation_summary/](conversation_summary/)**: Complete conversation history organized by development phase

---

## πŸ“„ License

MIT License - See [LICENSE](LICENSE) for details

Copyright (c) 2025 Daniel Pittman

---

## πŸ™ Acknowledgments

- **MagicCube** ([github.com/trincaog/magiccube](https://github.com/trincaog/magiccube)): Reference for cube mechanics
- **Three.js**: 3D visualization library
- **Flask & Socket.IO**: Real-time web framework
- **PySide6**: Qt6 Python bindings
- **Anthropic**: Claude Code AI coding assistant

---

## πŸ’¬ Reflections on AI-Assisted Development

This project demonstrates that LLMs can build **production-quality software** when given proper guidance. But it's not magicβ€”it's collaboration.

**What surprised us**:
- How quickly complex features came together with good prompts
- The importance of incremental development (don't skip phases!)
- How much human judgment matters for architecture and UX
- That AI-generated code can meet professional quality standards

**What we'd do differently**:
- Start with even more research on cube mechanics
- Build a test suite *before* implementing features
- Document architectural decisions as we make them
- Create a git branching strategy earlier

**The bottom line**: AI coding assistants are powerful tools that amplify human developers, not replace them. The human provides vision, judgment, and direction. The AI provides implementation speed, consistency, and tireless iteration.

---

**Built through conversation between** 🧠 Human Guidance + πŸ€– Claude Code

*Want to see the complete development conversation? Check out [conversation_summary/](conversation_summary/)*