Skip to content

Repository files navigation

Brilliant Movee

Brilliant Movee is a high-performance, premium chess analysis application built with Flutter. It integrates world-class technology with an industrial-grade "Obsidian" design system to provide chess players with an unvarnished, high-impact environment for study and evolution.


1. Vision & Core Pillars

Brilliant Movee is not just a replay tool. It is a structured wisdom system. By combining live Stockfish engine metrics, seamless Chess.com data integration, and a curated philosophical manual, the application aims to shift the user's tactical and psychological mindset.

1. High-Performance Analysis

  • Integrated Stockfish Bridge: Real-time evaluation via high-level engine profiles (Stockfish 16 through 20).
  • Advanced Move Classification: Automated detection of Brilliant, Great, Best, Book, Excellent, Good, Inaccuracy, Mistake, Blunder, and Miss moves using proprietary sensitivity logic.
  • Deep Neural Networks: Support for full NNUE networks (~78MB) for Grandmaster-level accuracy on mobile and desktop.
  • Multi-Line Evaluation: Dynamic Multi-PV analysis to explore complex tactical branches simultaneously.

2. Seamless Data Integration

  • Chess.com Synchronization: Direct import of game history using Chess.com public APIs.
  • PGN Processing: Robust parser for importing external games and managing metadata.
  • Game Persistence: Local storage of reviewed games for offline study and comparison.

3. The Restricted Manual (Stoic Wisdom)

  • Philosophical Directives: A curated database of ~100 high-intensity lessons categorized into industrial pillars (Dominance, Unshakeable, The Void, etc.).
  • Psychological Fortification: Content designed to challenge the user's current mindset and build an "Inner Citadel."
  • HD Visuals: 4K visual covers and active data engines for financial and character-driven lessons.

4. Technical Strategy (Openings & Tips)

  • Opening Explorer: Detailed breakdown of the top 50 chess openings with black-and-white illustrator-style visuals.
  • Author Profiles: Historical context for each line, featuring the grandmasters and theorists who pioneered them.
  • Tactical Encyclopedia: Categorized tips for opening concepts, middle-game positioning, and endgame conversion.

2. Technical Architecture & File Structure

