Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- PROJECT SUMMARY
- --------------------------------------------------------------------------------
- Total Files: 2,798
- Total Lines of Code: 871,605
- - Config: 21,753 (2.5%)
- - Docs: 433,639 (49.8%)
- - Source: 121,209 (13.9%)
- - Tests: 272,065 (31.2%)
- - Tooling: 22,846 (2.6%)
- - Unclassified: 93 (0.0%)
- # Part 1: Project Overview & Architecture
- **Source Document:** `TECHNICAL_OVERVIEW_2026-01-14.md`
- **Document Version:** 3.0
- **Sections:** 1, 2, 3, 4
- **Last Updated:** January 16, 2026
- ---
- **Purpose:** Answers "What is this project and how is it structured?"
- **Related Parts:**
- - Part 2: Quality, Testing & Development (how we maintain quality)
- - Part 3: Game Systems & Combat (how mechanics work)
- - Part 4: Features & Implementations (notable implementations)
- ---
- ## 1. Project Classification
- | Attribute | Value |
- |-----------|-------|
- | **Type** | Full-stack web-based turn-based strategy game |
- | **Primary Language** | TypeScript (strict mode) |
- | **Architecture** | Domain-Driven Design with clean architecture layers |
- ---
- ## 2. Technology Stack
- ### 2.1 Backend
- | Category | Technology | Version |
- |----------|------------|---------|
- | **Runtime** | Node.js | >=20.0.0 |
- | **Language** | TypeScript | 5.9.2 |
- | **Framework** | Express.js | 5.1 |
- | **Database** | Supabase Local (PostgreSQL) | Docker-based |
- | **ORM** | Prisma | 6.16.0 |
- | **Validation** | Zod | 3.25 |
- | **Dependency Injection** | TSyringe | 4.10 |
- | **Logging** | Winston | 3.17 |
- | **Real-time** | Socket.IO | 4.8 |
- | **Authentication** | JWT (jsonwebtoken) | 9.0 |
- | **Password Hashing** | bcrypt | 6.0 |
- > **Database Strategy:** Supabase Local (Docker PostgreSQL) for development/testing - production parity, parallel test workers, database-per-worker isolation. Production uses Supabase Cloud (PostgreSQL). Schema identical across environments.
- ### 2.2 Frontend
- | Category | Technology | Version |
- |----------|------------|---------|
- | **Framework** | Next.js | 15.5 |
- | **UI Library** | React | 18.3 |
- | **Build Tool** | Turbopack | (Next.js native) |
- | **State Management** | React hooks + SWR | 2.3 |
- | **Styling** | Bootstrap | 5.3 |
- | **Animation** | Framer Motion | 12.23 |
- | **Skeletal Animation** | Spine WebGL (spine-webgl runtime) | 4.2 |
- | **VFX Rendering** | Raw WebGL (OpenGL ES 2.0, no framework) | - |
- | **Tooltips/Dialogs** | Radix UI | 1.x-2.x |
- | **Drag & Drop** | DND Kit | 6.3 |
- | **Notifications** | React Hot Toast | 2.6 |
- | **Charts** | Recharts | 3.1 |
- > **Rendering Architecture:** All battlefield rendering uses raw WebGL (OpenGL ES 2.0) with hand-written GLSL shaders - no Pixi.js, no Three.js, no game engine. Spine runtime provides skeletal animation; custom WebGL infrastructure handles effects, projectiles, and ground glows. Single shared WebGL context for maximum GPU efficiency.
- ### 2.3 Testing & Quality
- | Category | Technology | Version |
- |----------|------------|---------|
- | **Test Runner** | Jest | 29.7 |
- | **Component Testing** | @testing-library/react | 16.3 |
- | **E2E Testing** | Playwright | 1.56 |
- | **HTTP Testing** | Supertest | 7.1 |
- | **Linting** | ESLint | 9.38 |
- | **Type Checking** | TypeScript strict mode | - |
- | **Quality Gates** | Custom AST-based violation detection | - |
- ---
- ## 3. Architecture
- ### 3.1 Backend Structure
- ```
- src/
- ├── contracts/ # API contracts (Zod schemas)
- ├── core/
- │ └── data/ # 25 JSON game data files
- │ ├── items.json # 25+ equipment templates
- │ ├── spells.json # Spell definitions + effects
- │ ├── character-classes.json # 5 classes with tier scaling
- │ ├── creatures.json # Enemy creature definitions
- │ ├── effects.json # DoT/CC effect definitions
- │ ├── globals.json # Combat constants
- │ ├── traits.json # Passive ability definitions
- │ ├── row-orbs.json # Row orb configuration
- │ ├── upgrade-config.json # Item/spell upgrade rates
- │ ├── loot-tables.json # Drop tables
- │ ├── league-rewards.json # League reward tiers
- │ ├── league-defaults.json # League configuration defaults
- │ ├── xp-rewards.json # XP reward tables
- │ ├── speed-mechanics.json # Queue jump thresholds
- │ ├── item-level-scaling.json # Item stat scaling
- │ └── test-*.json # Test data variants
- ├── domain/ # Domain layer (DDD)
- │ ├── entities/ # 11 core entities
- │ │ ├── character.ts # Character + activeEffects[]
- │ │ ├── squad.ts # Squad container
- │ │ ├── battle.ts # Battle + snapshots
- │ │ ├── item.ts # Item entity
- │ │ ├── user.ts # User entity
- │ │ └── league/ # League-specific entities
- │ │ ├── league.ts # League entity
- │ │ ├── league-match.ts # Match with snapshots
- │ │ ├── league-season.ts # Season configuration
- │ │ ├── league-standings.ts
- │ │ ├── league-participant.ts
- │ │ └── league-invite.ts
- │ ├── services/
- │ │ ├── battle-simulator/ # Core game logic (16 subsystems)
- │ │ │ ├── attack/ # Attack execution pipeline
- │ │ │ │ └── phases/ # 5-phase attack resolution (ActionResolver → HitResolver → DamageResolver → EffectResolver → EventBuilder)
- │ │ │ ├── damage/ # Physical, Spell, Elemental, Crit calculators
- │ │ │ ├── effects/ # StatusEffectSystem, DotProcessor
- │ │ │ ├── evasion/ # EvasionCheckSystem
- │ │ │ ├── finalization/ # BattleFinalizationSystem
- │ │ │ ├── initiative/ # InitiativeSystem (turn queue by speed)
- │ │ │ ├── logging/ # VerboseLogger
- │ │ │ ├── orbs/ # RowOrbSystem (flat + percent bonuses)
- │ │ │ ├── positioning/ # GridPositionManager (2x4 grid)
- │ │ │ ├── queue/ # QueueJumpSystem (speed-based extra turns)
- │ │ │ ├── randomness/ # BattleRNG (seeded determinism)
- │ │ │ ├── regeneration/ # ManaRegenerationSystem
- │ │ │ ├── spells/ # WizardSpellSystem, Chain Lightning
- │ │ │ ├── stats/ # StatModifierBucket (unified stacking)
- │ │ │ ├── targeting/ # ThreatCalculator, BlockingSystem, ChainTargeting
- │ │ │ └── traits/ # TraitSystem + handlers
- │ │ │ ├── TraitSystem.ts
- │ │ │ ├── TraitLoader.ts
- │ │ │ ├── TargetResolver.ts
- │ │ │ ├── handlers/ # StatModifierHandler
- │ │ │ └── trait-schema.ts
- │ │ ├── league/ # League domain services
- │ │ │ ├── core/ # Rules validation, eligibility
- │ │ │ ├── execution/ # Match executor, formation snapshots
- │ │ │ ├── lifecycle/ # Season transitions, end detection
- │ │ │ ├── scheduling/ # Round-robin, timezone handling
- │ │ │ └── scoring/ # Standings, tiebreakers, winner determination
- │ │ ├── xp/ # XP breakpoint interpolation
- │ │ └── elemental-damage-reduction-service.ts
- │ ├── types/ # TypeScript interfaces
- │ │ ├── character-types.ts
- │ │ ├── element-types.ts
- │ │ └── league-types.ts
- │ └── values/ # Value objects
- │ └── combat-value.ts # CombatValue (base + bonuses)
- ├── infrastructure/ # Infrastructure layer
- │ ├── prisma/ # Database client
- │ │ ├── prisma-transaction-context.ts # AsyncLocalStorage propagation
- │ │ └── prisma-error-handler.ts
- │ └── repositories/ # 16+ repositories (BaseRepository)
- │ ├── base-repository.ts
- │ ├── item-repository.ts
- │ └── league/ # League-specific repositories
- ├── services/ # Application services (100+)
- │ ├── auth-service.ts # Authentication
- │ ├── combat-service-helpers/ # Combat orchestration
- │ │ ├── shared/ # Test helpers
- │ │ └── verification/ # Test isolation, cleanup
- │ ├── game-data/ # GameDataService + calculators
- │ │ ├── calculators/ # Character stats, XP, spell level
- │ │ ├── loaders/ # JSON loaders + file watcher
- │ │ ├── providers/ # Items, spells, class-stats, rules, threat-config
- │ │ ├── schemas/ # Zod validation schemas
- │ │ ├── tier-calculator.ts # Tier determination
- │ │ ├── item-stat-calculator.ts
- │ │ └── creature-skin-resolver.ts
- │ ├── league/ # League application services
- │ │ ├── league-application-service.ts
- │ │ ├── league-lifecycle-service.ts
- │ │ ├── league-participation-service.ts
- │ │ ├── league-standings-service.ts
- │ │ ├── league-invite-service.ts
- │ │ ├── league-search-service.ts
- │ │ ├── league-notification-service.ts
- │ │ ├── league-scheduler-orchestrator.ts
- │ │ ├── mailbox-service.ts
- │ │ └── chat-service.ts
- │ ├── xp/ # XP distribution services
- │ │ ├── xp-distribution-service.ts
- │ │ ├── xp-reward-calculator.ts
- │ │ ├── squad-xp-calculator.ts
- │ │ ├── token-distribution-service.ts
- │ │ └── level-gap-penalty-calculator.ts
- │ ├── interactive-battle/ # Live battle system (real-time PvP)
- │ │ ├── battle-session.ts # Single battle instance state
- │ │ ├── battle-session-manager.ts # Active session tracking
- │ │ ├── challenge-service.ts # Challenge create/accept flow
- │ │ ├── battle-state-initializer.ts # Formation → BattleState
- │ │ └── engine-state-sync.ts # Engine ↔ WebSocket sync
- │ ├── evasion-scaling-service.ts
- │ └── physical-damage-reduction-service.ts
- ├── web/ # HTTP layer
- │ ├── routes/ # 30+ API route files
- │ │ ├── auth-routes.ts
- │ │ ├── combat-routes.ts
- │ │ ├── equipment-routes.ts
- │ │ ├── game-data-routes.ts
- │ │ ├── squad-routes.ts
- │ │ ├── upgrade-routes.ts
- │ │ ├── xp-routes.ts
- │ │ ├── dev/ # Developer tools
- │ │ │ └── balance-tool-routes.ts
- │ │ ├── equipment/ # Equipment helpers + mappers
- │ │ └── league/ # League routes (7 files)
- │ ├── middleware/ # Auth, developer mode
- │ ├── validation/ # Request validation
- │ └── websocket/ # Real-time gateways
- │ ├── chat-gateway.ts # League chat WebSocket
- │ └── battle-gateway.ts # Live battle WebSocket (Socket.IO)
- ├── flows/ # Business workflows
- ├── jobs/ # Background job handlers
- │ └── league/ # Match scheduling, standings, season detection
- ├── monitoring/ # Observability utilities
- │ ├── performance-tracker.ts
- │ ├── fallback-detector.ts
- │ └── alert-manager.ts
- └── utils/ # Shared utilities
- ├── jwt.ts
- ├── errors.ts
- ├── async-handler.ts
- ├── database-check.ts
- └── logger.ts
- ```
- ### 3.2 Frontend Structure
- ```
- frontend/src/
- ├── app/ # Next.js 15 app router (35+ pages)
- │ ├── api/ # API routes (Next.js)
- │ ├── battlefield/[battleId]/ # Battle replay visualization
- │ ├── battle/ # Live battle system
- │ │ └── live/[sessionId]/ # Real-time PvP battle page
- │ ├── combat/ # Combat system
- │ │ ├── challenge/ # Instant battle setup
- │ │ ├── history/ # Battle history
- │ │ ├── live-challenge/ # Live PvP challenge lobby
- │ │ │ └── pending/ # Pending challenge invitations
- │ │ ├── live-setup/[challengeId]/ # Live battle pre-match setup
- │ │ ├── result/[battleId]/ # Battle results
- │ │ └── setup/[opponentSquadId]/ # Pre-battle configuration
- │ ├── dashboard/ # Main dashboard
- │ ├── dev/ # Developer tools
- │ │ ├── balance-tool/ # JSON balance editor
- │ │ ├── workbench/ # Stat preview workbench
- │ │ └── test-rotate-prompt/ # Mobile rotation testing
- │ ├── equipment-prototype/ # Equipment management
- │ ├── leagues/ # League system
- │ │ ├── new/ # Create league
- │ │ ├── invites/ # League invitations
- │ │ ├── formation/[matchId]/ # Formation editor (legacy)
- │ │ ├── formation-v2/ # Formation editor v2
- │ │ │ ├── demo/
- │ │ │ └── [matchId]/
- │ │ └── [id]/ # League detail pages
- │ │ ├── standings/
- │ │ ├── matches/
- │ │ ├── history/
- │ │ ├── invite/
- │ │ ├── join/
- │ │ └── home-prototype/
- │ ├── squads/ # Squad management
- │ │ ├── new/
- │ │ └── [id]/equipment/
- │ ├── treasure-chamber/[squadId]/ # Inventory/loot management
- │ ├── login/ # Authentication
- │ └── register/
- ├── components/
- │ ├── allocation/ # Stat allocation UI
- │ ├── balance-tool/ # Balance editor components
- │ ├── battle/ # Battle UI components
- │ │ ├── BattleReplayControls/ # Playback controls
- │ │ ├── TurnOrderDisplay/ # Turn queue display
- │ │ ├── TacticalGrid/ # Formation grid
- │ │ ├── CharacterCard/ # Character display
- │ │ ├── BattleHeader/ # Battle info header
- │ │ └── BattleActions/ # Action buttons
- │ ├── battlefield/ # Battlefield rendering (30+ subdirectories)
- │ │ ├── AnimationController/ # Animation state machine
- │ │ ├── animations/ # Character animation definitions
- │ │ │ └── characters/ # Wizard, Knight, etc.
- │ │ ├── BattlefieldCore/ # Main canvas component (replay mode)
- │ │ ├── InteractiveBattlefieldCore/ # Interactive battle cards/UI wrapper
- │ │ ├── LiveBattlefieldCore/ # Live battle canvas (real-time PvP)
- │ │ │ ├── LiveBattlefieldCore.tsx # Main live battle renderer
- │ │ │ └── LiveTurnOrderDisplay.tsx # Real-time turn queue
- │ │ ├── BattlefieldOverlay/ # SVG overlay (HP bars, damage, status)
- │ │ ├── BattlefieldRotatePrompt/ # Mobile rotation prompt
- │ │ ├── CompactTurnOrder/ # Mobile turn order display
- │ │ ├── DamageNumber/ # Floating damage text
- │ │ ├── effect-parsers/ # Battle log effect parsers
- │ │ ├── effects/ # Raw WebGL effects system
- │ │ │ ├── core/ # WebGLEffectsContext, ShaderManager, BufferPool, TextureManager
- │ │ │ ├── renderers/ # Particle, Sprite, Line, GroundGlow, Shockwave renderers
- │ │ │ ├── systems/ # EffectsManager, ParticleSystem, ProjectileSystem, MeshEffectSystem
- │ │ │ │ └── helpers/ # FBOManager, CrosshairOverlay, QueueJumpEffects, GroundGlowManager
- │ │ │ ├── mesh/ # MeshDataExtractor, ScalingCalculator, LODCalculator, BoneTracking
- │ │ │ ├── orbit/ # ParametricPathCalculator, OrbitPresets, WaveformFunctions, NoiseGenerator
- │ │ │ ├── configs/ # Effect profiles, mesh archetypes, particle/projectile/lightning configs
- │ │ │ ├── utils/ # particle-textures, color-palettes, scale-config, coordinate-transform
- │ │ │ └── shaders/ # GLSL shaders (particle, sprite, line, ground-glow, shockwave)
- │ │ ├── FPSMeter/ # Performance display
- │ │ ├── hooks/ # Battlefield-specific hooks
- │ │ │ ├── useBattleReplayAnimations.ts # Replay mode animation coordinator
- │ │ │ └── useLiveBattleAnimations.ts # Live battle animation + HP sync
- │ │ ├── HPBar/ # Health bar component
- │ │ ├── layouts/ # Battlefield layout variants
- │ │ ├── ManaBar/ # Mana display
- │ │ ├── MobileControlsBar/ # Touch controls
- │ │ ├── QueueJumpText/ # Queue jump announcements
- │ │ ├── ResistanceBadge/ # Elemental resistance display
- │ │ ├── spell-handlers/ # Per-spell animation handlers
- │ │ ├── SpineAnimationController/ # Spine animation coordination
- │ │ ├── SpineErrorBoundary/ # Animation error handling
- │ │ ├── SpineRenderer/ # WebGL Spine rendering
- │ │ ├── SpriteRenderer/ # CSS sprite rendering
- │ │ ├── StatBreakdownPanel/ # Arcane Insight debug overlay
- │ │ ├── StunStatusBadge/ # Stun indicator
- │ │ ├── BurnStatusBadge/ # Burn indicator
- │ │ ├── TurnOrderDisplay/ # Turn queue with queue jump animations
- │ │ └── TurnTimer/ # Live battle turn countdown timer
- │ ├── character/ # Character components
- │ │ ├── TierBadgeSkeleton.tsx
- │ │ ├── TierChangeAnimation.tsx
- │ │ ├── TierErrorBoundary.tsx
- │ │ └── LevelUpPreview.tsx
- │ ├── equipment/ # Equipment system (20+ subdirectories)
- │ │ ├── ArcaneLibrary/ # Spell management (Arcane Codex)
- │ │ │ ├── HeroRoster/ # Character spell assignments
- │ │ │ ├── SpellGrimoire/ # Spell collection display
- │ │ │ ├── SpellSlot/ # Spell slot with MagicalSeal
- │ │ │ └── shared/ # SpellOrb, SpellTooltip, RarityBorder, MasteryProgressBar
- │ │ ├── Accessibility/ # Screen reader support
- │ │ ├── Badges/ # Item level/quality badges
- │ │ ├── CharacterBoard/ # Character stats + trait panel
- │ │ ├── CharacterNavigation/ # Character switcher
- │ │ ├── ContextMenu/ # Item context menu
- │ │ ├── Draggable/ # EnhancedDraggable
- │ │ ├── DropZone/ # Drop zone highlighting
- │ │ ├── Effects/ # Particles, floating text, set connections
- │ │ ├── EquipmentLayout/ # Main layout component
- │ │ ├── EquipmentSlot/ # Individual slot component
- │ │ ├── Forge/ # Upgrade anvil system
- │ │ │ ├── AnvilBackground.tsx
- │ │ │ ├── VolcanicAnvil.tsx
- │ │ │ ├── ForgeTab.tsx
- │ │ │ ├── SuccessRateMeter.tsx
- │ │ │ ├── MaterialSlotsRing.tsx
- │ │ │ ├── StatsPreview.tsx
- │ │ │ └── UpgradeResultOverlay.tsx
- │ │ ├── InventoryGrid/ # Inventory display
- │ │ ├── InventoryManager/ # Inventory coordination
- │ │ ├── Modals/ # ItemUpgradeModal
- │ │ ├── PaperDoll/ # Character model preview + energy effects
- │ │ ├── Quality/ # Reroll, quality bars, tooltips
- │ │ ├── QuickActions/ # Quick action bar
- │ │ ├── Slots/ # MotionSlot, EnhancedSlot, ItemTooltip
- │ │ ├── Spells/ # SpellsTab, SpellUpgradeModal
- │ │ ├── SquadBar/ # Squad member bar
- │ │ ├── States/ # Loading/error states
- │ │ └── StatsPanel/ # Character stats display
- │ ├── layout/ # App layout
- │ │ └── AppHeader/ # Navigation header
- │ ├── league/ # League components (20+ components)
- │ │ ├── Button/ # Styled buttons
- │ │ ├── Card/ # Card container
- │ │ ├── InviteManager/ # Player search + invites
- │ │ ├── LeagueCard/ # League preview card
- │ │ ├── LeagueChat/ # Real-time chat
- │ │ ├── LeagueCreator/ # League creation form
- │ │ ├── LeagueHeroSection/ # League header
- │ │ ├── LeagueHomePage/ # League dashboard
- │ │ ├── LeagueList/ # League browser
- │ │ ├── LeagueStatus/ # Status indicators
- │ │ ├── LeagueTabNavigation/ # Tab navigation
- │ │ ├── LeagueWall/ # Activity feed
- │ │ ├── MatchSchedule/ # Match calendar + NextMatchBanner
- │ │ ├── MatchTimer/ # Countdown timer
- │ │ ├── ParticipantList/ # Participant cards
- │ │ ├── ScheduleInfo/ # Schedule display
- │ │ ├── SeasonSummary/ # Season overview
- │ │ ├── SquadSelector/ # Squad picker
- │ │ └── StandingsTable/ # Leaderboard
- │ ├── mailbox/ # Notification components
- │ │ ├── InviteNotification/
- │ │ └── MailboxBadge/
- │ ├── quality-roll/ # Quality roll animations
- │ ├── squad/ # Squad components
- │ │ ├── CharacterCard/ # Squad character display
- │ │ ├── EquipmentManager/ # Equipment drag-drop (DndKit)
- │ │ └── InventoryPanel/ # Inventory grid (DndKit)
- │ ├── workbench/ # Dev workbench components
- │ │ ├── AdvancedStatsPanel/
- │ │ ├── StatisticsPanel/
- │ │ ├── SimulationResults/
- │ │ └── shared/ # Item/Spell select tooltips
- │ └── ErrorBoundary.tsx
- ├── hooks/ # Custom React hooks (100+)
- │ ├── league/ # League hooks (15+)
- │ │ ├── useLeagues.ts
- │ │ ├── useLeagueDetails.ts
- │ │ ├── useLeagueStandings.ts
- │ │ ├── useLeagueSchedule.ts
- │ │ ├── useLeagueChat.ts
- │ │ ├── useLeagueInvites.ts
- │ │ ├── useLeagueParticipation.ts
- │ │ ├── useFormationSetup.ts
- │ │ ├── useMatchExecution.ts
- │ │ ├── useMatchResult.ts
- │ │ ├── useNextMatch.ts
- │ │ ├── useMyNextMatch.ts
- │ │ ├── useMailbox.ts
- │ │ ├── useSeasonHistory.ts
- │ │ └── useDevTools.ts
- │ ├── test-data/ # Test data hooks
- │ ├── useEquipment.ts # Equipment state
- │ ├── useEquipmentDragHandlers.ts
- │ ├── useCharacterStats.ts # Character stat display
- │ ├── useCharacterSelection.ts
- │ ├── useItemUpgrade.ts
- │ ├── useSpellUpgrade.ts
- │ ├── useSpells.ts
- │ ├── useGameData.ts # Game data fetching
- │ ├── useAllocation.ts # Stat allocation
- │ ├── useXpDistribution.ts
- │ ├── useBattleReplay.ts # Battle replay coordination
- │ ├── useBattlefieldResponsive.ts # Responsive battlefield
- │ ├── useCanvasScale.ts
- │ ├── useBalanceTool.ts
- │ ├── useSimulation.ts
- │ ├── useInteractiveBattle.ts # Live battle WebSocket connection
- │ ├── useInteractiveBattleChallenges.ts # Challenge create/accept
- │ ├── useVisibilityState.ts # Tab visibility detection
- │ └── useCatchUpController.ts # Animation catch-up (graduated speeds)
- ├── lib/ # API client, utilities
- ├── utils/ # Validation, helpers
- │ ├── positionCalculator.ts # Battlefield positioning
- │ └── safeZonePositioning.ts # Responsive safe zones
- ├── config/ # Configuration
- ├── constants/ # App constants
- ├── data/ # Static data
- ├── styles/ # Global styles
- ├── tokens/ # Design tokens
- ├── types/ # TypeScript types
- └── test-infrastructure/ # Test utilities
- ```
- ### 3.3 Key Architectural Patterns
- #### Core Architecture Patterns
- | Pattern | Implementation |
- |---------|---------------|
- | **Domain-Driven Design** | Entities, value objects, domain services |
- | **Repository Pattern** | BaseRepository with shared CRUD logic |
- | **Dependency Injection** | TSyringe container, constructor injection |
- | **Single Source of Truth** | Backend calculates all stats, frontend displays |
- | **Event Sourcing** | Battle replay via event log reconstruction |
- | **Temporal Isolation** | JSON snapshots preserve state at execution time |
- #### Database & Transaction Patterns
- | Pattern | Implementation |
- |---------|---------------|
- | **Direct $transaction** | `prisma.$transaction([...])` for multi-operation atomicity |
- | **AsyncLocalStorage Context** | Transaction propagation across service calls |
- | **Optimistic Locking** | Character.version field prevents concurrent modification |
- | **Formation Snapshots** | Full character state frozen at match creation time |
- #### Real-Time Communication Patterns
- | Pattern | Implementation |
- |---------|---------------|
- | **WebSocket State Sync** | Socket.IO for live battle events (`battle:joined`, `battle:your_turn`, `battle:action_result`) |
- | **State-First Sync** | HP/state updates immediately, animations are visual feedback only (never block game state) |
- | **Deferred UI Updates** | Turn queue rotates AFTER animation completes via `commitTurnQueueUpdate()` |
- | **Session Lifecycle** | BattleSessionManager tracks active sessions, handles disconnection/timeout |
- #### Battle Engine Patterns
- | Pattern | Implementation |
- |---------|---------------|
- | **StatModifierBucket** | Unified stat stacking: flat bonuses first, then percentage multipliers |
- | **Stepable Engine** | `executeSingleTurn()` enables turn-by-turn live battle execution |
- | **Bucket Preparation** | `prepareSquadsWithBucket()` creates StatModifierBucket for each character |
- | **FINAL_CHARACTERS State** | After all bucket modifiers applied, used for actual combat |
- #### Animation & Rendering Patterns
- | Pattern | Implementation |
- |---------|---------------|
- | **Ref-Based Queue Protection** | `animationQueueRef.current` prevents React batching from dropping events |
- | **Catch-Up Controller** | Handles visibility changes with graduated speed multipliers (1x→2x→4x→8x) |
- | **Equipment Preservation** | `injectCurrentAttachmentsIntoIdle()` maintains equipment during attack animations |
- | **Animation-State Pairing** | Atomic `{ animation, stateUpdate }` objects ensure HP sync with visual feedback |
- ### 3.4 Data Flow
- #### Traditional API Flow (REST)
- ```
- API Request → Route → Service → Repository → Database
- ↓
- GameDataService (JSON configuration)
- ↓
- StatService (stat calculation)
- ↓
- BattleSimulator (16 injected subsystems)
- ↓
- Database (results + snapshots)
- ```
- #### Live Battle Flow (WebSocket)
- ```
- Client Action → Socket.IO → BattleGateway → BattleSession
- ↓
- BattleSessionManager.getSession()
- ↓
- executeSingleTurn() (stepable engine)
- ↓
- Broadcast to both players:
- - battle:action_result (attack events, HP updates)
- - battle:your_turn (next player's turn)
- - battle:ended (winner determined)
- ```
- #### Animation Sync Flow (Frontend)
- ```
- WebSocket Event → useLiveBattleAnimations → animationQueueRef
- ↓
- processAnimationQueue() (state-first)
- ↓
- 1. Update HP immediately (setCharacters)
- 2. Play animation (playAttackAnimation)
- 3. Commit turn queue update (deferred)
- ```
- ---
- ## 4. Database Schema
- ### 4.1 Model Overview (21 Prisma Models)
- **Core Models:**
- - User (authentication, gold currency, avatar)
- - Squad (team container, XP progression, inventory)
- - Character (stats, equipment slots, allocations, version for optimistic locking)
- - Battle (event log, formation, temporal snapshots)
- **Equipment System:**
- - Item (templates)
- - UserItem (instances with squad inventory tracking)
- - ItemUpgrade (levels 1-10)
- - SquadSpell (spell library per squad, not user)
- - SpellUpgrade (levels 1-10)
- **Economy System:**
- - PendingReward (unclaimed battle rewards)
- - TreasureChest (Two-Pool Reward System)
- **League System:**
- - League (visibility, team limits, status)
- - LeagueSeason (scheduling configuration, timestamps)
- - LeagueParticipant (user-squad-league junction)
- - LeagueMatch (scheduling, formation snapshots, row orbs)
- - LeagueStandings (points, wins, losses, rank)
- - LeagueInvite (invitation workflow)
- **Communication:**
- - ChatMessage (league chat)
- - ChatReadReceipt (read tracking)
- **Interactive Battle (Real-Time PvP):**
- - InteractiveBattleChallenge (challenge workflow)
- - InteractiveBattleReplay (live battle history)
- ### 4.2 Key Schema Patterns
- | Pattern | Description |
- |---------|-------------|
- | **Template/Instance** | Item (template) → UserItem (owned instance with upgrade) |
- | **Equipment Foreign Keys** | Character → UserItem (not Item directly) |
- | **Temporal Snapshots** | Battle stores attackerSnapshot/defenderSnapshot as JSON |
- | **Optimistic Locking** | Character.version field for concurrency control |
- | **Unique Constraints** | Squad names globally unique, character names unique per squad |
Add Comment
Please, Sign In to add comment