Guest User

Untitled

a guest
Jan 16th, 2026
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.18 KB | None | 0 0
  1. PROJECT SUMMARY
  2. --------------------------------------------------------------------------------
  3. Total Files: 2,798
  4. Total Lines of Code: 871,605
  5. - Config: 21,753 (2.5%)
  6. - Docs: 433,639 (49.8%)
  7. - Source: 121,209 (13.9%)
  8. - Tests: 272,065 (31.2%)
  9. - Tooling: 22,846 (2.6%)
  10. - Unclassified: 93 (0.0%)
  11.  
  12.  
  13.  
  14. # Part 1: Project Overview & Architecture
  15.  
  16. **Source Document:** `TECHNICAL_OVERVIEW_2026-01-14.md`
  17. **Document Version:** 3.0
  18. **Sections:** 1, 2, 3, 4
  19. **Last Updated:** January 16, 2026
  20.  
  21. ---
  22.  
  23. **Purpose:** Answers "What is this project and how is it structured?"
  24.  
  25. **Related Parts:**
  26. - Part 2: Quality, Testing & Development (how we maintain quality)
  27. - Part 3: Game Systems & Combat (how mechanics work)
  28. - Part 4: Features & Implementations (notable implementations)
  29.  
  30. ---
  31.  
  32. ## 1. Project Classification
  33.  
  34. | Attribute | Value |
  35. |-----------|-------|
  36. | **Type** | Full-stack web-based turn-based strategy game |
  37. | **Primary Language** | TypeScript (strict mode) |
  38. | **Architecture** | Domain-Driven Design with clean architecture layers |
  39.  
  40. ---
  41.  
  42. ## 2. Technology Stack
  43.  
  44. ### 2.1 Backend
  45.  
  46. | Category | Technology | Version |
  47. |----------|------------|---------|
  48. | **Runtime** | Node.js | >=20.0.0 |
  49. | **Language** | TypeScript | 5.9.2 |
  50. | **Framework** | Express.js | 5.1 |
  51. | **Database** | Supabase Local (PostgreSQL) | Docker-based |
  52. | **ORM** | Prisma | 6.16.0 |
  53. | **Validation** | Zod | 3.25 |
  54. | **Dependency Injection** | TSyringe | 4.10 |
  55. | **Logging** | Winston | 3.17 |
  56. | **Real-time** | Socket.IO | 4.8 |
  57. | **Authentication** | JWT (jsonwebtoken) | 9.0 |
  58. | **Password Hashing** | bcrypt | 6.0 |
  59.  
  60. > **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.
  61.  
  62. ### 2.2 Frontend
  63.  
  64. | Category | Technology | Version |
  65. |----------|------------|---------|
  66. | **Framework** | Next.js | 15.5 |
  67. | **UI Library** | React | 18.3 |
  68. | **Build Tool** | Turbopack | (Next.js native) |
  69. | **State Management** | React hooks + SWR | 2.3 |
  70. | **Styling** | Bootstrap | 5.3 |
  71. | **Animation** | Framer Motion | 12.23 |
  72. | **Skeletal Animation** | Spine WebGL (spine-webgl runtime) | 4.2 |
  73. | **VFX Rendering** | Raw WebGL (OpenGL ES 2.0, no framework) | - |
  74. | **Tooltips/Dialogs** | Radix UI | 1.x-2.x |
  75. | **Drag & Drop** | DND Kit | 6.3 |
  76. | **Notifications** | React Hot Toast | 2.6 |
  77. | **Charts** | Recharts | 3.1 |
  78.  
  79. > **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.
  80.  
  81. ### 2.3 Testing & Quality
  82.  
  83. | Category | Technology | Version |
  84. |----------|------------|---------|
  85. | **Test Runner** | Jest | 29.7 |
  86. | **Component Testing** | @testing-library/react | 16.3 |
  87. | **E2E Testing** | Playwright | 1.56 |
  88. | **HTTP Testing** | Supertest | 7.1 |
  89. | **Linting** | ESLint | 9.38 |
  90. | **Type Checking** | TypeScript strict mode | - |
  91. | **Quality Gates** | Custom AST-based violation detection | - |
  92.  
  93. ---
  94.  
  95. ## 3. Architecture
  96.  
  97. ### 3.1 Backend Structure
  98.  
  99. ```
  100. src/
  101. ├── contracts/ # API contracts (Zod schemas)
  102. ├── core/
  103. │ └── data/ # 25 JSON game data files
  104. │ ├── items.json # 25+ equipment templates
  105. │ ├── spells.json # Spell definitions + effects
  106. │ ├── character-classes.json # 5 classes with tier scaling
  107. │ ├── creatures.json # Enemy creature definitions
  108. │ ├── effects.json # DoT/CC effect definitions
  109. │ ├── globals.json # Combat constants
  110. │ ├── traits.json # Passive ability definitions
  111. │ ├── row-orbs.json # Row orb configuration
  112. │ ├── upgrade-config.json # Item/spell upgrade rates
  113. │ ├── loot-tables.json # Drop tables
  114. │ ├── league-rewards.json # League reward tiers
  115. │ ├── league-defaults.json # League configuration defaults
  116. │ ├── xp-rewards.json # XP reward tables
  117. │ ├── speed-mechanics.json # Queue jump thresholds
  118. │ ├── item-level-scaling.json # Item stat scaling
  119. │ └── test-*.json # Test data variants
  120. ├── domain/ # Domain layer (DDD)
  121. │ ├── entities/ # 11 core entities
  122. │ │ ├── character.ts # Character + activeEffects[]
  123. │ │ ├── squad.ts # Squad container
  124. │ │ ├── battle.ts # Battle + snapshots
  125. │ │ ├── item.ts # Item entity
  126. │ │ ├── user.ts # User entity
  127. │ │ └── league/ # League-specific entities
  128. │ │ ├── league.ts # League entity
  129. │ │ ├── league-match.ts # Match with snapshots
  130. │ │ ├── league-season.ts # Season configuration
  131. │ │ ├── league-standings.ts
  132. │ │ ├── league-participant.ts
  133. │ │ └── league-invite.ts
  134. │ ├── services/
  135. │ │ ├── battle-simulator/ # Core game logic (16 subsystems)
  136. │ │ │ ├── attack/ # Attack execution pipeline
  137. │ │ │ │ └── phases/ # 5-phase attack resolution (ActionResolver → HitResolver → DamageResolver → EffectResolver → EventBuilder)
  138. │ │ │ ├── damage/ # Physical, Spell, Elemental, Crit calculators
  139. │ │ │ ├── effects/ # StatusEffectSystem, DotProcessor
  140. │ │ │ ├── evasion/ # EvasionCheckSystem
  141. │ │ │ ├── finalization/ # BattleFinalizationSystem
  142. │ │ │ ├── initiative/ # InitiativeSystem (turn queue by speed)
  143. │ │ │ ├── logging/ # VerboseLogger
  144. │ │ │ ├── orbs/ # RowOrbSystem (flat + percent bonuses)
  145. │ │ │ ├── positioning/ # GridPositionManager (2x4 grid)
  146. │ │ │ ├── queue/ # QueueJumpSystem (speed-based extra turns)
  147. │ │ │ ├── randomness/ # BattleRNG (seeded determinism)
  148. │ │ │ ├── regeneration/ # ManaRegenerationSystem
  149. │ │ │ ├── spells/ # WizardSpellSystem, Chain Lightning
  150. │ │ │ ├── stats/ # StatModifierBucket (unified stacking)
  151. │ │ │ ├── targeting/ # ThreatCalculator, BlockingSystem, ChainTargeting
  152. │ │ │ └── traits/ # TraitSystem + handlers
  153. │ │ │ ├── TraitSystem.ts
  154. │ │ │ ├── TraitLoader.ts
  155. │ │ │ ├── TargetResolver.ts
  156. │ │ │ ├── handlers/ # StatModifierHandler
  157. │ │ │ └── trait-schema.ts
  158. │ │ ├── league/ # League domain services
  159. │ │ │ ├── core/ # Rules validation, eligibility
  160. │ │ │ ├── execution/ # Match executor, formation snapshots
  161. │ │ │ ├── lifecycle/ # Season transitions, end detection
  162. │ │ │ ├── scheduling/ # Round-robin, timezone handling
  163. │ │ │ └── scoring/ # Standings, tiebreakers, winner determination
  164. │ │ ├── xp/ # XP breakpoint interpolation
  165. │ │ └── elemental-damage-reduction-service.ts
  166. │ ├── types/ # TypeScript interfaces
  167. │ │ ├── character-types.ts
  168. │ │ ├── element-types.ts
  169. │ │ └── league-types.ts
  170. │ └── values/ # Value objects
  171. │ └── combat-value.ts # CombatValue (base + bonuses)
  172. ├── infrastructure/ # Infrastructure layer
  173. │ ├── prisma/ # Database client
  174. │ │ ├── prisma-transaction-context.ts # AsyncLocalStorage propagation
  175. │ │ └── prisma-error-handler.ts
  176. │ └── repositories/ # 16+ repositories (BaseRepository)
  177. │ ├── base-repository.ts
  178. │ ├── item-repository.ts
  179. │ └── league/ # League-specific repositories
  180. ├── services/ # Application services (100+)
  181. │ ├── auth-service.ts # Authentication
  182. │ ├── combat-service-helpers/ # Combat orchestration
  183. │ │ ├── shared/ # Test helpers
  184. │ │ └── verification/ # Test isolation, cleanup
  185. │ ├── game-data/ # GameDataService + calculators
  186. │ │ ├── calculators/ # Character stats, XP, spell level
  187. │ │ ├── loaders/ # JSON loaders + file watcher
  188. │ │ ├── providers/ # Items, spells, class-stats, rules, threat-config
  189. │ │ ├── schemas/ # Zod validation schemas
  190. │ │ ├── tier-calculator.ts # Tier determination
  191. │ │ ├── item-stat-calculator.ts
  192. │ │ └── creature-skin-resolver.ts
  193. │ ├── league/ # League application services
  194. │ │ ├── league-application-service.ts
  195. │ │ ├── league-lifecycle-service.ts
  196. │ │ ├── league-participation-service.ts
  197. │ │ ├── league-standings-service.ts
  198. │ │ ├── league-invite-service.ts
  199. │ │ ├── league-search-service.ts
  200. │ │ ├── league-notification-service.ts
  201. │ │ ├── league-scheduler-orchestrator.ts
  202. │ │ ├── mailbox-service.ts
  203. │ │ └── chat-service.ts
  204. │ ├── xp/ # XP distribution services
  205. │ │ ├── xp-distribution-service.ts
  206. │ │ ├── xp-reward-calculator.ts
  207. │ │ ├── squad-xp-calculator.ts
  208. │ │ ├── token-distribution-service.ts
  209. │ │ └── level-gap-penalty-calculator.ts
  210. │ ├── interactive-battle/ # Live battle system (real-time PvP)
  211. │ │ ├── battle-session.ts # Single battle instance state
  212. │ │ ├── battle-session-manager.ts # Active session tracking
  213. │ │ ├── challenge-service.ts # Challenge create/accept flow
  214. │ │ ├── battle-state-initializer.ts # Formation → BattleState
  215. │ │ └── engine-state-sync.ts # Engine ↔ WebSocket sync
  216. │ ├── evasion-scaling-service.ts
  217. │ └── physical-damage-reduction-service.ts
  218. ├── web/ # HTTP layer
  219. │ ├── routes/ # 30+ API route files
  220. │ │ ├── auth-routes.ts
  221. │ │ ├── combat-routes.ts
  222. │ │ ├── equipment-routes.ts
  223. │ │ ├── game-data-routes.ts
  224. │ │ ├── squad-routes.ts
  225. │ │ ├── upgrade-routes.ts
  226. │ │ ├── xp-routes.ts
  227. │ │ ├── dev/ # Developer tools
  228. │ │ │ └── balance-tool-routes.ts
  229. │ │ ├── equipment/ # Equipment helpers + mappers
  230. │ │ └── league/ # League routes (7 files)
  231. │ ├── middleware/ # Auth, developer mode
  232. │ ├── validation/ # Request validation
  233. │ └── websocket/ # Real-time gateways
  234. │ ├── chat-gateway.ts # League chat WebSocket
  235. │ └── battle-gateway.ts # Live battle WebSocket (Socket.IO)
  236. ├── flows/ # Business workflows
  237. ├── jobs/ # Background job handlers
  238. │ └── league/ # Match scheduling, standings, season detection
  239. ├── monitoring/ # Observability utilities
  240. │ ├── performance-tracker.ts
  241. │ ├── fallback-detector.ts
  242. │ └── alert-manager.ts
  243. └── utils/ # Shared utilities
  244. ├── jwt.ts
  245. ├── errors.ts
  246. ├── async-handler.ts
  247. ├── database-check.ts
  248. └── logger.ts
  249. ```
  250.  
  251. ### 3.2 Frontend Structure
  252.  
  253. ```
  254. frontend/src/
  255. ├── app/ # Next.js 15 app router (35+ pages)
  256. │ ├── api/ # API routes (Next.js)
  257. │ ├── battlefield/[battleId]/ # Battle replay visualization
  258. │ ├── battle/ # Live battle system
  259. │ │ └── live/[sessionId]/ # Real-time PvP battle page
  260. │ ├── combat/ # Combat system
  261. │ │ ├── challenge/ # Instant battle setup
  262. │ │ ├── history/ # Battle history
  263. │ │ ├── live-challenge/ # Live PvP challenge lobby
  264. │ │ │ └── pending/ # Pending challenge invitations
  265. │ │ ├── live-setup/[challengeId]/ # Live battle pre-match setup
  266. │ │ ├── result/[battleId]/ # Battle results
  267. │ │ └── setup/[opponentSquadId]/ # Pre-battle configuration
  268. │ ├── dashboard/ # Main dashboard
  269. │ ├── dev/ # Developer tools
  270. │ │ ├── balance-tool/ # JSON balance editor
  271. │ │ ├── workbench/ # Stat preview workbench
  272. │ │ └── test-rotate-prompt/ # Mobile rotation testing
  273. │ ├── equipment-prototype/ # Equipment management
  274. │ ├── leagues/ # League system
  275. │ │ ├── new/ # Create league
  276. │ │ ├── invites/ # League invitations
  277. │ │ ├── formation/[matchId]/ # Formation editor (legacy)
  278. │ │ ├── formation-v2/ # Formation editor v2
  279. │ │ │ ├── demo/
  280. │ │ │ └── [matchId]/
  281. │ │ └── [id]/ # League detail pages
  282. │ │ ├── standings/
  283. │ │ ├── matches/
  284. │ │ ├── history/
  285. │ │ ├── invite/
  286. │ │ ├── join/
  287. │ │ └── home-prototype/
  288. │ ├── squads/ # Squad management
  289. │ │ ├── new/
  290. │ │ └── [id]/equipment/
  291. │ ├── treasure-chamber/[squadId]/ # Inventory/loot management
  292. │ ├── login/ # Authentication
  293. │ └── register/
  294. ├── components/
  295. │ ├── allocation/ # Stat allocation UI
  296. │ ├── balance-tool/ # Balance editor components
  297. │ ├── battle/ # Battle UI components
  298. │ │ ├── BattleReplayControls/ # Playback controls
  299. │ │ ├── TurnOrderDisplay/ # Turn queue display
  300. │ │ ├── TacticalGrid/ # Formation grid
  301. │ │ ├── CharacterCard/ # Character display
  302. │ │ ├── BattleHeader/ # Battle info header
  303. │ │ └── BattleActions/ # Action buttons
  304. │ ├── battlefield/ # Battlefield rendering (30+ subdirectories)
  305. │ │ ├── AnimationController/ # Animation state machine
  306. │ │ ├── animations/ # Character animation definitions
  307. │ │ │ └── characters/ # Wizard, Knight, etc.
  308. │ │ ├── BattlefieldCore/ # Main canvas component (replay mode)
  309. │ │ ├── InteractiveBattlefieldCore/ # Interactive battle cards/UI wrapper
  310. │ │ ├── LiveBattlefieldCore/ # Live battle canvas (real-time PvP)
  311. │ │ │ ├── LiveBattlefieldCore.tsx # Main live battle renderer
  312. │ │ │ └── LiveTurnOrderDisplay.tsx # Real-time turn queue
  313. │ │ ├── BattlefieldOverlay/ # SVG overlay (HP bars, damage, status)
  314. │ │ ├── BattlefieldRotatePrompt/ # Mobile rotation prompt
  315. │ │ ├── CompactTurnOrder/ # Mobile turn order display
  316. │ │ ├── DamageNumber/ # Floating damage text
  317. │ │ ├── effect-parsers/ # Battle log effect parsers
  318. │ │ ├── effects/ # Raw WebGL effects system
  319. │ │ │ ├── core/ # WebGLEffectsContext, ShaderManager, BufferPool, TextureManager
  320. │ │ │ ├── renderers/ # Particle, Sprite, Line, GroundGlow, Shockwave renderers
  321. │ │ │ ├── systems/ # EffectsManager, ParticleSystem, ProjectileSystem, MeshEffectSystem
  322. │ │ │ │ └── helpers/ # FBOManager, CrosshairOverlay, QueueJumpEffects, GroundGlowManager
  323. │ │ │ ├── mesh/ # MeshDataExtractor, ScalingCalculator, LODCalculator, BoneTracking
  324. │ │ │ ├── orbit/ # ParametricPathCalculator, OrbitPresets, WaveformFunctions, NoiseGenerator
  325. │ │ │ ├── configs/ # Effect profiles, mesh archetypes, particle/projectile/lightning configs
  326. │ │ │ ├── utils/ # particle-textures, color-palettes, scale-config, coordinate-transform
  327. │ │ │ └── shaders/ # GLSL shaders (particle, sprite, line, ground-glow, shockwave)
  328. │ │ ├── FPSMeter/ # Performance display
  329. │ │ ├── hooks/ # Battlefield-specific hooks
  330. │ │ │ ├── useBattleReplayAnimations.ts # Replay mode animation coordinator
  331. │ │ │ └── useLiveBattleAnimations.ts # Live battle animation + HP sync
  332. │ │ ├── HPBar/ # Health bar component
  333. │ │ ├── layouts/ # Battlefield layout variants
  334. │ │ ├── ManaBar/ # Mana display
  335. │ │ ├── MobileControlsBar/ # Touch controls
  336. │ │ ├── QueueJumpText/ # Queue jump announcements
  337. │ │ ├── ResistanceBadge/ # Elemental resistance display
  338. │ │ ├── spell-handlers/ # Per-spell animation handlers
  339. │ │ ├── SpineAnimationController/ # Spine animation coordination
  340. │ │ ├── SpineErrorBoundary/ # Animation error handling
  341. │ │ ├── SpineRenderer/ # WebGL Spine rendering
  342. │ │ ├── SpriteRenderer/ # CSS sprite rendering
  343. │ │ ├── StatBreakdownPanel/ # Arcane Insight debug overlay
  344. │ │ ├── StunStatusBadge/ # Stun indicator
  345. │ │ ├── BurnStatusBadge/ # Burn indicator
  346. │ │ ├── TurnOrderDisplay/ # Turn queue with queue jump animations
  347. │ │ └── TurnTimer/ # Live battle turn countdown timer
  348. │ ├── character/ # Character components
  349. │ │ ├── TierBadgeSkeleton.tsx
  350. │ │ ├── TierChangeAnimation.tsx
  351. │ │ ├── TierErrorBoundary.tsx
  352. │ │ └── LevelUpPreview.tsx
  353. │ ├── equipment/ # Equipment system (20+ subdirectories)
  354. │ │ ├── ArcaneLibrary/ # Spell management (Arcane Codex)
  355. │ │ │ ├── HeroRoster/ # Character spell assignments
  356. │ │ │ ├── SpellGrimoire/ # Spell collection display
  357. │ │ │ ├── SpellSlot/ # Spell slot with MagicalSeal
  358. │ │ │ └── shared/ # SpellOrb, SpellTooltip, RarityBorder, MasteryProgressBar
  359. │ │ ├── Accessibility/ # Screen reader support
  360. │ │ ├── Badges/ # Item level/quality badges
  361. │ │ ├── CharacterBoard/ # Character stats + trait panel
  362. │ │ ├── CharacterNavigation/ # Character switcher
  363. │ │ ├── ContextMenu/ # Item context menu
  364. │ │ ├── Draggable/ # EnhancedDraggable
  365. │ │ ├── DropZone/ # Drop zone highlighting
  366. │ │ ├── Effects/ # Particles, floating text, set connections
  367. │ │ ├── EquipmentLayout/ # Main layout component
  368. │ │ ├── EquipmentSlot/ # Individual slot component
  369. │ │ ├── Forge/ # Upgrade anvil system
  370. │ │ │ ├── AnvilBackground.tsx
  371. │ │ │ ├── VolcanicAnvil.tsx
  372. │ │ │ ├── ForgeTab.tsx
  373. │ │ │ ├── SuccessRateMeter.tsx
  374. │ │ │ ├── MaterialSlotsRing.tsx
  375. │ │ │ ├── StatsPreview.tsx
  376. │ │ │ └── UpgradeResultOverlay.tsx
  377. │ │ ├── InventoryGrid/ # Inventory display
  378. │ │ ├── InventoryManager/ # Inventory coordination
  379. │ │ ├── Modals/ # ItemUpgradeModal
  380. │ │ ├── PaperDoll/ # Character model preview + energy effects
  381. │ │ ├── Quality/ # Reroll, quality bars, tooltips
  382. │ │ ├── QuickActions/ # Quick action bar
  383. │ │ ├── Slots/ # MotionSlot, EnhancedSlot, ItemTooltip
  384. │ │ ├── Spells/ # SpellsTab, SpellUpgradeModal
  385. │ │ ├── SquadBar/ # Squad member bar
  386. │ │ ├── States/ # Loading/error states
  387. │ │ └── StatsPanel/ # Character stats display
  388. │ ├── layout/ # App layout
  389. │ │ └── AppHeader/ # Navigation header
  390. │ ├── league/ # League components (20+ components)
  391. │ │ ├── Button/ # Styled buttons
  392. │ │ ├── Card/ # Card container
  393. │ │ ├── InviteManager/ # Player search + invites
  394. │ │ ├── LeagueCard/ # League preview card
  395. │ │ ├── LeagueChat/ # Real-time chat
  396. │ │ ├── LeagueCreator/ # League creation form
  397. │ │ ├── LeagueHeroSection/ # League header
  398. │ │ ├── LeagueHomePage/ # League dashboard
  399. │ │ ├── LeagueList/ # League browser
  400. │ │ ├── LeagueStatus/ # Status indicators
  401. │ │ ├── LeagueTabNavigation/ # Tab navigation
  402. │ │ ├── LeagueWall/ # Activity feed
  403. │ │ ├── MatchSchedule/ # Match calendar + NextMatchBanner
  404. │ │ ├── MatchTimer/ # Countdown timer
  405. │ │ ├── ParticipantList/ # Participant cards
  406. │ │ ├── ScheduleInfo/ # Schedule display
  407. │ │ ├── SeasonSummary/ # Season overview
  408. │ │ ├── SquadSelector/ # Squad picker
  409. │ │ └── StandingsTable/ # Leaderboard
  410. │ ├── mailbox/ # Notification components
  411. │ │ ├── InviteNotification/
  412. │ │ └── MailboxBadge/
  413. │ ├── quality-roll/ # Quality roll animations
  414. │ ├── squad/ # Squad components
  415. │ │ ├── CharacterCard/ # Squad character display
  416. │ │ ├── EquipmentManager/ # Equipment drag-drop (DndKit)
  417. │ │ └── InventoryPanel/ # Inventory grid (DndKit)
  418. │ ├── workbench/ # Dev workbench components
  419. │ │ ├── AdvancedStatsPanel/
  420. │ │ ├── StatisticsPanel/
  421. │ │ ├── SimulationResults/
  422. │ │ └── shared/ # Item/Spell select tooltips
  423. │ └── ErrorBoundary.tsx
  424. ├── hooks/ # Custom React hooks (100+)
  425. │ ├── league/ # League hooks (15+)
  426. │ │ ├── useLeagues.ts
  427. │ │ ├── useLeagueDetails.ts
  428. │ │ ├── useLeagueStandings.ts
  429. │ │ ├── useLeagueSchedule.ts
  430. │ │ ├── useLeagueChat.ts
  431. │ │ ├── useLeagueInvites.ts
  432. │ │ ├── useLeagueParticipation.ts
  433. │ │ ├── useFormationSetup.ts
  434. │ │ ├── useMatchExecution.ts
  435. │ │ ├── useMatchResult.ts
  436. │ │ ├── useNextMatch.ts
  437. │ │ ├── useMyNextMatch.ts
  438. │ │ ├── useMailbox.ts
  439. │ │ ├── useSeasonHistory.ts
  440. │ │ └── useDevTools.ts
  441. │ ├── test-data/ # Test data hooks
  442. │ ├── useEquipment.ts # Equipment state
  443. │ ├── useEquipmentDragHandlers.ts
  444. │ ├── useCharacterStats.ts # Character stat display
  445. │ ├── useCharacterSelection.ts
  446. │ ├── useItemUpgrade.ts
  447. │ ├── useSpellUpgrade.ts
  448. │ ├── useSpells.ts
  449. │ ├── useGameData.ts # Game data fetching
  450. │ ├── useAllocation.ts # Stat allocation
  451. │ ├── useXpDistribution.ts
  452. │ ├── useBattleReplay.ts # Battle replay coordination
  453. │ ├── useBattlefieldResponsive.ts # Responsive battlefield
  454. │ ├── useCanvasScale.ts
  455. │ ├── useBalanceTool.ts
  456. │ ├── useSimulation.ts
  457. │ ├── useInteractiveBattle.ts # Live battle WebSocket connection
  458. │ ├── useInteractiveBattleChallenges.ts # Challenge create/accept
  459. │ ├── useVisibilityState.ts # Tab visibility detection
  460. │ └── useCatchUpController.ts # Animation catch-up (graduated speeds)
  461. ├── lib/ # API client, utilities
  462. ├── utils/ # Validation, helpers
  463. │ ├── positionCalculator.ts # Battlefield positioning
  464. │ └── safeZonePositioning.ts # Responsive safe zones
  465. ├── config/ # Configuration
  466. ├── constants/ # App constants
  467. ├── data/ # Static data
  468. ├── styles/ # Global styles
  469. ├── tokens/ # Design tokens
  470. ├── types/ # TypeScript types
  471. └── test-infrastructure/ # Test utilities
  472. ```
  473.  
  474. ### 3.3 Key Architectural Patterns
  475.  
  476. #### Core Architecture Patterns
  477.  
  478. | Pattern | Implementation |
  479. |---------|---------------|
  480. | **Domain-Driven Design** | Entities, value objects, domain services |
  481. | **Repository Pattern** | BaseRepository with shared CRUD logic |
  482. | **Dependency Injection** | TSyringe container, constructor injection |
  483. | **Single Source of Truth** | Backend calculates all stats, frontend displays |
  484. | **Event Sourcing** | Battle replay via event log reconstruction |
  485. | **Temporal Isolation** | JSON snapshots preserve state at execution time |
  486.  
  487. #### Database & Transaction Patterns
  488.  
  489. | Pattern | Implementation |
  490. |---------|---------------|
  491. | **Direct $transaction** | `prisma.$transaction([...])` for multi-operation atomicity |
  492. | **AsyncLocalStorage Context** | Transaction propagation across service calls |
  493. | **Optimistic Locking** | Character.version field prevents concurrent modification |
  494. | **Formation Snapshots** | Full character state frozen at match creation time |
  495.  
  496. #### Real-Time Communication Patterns
  497.  
  498. | Pattern | Implementation |
  499. |---------|---------------|
  500. | **WebSocket State Sync** | Socket.IO for live battle events (`battle:joined`, `battle:your_turn`, `battle:action_result`) |
  501. | **State-First Sync** | HP/state updates immediately, animations are visual feedback only (never block game state) |
  502. | **Deferred UI Updates** | Turn queue rotates AFTER animation completes via `commitTurnQueueUpdate()` |
  503. | **Session Lifecycle** | BattleSessionManager tracks active sessions, handles disconnection/timeout |
  504.  
  505. #### Battle Engine Patterns
  506.  
  507. | Pattern | Implementation |
  508. |---------|---------------|
  509. | **StatModifierBucket** | Unified stat stacking: flat bonuses first, then percentage multipliers |
  510. | **Stepable Engine** | `executeSingleTurn()` enables turn-by-turn live battle execution |
  511. | **Bucket Preparation** | `prepareSquadsWithBucket()` creates StatModifierBucket for each character |
  512. | **FINAL_CHARACTERS State** | After all bucket modifiers applied, used for actual combat |
  513.  
  514. #### Animation & Rendering Patterns
  515.  
  516. | Pattern | Implementation |
  517. |---------|---------------|
  518. | **Ref-Based Queue Protection** | `animationQueueRef.current` prevents React batching from dropping events |
  519. | **Catch-Up Controller** | Handles visibility changes with graduated speed multipliers (1x→2x→4x→8x) |
  520. | **Equipment Preservation** | `injectCurrentAttachmentsIntoIdle()` maintains equipment during attack animations |
  521. | **Animation-State Pairing** | Atomic `{ animation, stateUpdate }` objects ensure HP sync with visual feedback |
  522.  
  523. ### 3.4 Data Flow
  524.  
  525. #### Traditional API Flow (REST)
  526. ```
  527. API Request → Route → Service → Repository → Database
  528. GameDataService (JSON configuration)
  529. StatService (stat calculation)
  530. BattleSimulator (16 injected subsystems)
  531. Database (results + snapshots)
  532. ```
  533.  
  534. #### Live Battle Flow (WebSocket)
  535. ```
  536. Client Action → Socket.IO → BattleGateway → BattleSession
  537. BattleSessionManager.getSession()
  538. executeSingleTurn() (stepable engine)
  539. Broadcast to both players:
  540. - battle:action_result (attack events, HP updates)
  541. - battle:your_turn (next player's turn)
  542. - battle:ended (winner determined)
  543. ```
  544.  
  545. #### Animation Sync Flow (Frontend)
  546. ```
  547. WebSocket Event → useLiveBattleAnimations → animationQueueRef
  548. processAnimationQueue() (state-first)
  549. 1. Update HP immediately (setCharacters)
  550. 2. Play animation (playAttackAnimation)
  551. 3. Commit turn queue update (deferred)
  552. ```
  553.  
  554. ---
  555.  
  556. ## 4. Database Schema
  557.  
  558. ### 4.1 Model Overview (21 Prisma Models)
  559.  
  560. **Core Models:**
  561. - User (authentication, gold currency, avatar)
  562. - Squad (team container, XP progression, inventory)
  563. - Character (stats, equipment slots, allocations, version for optimistic locking)
  564. - Battle (event log, formation, temporal snapshots)
  565.  
  566. **Equipment System:**
  567. - Item (templates)
  568. - UserItem (instances with squad inventory tracking)
  569. - ItemUpgrade (levels 1-10)
  570. - SquadSpell (spell library per squad, not user)
  571. - SpellUpgrade (levels 1-10)
  572.  
  573. **Economy System:**
  574. - PendingReward (unclaimed battle rewards)
  575. - TreasureChest (Two-Pool Reward System)
  576.  
  577. **League System:**
  578. - League (visibility, team limits, status)
  579. - LeagueSeason (scheduling configuration, timestamps)
  580. - LeagueParticipant (user-squad-league junction)
  581. - LeagueMatch (scheduling, formation snapshots, row orbs)
  582. - LeagueStandings (points, wins, losses, rank)
  583. - LeagueInvite (invitation workflow)
  584.  
  585. **Communication:**
  586. - ChatMessage (league chat)
  587. - ChatReadReceipt (read tracking)
  588.  
  589. **Interactive Battle (Real-Time PvP):**
  590. - InteractiveBattleChallenge (challenge workflow)
  591. - InteractiveBattleReplay (live battle history)
  592.  
  593. ### 4.2 Key Schema Patterns
  594.  
  595. | Pattern | Description |
  596. |---------|-------------|
  597. | **Template/Instance** | Item (template) → UserItem (owned instance with upgrade) |
  598. | **Equipment Foreign Keys** | Character → UserItem (not Item directly) |
  599. | **Temporal Snapshots** | Battle stores attackerSnapshot/defenderSnapshot as JSON |
  600. | **Optimistic Locking** | Character.version field for concurrency control |
  601. | **Unique Constraints** | Squad names globally unique, character names unique per squad |
  602.  
Add Comment
Please, Sign In to add comment