The project is built on a "Feature-First" modular architecture, ensuring scalability, code isolation, and clean state management.

  • Framework: Flutter 3.22+ and Dart 3.4+
  • State Management: Flutter Riverpod (StateNotifier and Provider families)
  • Navigation: GoRouter with StatefulShellRoute (IndexedStack) for immersive tab transitions.
  • Storage: SharedPreferences for settings and Hive/JSON for local content databases.
  • Theme: Material 3 implementation of the "Obsidian" high-contrast system (Pure Black #000000 / Arctic White #FFFFFF with custom Purple accents).
  • Fonts: Consolidated StackSansNotch (English) and GoogleSans (Khmer).
  • Responsive Layout: Adaptive shell optimizing viewports for Mobile, Tablet, and Desktop via a custom ResponsiveContainer.

Codebase Organization

lib/
├── main.dart                       # App entry point, initializes Services (SharedPreferences, Audio, Asset)
├── app.dart                        # Wires MaterialApp.router, themes, and shell routes
├── core/
│   ├── router/                     # App router setup with GoRouter (tabs and standalone screens)
│   ├── theme/                      # AppTheme custom definition (Obsidian pure black system colors)
│   └── services/                   # StorageService, AudioService, RecordingService, AssetService
├── data/
│   ├── sources/                    # ChessComApi handling HTTP calls to Chess.com
│   └── repositories/               # PlayerRepository, GameRepository interfacing sources with UI
├── engine/
│   ├── models/                     # UCI commands, move quality types, board state models
│   ├── pipeline/                   # Analysis pipeline orchestrating engine passes
│   ├── runtime/                    # EngineIsolateV2 handling real UCI communication with Stockfish binary
│   ├── move_classifier.dart        # Sensitivity thresholds comparing actual played moves against Stockfish's top engine evaluations
│   ├── opening_book.dart           # Auto-generated database mapping chess positions to opening names/historical tags
│   ├── pgn_parser.dart             # Parsers translating chess notation files (PGN) into active Move objects
│   └── stockfish_isolate.dart      # Dispatches engine tasks away from the main UI thread (falls back to mock async engine on web targets)
└── features/
    ├── home/                       # Leaderboard dashboard showcasing elite players (defaults to Rapid matches)
    ├── history/                    # Real-time player history syncing with Chess.com
    ├── profile/                    # User analytics, custom stats, and "Chess.com Insights" styling breakdown
    ├── review/                     # Interactive chessboard, move notations, move classification markers, and video export
    ├── stoic/                      # Psychological Manual with responsive grid cards and text detail pages
    └── settings/                   # Local configurations for board styles, piece packages, sounds, and active Stockfish engine levels

3. How the Core Engine & Pipeline Works

The Local Stockfish Bridge and Isolates

To avoid blocking the UI thread during heavy calculations, Brilliant Movee executes chess engine calculations within a Dart Isolate:

  1. EngineIsolateV2 manages the spawn-lifecycle of the binary executable.
  2. It sets up unidirectional ReceivePort and SendPort streams.
  3. Communications use standard UCI (Universal Chess Interface) protocols:
    • Main isolate sends: position fen ... followed by go depth 22.
    • Stockfish returns lines starting with info depth X score cp Y pv ....
  4. On web builds where binary processes are blocked, the engine falls back to simulated async analysis to preserve page responsiveness.

Game Parsing and Review Flow

[PGN String]
     ↓
[PgnParser] → Outputs raw Move records (SAN, target squares, annotations)
     ↓
[BoardStateBuilder] → Iterates moves and builds coordinate/piece matrix for each ply
     ↓
[StockfishIsolate] → Runs in background to find best/alternative lines (Depth 22+)
     ↓
[MoveClassifier] → Rates moves (Brilliant, Great, Best, Book, Good, Inaccuracy, Mistake, Blunder)
     ↓
[ReviewNotifier] → Riverpod state holder feeding UI, play move sounds, and updates persistence

Move Classification Logic

The quality of each move is determined in lib/engine/move_classifier.dart by comparing the evaluation score (in centipawns or mate-in-N values) of the move actually played versus the best possible move returned by Stockfish:

  • Book: Matches known openings stored in lib/engine/opening_book.dart.
  • Best: Identical to the #1 engine recommended move.
  • Brilliant: A sacrifice or complex move that does not drop evaluation but rather secures/increases tactical dominance, validated through sensitivity parameters.
  • Great: A singular winning move that is difficult to locate.
  • Blunder: A mistake dropping the game evaluation dramatically (usually >2.0 centipawn drop).

4. Complete System Architecture & Data Flowcharts

Below are the key flowcharts detailing how the app processes actions, analyses, and assets.

1. General System Flow

graph TD
    Start([User Launches Application]) --> CheckAuth{User Authenticated}
    CheckAuth -->|No| AuthFlow[Chess.com OAuth Flow]
    AuthFlow --> StoreCredentials[Store Encrypted Credentials]
    StoreCredentials --> MainDashboard
    CheckAuth -->|Yes| MainDashboard[Display Main Dashboard]
    
    MainDashboard --> UserChoice{User Action}
    
    UserChoice -->|Browse Games| HistoryFlow[Navigate to Game History]
    UserChoice -->|View Profile| ProfileFlow[View Performance Dashboard]
    UserChoice -->|Search Player| SearchFlow[Global Leaderboard Search]
    UserChoice -->|Analyze Game| ReviewFlow[Game Analysis]
    
    HistoryFlow --> FetchGames[Fetch Game Data from Chess.com API]
    FetchGames --> ParseGames[Parse Game Metadata]
    ParseGames --> CacheGames[Store in Local Cache]
    CacheGames --> DisplayList[Display Game List with Filters]
    DisplayList --> SelectGame{User Selects Game}
    SelectGame -->|Select| ReviewFlow
    SelectGame -->|Back| MainDashboard
    
    ProfileFlow --> FetchStats[Fetch Player Statistics]
    FetchStats --> CalculateMetrics[Calculate Performance Metrics]
    CalculateMetrics --> DisplayProfile[Render Analytics Dashboard]
    DisplayProfile --> BackProfile{User Action}
    BackProfile -->|Back| MainDashboard
    BackProfile -->|View Game| HistoryFlow
    
    SearchFlow --> InputSearch[User Enters Player Name]
    InputSearch --> QueryAPI[Query Chess.com Rankings API]
    QueryAPI --> DisplayResults[Show Player Rankings]
    DisplayResults --> SelectPlayer{Select Player}
    SelectPlayer -->|View| ProfileFlow
    SelectPlayer -->|Back| MainDashboard
    
    ReviewFlow --> LoadPGN[Load Game PGN Notation]
    LoadPGN --> ParsePGN[Parse PGN into Moves]
    ParsePGN --> BuildBoardStates[Generate Board States for Each Move]
    BuildBoardStates --> InitEngine[Initialize Chess Engine]
    InitEngine --> EngineReady{Engine Ready}
    
    EngineReady -->|Ready| StartAnalysis[Begin Position Analysis]
    EngineReady -->|Error| EngineError[Display Engine Error]
    EngineError --> ReviewFlow
    
    StartAnalysis --> AnalysisLoop{Process All Moves}
    AnalysisLoop -->|Remaining Moves| GetPosition[Get Next Position]
    GetPosition --> AnalyzePosition[Analyze Position with Engine]
    AnalyzePosition --> GetEvaluation[Retrieve Engine Evaluation]
    GetEvaluation --> CalculateDepth[Analyze at Depth 22+]
    CalculateDepth --> GetBestMove[Determine Best Move]
    GetBestMove --> CompareActual[Compare with Actual Move]
    CompareActual --> ClassifyMove[Classify Move Quality]
    ClassifyMove --> StoreEvaluation[Store Position Evaluation]
    StoreEvaluation --> AnalysisLoop
    
    AnalysisLoop -->|All Done| GenerateCoaching[Generate AI Coaching Text]
    GenerateCoaching --> CreateVariations[Create Alternative Variations]
    CreateVariations --> RenderBoard[Render Interactive Analysis Board]
    RenderBoard --> DisplayAnalysis[Display Move-by-Move Analysis]
    DisplayAnalysis --> UserAnalysisChoice{User Action}
    
    UserAnalysisChoice -->|Explore Move| ExploreVariation[Show Alternative Lines]
    ExploreVariation --> DisplayAnalysis
    
    UserAnalysisChoice -->|View Stats| MoveStats[Display Move Classification Stats]
    MoveStats --> DisplayAnalysis
    
    UserAnalysisChoice -->|Export Video| VideoExport[Prepare Video Export]
    VideoExport --> RenderFrames[Render Board Frames]
    RenderFrames --> EncodeVideo[Encode Video File]
    EncodeVideo --> ExportOptions{Export Format}
    ExportOptions -->|Social Media| PrepareShare[Format for Social Media]
    ExportOptions -->|Local Save| SaveFile[Save to Device Storage]
    PrepareShare --> UploadPrompt[Prompt User to Share]
    SaveFile --> ExportComplete[Export Complete]
    UploadPrompt --> ExportComplete
    ExportComplete --> DisplayAnalysis
    
    UserAnalysisChoice -->|Back| MainDashboard
    
    MainDashboard --> End([Session End])
Loading

2. Move Analysis Process

graph TD
    Start([Start Game Analysis]) --> Fetch[Fetch Game from Chess.com]
    Fetch --> Validate{Valid Game Data}
    Validate -->|Invalid| Error[Display Error Message]
    Error --> End([Analysis Failed])
    
    Validate -->|Valid| GetPGN[Download Game PGN]
    GetPGN --> ParsePGN[Parse PGN Notation]
    ParsePGN --> Extract[Extract Moves and Metadata]
    Extract --> CreateBoard[Initialize Chess Board]
    CreateBoard --> BuildStates[Generate Board State for Each Move]
    
    BuildStates --> EngineInit[Initialize Chess Engine Process]
    EngineInit --> CheckEngine{Engine Available}
    CheckEngine -->|Not Available| LoadEngine[Download Engine Binary]
    LoadEngine --> ConfigEngine[Configure Engine Settings]
    ConfigEngine --> EngineReady[Engine Ready]
    CheckEngine -->|Available| EngineReady
    
    EngineReady --> MoveAnalysis[Start Move Analysis Loop]
    MoveAnalysis --> MoveCounter[Initialize Move Counter]
    MoveCounter --> NextMove{More Moves to Analyze}
    
    NextMove -->|Yes| FetchPosition[Get Next Board Position]
    FetchPosition --> StockfishAnalyze[Analyze with Stockfish]
    StockfishAnalyze --> GetEval[Retrieve Position Evaluation]
    GetEval --> BestMove[Calculate Best Move]
    BestMove --> ActualMove[Get Actual Move Played]
    
    ActualMove --> Comparison{Compare Best vs Actual}
    Comparison -->|Same Move| Rating1[Excellent Move]
    Comparison -->|Within 0.5| Rating2[Good Move]
    Comparison -->|Within 2.0| Rating3[Questionable Move]
    Comparison -->|Greater 2.0| Rating4[Blunder]
    
    Rating1 --> StoreRating[Store Move Classification]
    Rating2 --> StoreRating
    Rating3 --> StoreRating
    Rating4 --> StoreRating
    
    StoreRating --> GenerateNotes[Generate AI Coaching Notes]
    GenerateNotes --> CalculateVariations[Calculate Alternative Lines]
    CalculateVariations --> StoreMoveData[Store Complete Move Data]
    StoreMoveData --> IncrementCounter[Move Counter Plus One]
    IncrementCounter --> NextMove
    
    NextMove -->|No| CompileStats[Compile Game Statistics]
    CompileStats --> CalcAccuracy[Calculate Overall Accuracy]
    CalcAccuracy --> CalcStrongest[Identify Strongest Moves]
    CalcStrongest --> CalcWeakest[Identify Weakest Moves]
    CalcWeakest --> CreateSummary[Create Game Summary Report]
    CreateSummary --> RenderDisplay[Render Analysis Display]
    RenderDisplay --> Success([Analysis Complete])
Loading

3. Engine Deep Dive

graph TD
    Start([Engine Analysis Request]) --> IsEngine{Engine Running}
    IsEngine -->|No| StartEngine[Start Engine Process]
    StartEngine --> ConfigEngine[Configure Depth and Time]
    ConfigEngine --> EngineRunning[Engine Process Running]
    IsEngine -->|Yes| EngineRunning
    
    EngineRunning --> Setup[Setup Analysis Parameters]
    Setup --> SetDepth[Set Analysis Depth 22+]
    SetDepth --> SetTime[Set Max Time Allocation]
    SetTime --> SetThreads[Configure Thread Count]
    SetThreads --> SendPosition[Send Position to Engine]
    
    SendPosition --> Engine[Chess Engine Processing]
    Engine --> Analyze[Begin Position Evaluation]
    Analyze --> TreeSearch[Search Move Tree]
    TreeSearch --> CalculateEvals[Calculate Position Evaluations]
    CalculateEvals --> FindBest[Find Best Move Line]
    FindBest --> GetVariations[Extract Top 3-5 Variations]
    GetVariations --> ProcessingComplete[Processing Complete]
    
    ProcessingComplete --> Results[Retrieve Results]
    Results --> Evaluation[Get Primary Evaluation]
    Evaluation --> BestMoveLine[Get Best Move Line]
    BestMoveLine --> Variations[Get Alternative Variations]
    Variations --> CheckMate{Check for Checkmate}
    
    CheckMate -->|Mate Found| MateInfo[Extract Mate in N]
    MateInfo --> ReturnMate[Return Mate Information]
    CheckMate -->|No Mate| ReturnEval[Return Normal Evaluation]
    
    ReturnMate --> Cache[Cache Results]
    ReturnEval --> Cache
    Cache --> Return[Return to Analysis Module]
    Return --> End([Analysis Complete])
Loading

4. Data Flow Architecture

graph LR
    User[User Input] --> UI[Flutter UI Layer]
    UI --> StateMan[State Management Layer]
    StateMan --> BizLogic[Business Logic Layer]
    BizLogic --> Repo[Repository Pattern]
    
    Repo --> LocalCache[(Local Cache Database)]
    Repo --> ChessAPI[Chess.com API Service]
    Repo --> EngineService[Engine Service]
    
    ChessAPI --> ChessNet[Network Layer]
    ChessNet --> ChessServer[Chess.com Servers]
    
    EngineService --> PGNParser[PGN Parser]
    EngineService --> BoardState[Board State Manager]
    EngineService --> Stockfish[Stockfish Engine]
    
    LocalCache --> StoredData[(Persistent Storage)]
    
    PGNParser --> Moves[Move Sequence]
    BoardState --> Positions[Board Positions]
    Moves --> Engine[Engine Input]
    Positions --> Engine
    Stockfish --> Analysis[Analysis Results]
    
    Analysis --> Classifier[Move Classifier]
    Classifier --> NLP[Natural Language Generator]
    NLP --> UI
    StoredData --> UI
Loading

5. Video Export Pipeline

graph TD
    Start([Initiate Video Export]) --> CheckSpace{Disk Space Available}
    CheckSpace -->|No| DiskError[Display Storage Error]
    DiskError --> End1([Export Failed])
    CheckSpace -->|Yes| GetConfig[Get Export Configuration]
    
    GetConfig --> SelectFormat{Video Format}
    SelectFormat -->|4:3| Set43[Set 4:3 Aspect Ratio]
    SelectFormat -->|16:9| Set169[Set 16:9 Aspect Ratio]
    SelectFormat -->|9:16| Set916[Set 9:16 Portrait]
    
    Set43 --> SetCodec[Set Codec Parameters]
    Set169 --> SetCodec
    Set916 --> SetCodec
    
    SetCodec --> SetResolution[Set Output Resolution]
    SetResolution --> SetFPS[Set Frame Rate 30 FPS]
    SetFPS --> SetBitrate[Set Bitrate 5 Mbps]
    SetBitrate --> CreateTemp[Create Temporary Directory]
    
    CreateTemp --> GetMoves[Get Analysis Moves]
    GetMoves --> MoveFrames[Render Move Display Frames]
    MoveFrames --> EvalFrames[Render Evaluation Frames]
    EvalFrames --> BoardFrames[Render Board State Frames]
    BoardFrames --> AddAnnotations[Add Move Annotations]
    AddAnnotations --> FrameQueue[Queue Frames for Encoding]
    
    FrameQueue --> EncodeStart[Start Video Encoding]
    EncodeStart --> ProcessFrames{Process All Frames}
    ProcessFrames -->|More Frames| EncodeFrame[Encode Frame]
    EncodeFrame --> WriteFrame[Write to Video File]
    WriteFrame --> ProcessFrames
    
    ProcessFrames -->|Complete| AddAudio[Add Audio Commentary]
    AddAudio --> AddSubtitles[Add Move Notation Subtitles]
    AddSubtitles --> Finalize[Finalize Video File]
    Finalize --> MoveToOutput[Move to Output Directory]
    
    MoveToOutput --> SelectDest{Select Destination}
    SelectDest -->|Device| SaveDevice[Save to Device Storage]
    SelectDest -->|Share| ShareOptions[Show Share Options]
    SelectDest -->|Social| PrepareShare[Format for Social Media]
    
    SaveDevice --> Success[Video Saved]
    ShareOptions --> Launch[Launch Share Dialog]
    Launch --> Success
    PrepareShare --> Social[Prepare for Upload]
    Social --> Success
    
    Success --> End2([Export Complete])
Loading

5. Recent System Enhancements

A set of premium features have been integrated to improve both performance and presentation:

Defaulting to Rapid Rankings

The Home screen global leaderboard now defaults to Rapid category lists.

  • User cards feature custom ranking icons and scores.
  • Connected player profiles (specifically highlighting the user shiliaiwei) are dynamically highlighted in the list with a professional teal glow.

Chess.com "Insights" Profile Section

Redesigned to resemble the premium "Chess.com Insights" aesthetic.

  • Shows custom classifications (Brilliant, Great, Best, Book, etc.) alongside direct counts.
  • Standardized 10 local classification icons loaded from assets/classification/ replace standard Material icons on both the review board and profile insights for high-fidelity presentation.
  • Incorporates tap animations giving user cards and metric containers a responsive Scale feedback effect.

Real-Time Updates & Manual Pull-to-Refresh

  • Implemented manual pull-to-refresh capabilities in history_screen.dart via RefreshIndicator and a top AppBar refresh button to force fresh data fetching from Chess.com (bypassing outdated local caches).
  • Games menu icon updated to Icons.sports_esports_rounded for a modern look.

6. Build and Deployment

Getting Started

  1. Install Flutter SDK (3.22.0 or newer).
  2. Fetch project packages:
    flutter pub get
  3. Generate serializable models and assets:
    dart run build_runner build
  4. If you update opening definitions, regenerate the database:
    python3 assets_prepare/gen_openings.py

Compile Targets

  • Android APK:
    flutter build apk --release --split-per-abi
  • Web Target:
    flutter build web --release --base-href /
  • Desktop Releases:
    • MacOS: flutter build macos
    • Windows: flutter build windows

About

Analyze. Learn. Evolve. A Flutter/Dart chess app that syncs Chess.com games, runs Stockfish analysis, and teaches you both tactics and mental fortification.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages