← Back
Play

Flow State

An HVAC/plumbing installation game where students answer service calls, diagnose problems, and build both plumbing and HVAC systems using component-based drag-and-drop placement. Each level has two "zones" — a plumbing task (pipe fitting selection with slope logic) and an HVAC task (duct component selection with sizing). Students choose which zone to tackle first, complete both, and receive a combined score.

Game Flow

Menu → Level Selection → Level Intro → Dispatch (Customer Call)
  → Task Select → [Zone A: Prep → Connection Challenge → Flow Test → Compliance Check]
  → Task Select → [Zone B: Prep → Connection Challenge → Flow Test → Compliance Check]
  → Job Report (Results)
  • Menu: Hero screen with game description and Play button
  • Level Selection: 13 levels (1 tutorial + 12 campaign) across Easy/Medium/Hard/Expert with stars, best score
  • Level Intro: Service call briefing — customer, location, complaint
  • Dispatch: Customer call with 3 rounds of diagnostic questions (best/decent/poor quality); best questions earn hints that reveal blueprint detail
  • Task Select: Choose Plumbing or HVAC zone; completed zones show checkmarks
  • Prep: Per-zone PPE (Gear Up), tools (Tool Match), and/or safety checks (Safety Scan)
  • Measurement (Medium+ only): Quick sizing/calculation MCQ questions
  • Connection Challenge: Component-based drag-and-drop placement puzzle
  • Flow Test: Visual simulation — water/air particles flow through placed components
  • Compliance Check: Post-flow code compliance checklist with educational feedback
  • Job Report: Combined score from both zones, grade, stars

Core Mechanics

Customer Dispatch (Shared Mini-Game)

Uses lib/mini-games/dispatch/. Customer describes a problem; student asks diagnostic questions across 3 rounds. Best questions earn hints that appear on the blueprint panel during the connection challenge.

Connection Challenge (Component Placement)

Grid-based component placement puzzle. Player selects components from a categorized palette and places them on the grid to build a complete system from START to END.

Two perspectives:

  • Plumbing: Place pipe fittings (straight pipes, elbows, traps, reducers) to build a pipe run. Drain lines must maintain downward slope and include a trap (P-trap or S-trap) — uphill connections cause flow test failure. Supply lines (pressurized) do not require slope or traps. Components come in sizes (1/2", 3/4", 1.5", 2") that must match at connections.
  • HVAC (top-down): Place duct components (rigid, flex, elbows, reducers) to route airflow. Must size trunk larger than branches. Rigid duct is more efficient than flex; each elbow reduces airflow.

Interaction model:

  • Drag: Drag components from the bottom palette onto grid cells (via GameDndProvider + @dnd-kit)
  • Tap-select: Tap a palette item to select, then tap an empty grid cell to place
  • Select: Tap a placed component to select it — shows rotate/remove buttons alongside the palette
  • Rotate: Rotate button or tap-to-rotate turns the component 90° (0/90/180/270)
  • Remove: Remove button returns the component to inventory (increments rework counter)

Component palette: Accordion-style grouped tray at the bottom — components are organized into categories (Straight, Elbows, Traps, Tees, Reducers, Flex, Ends, Other). Each group collapses/expands with a chevron toggle. Items show SVG thumbnails, size labels, and remaining count.

Grid rendering: Components render as SVG pipe shapes directly in each cell:

  • Plumbing pipes: sky-blue with gradient fills, rounded ends
  • HVAC ducts: zinc-gray with flat fills, square ends
  • Pipe segments extend to cell edges so adjacent pieces visually connect
  • Type-specific details: P-trap U-curve, S-trap S-curve, elbow highlight arc, flex duct corrugation, reducer taper, clean-out cross
  • Flow state: pipes change to bright blue (plumbing) or teal (HVAC) with glow

Flow test: Player presses "Turn on Water" / "Turn on System":

  • simulateFlow traces flow through connected components via BFS
  • Checks: connection completeness, size compatibility, slope (plumbing), trap presence, sizing adequacy
  • Success: Animated flow particles (blue dots for water, cyan for air) travel through each cell sequentially with staggered delays; arrival pulse at each junction
  • Partial success: Flow reaches end but has issues — shows animation + issue banner explaining the problem
  • Failure: No complete path — spill point highlighted with ! badge on the cell, descriptive message in banner ("Path does not reach the endpoint", "Uphill run — water cannot flow upward in a drain line")
  • Issues banner: colored strip between HUD and grid — red for failures, green for success — auto-dismisses after 5s

Code compliance: After flow test passes, an inspection checklist appears (via CompliancePanel):

  • Each rule shows green (pass) or red (fail) with a one-line educational explanation
  • Compliance affects the final score but doesn't block completion
  • "Complete Zone" button finishes the zone and calculates final score

Blueprint Panel

Modal overlay (ported from Circuit Breaker pattern) showing the target system layout:

  • Easy: Full blueprint with component types labeled
  • Medium: Types shown but not sizes
  • Hard: Layout outline only (dots for component positions)
  • Expert: Only shows what dispatch hints revealed; locked message if no hints
  • Shows progress: "X of Y components placed"
  • Shows dispatch hint in a green callout when available

Component Types

Plumbing (8 types, up to 4 sizes each):

TypeSizesConnectionsEfficiencyReal-World Use
Straight Pipe1/2", 3/4", 1.5", 2"top-bottom1.0Basic pipe run. 1/2" for fixture supply, 3/4" for main supply, 1.5" for sink drains, 2" for shower/main drains
90° Elbow1/2", 3/4", 1.5", 2"top-right (rotatable)0.85Direction change. Route around obstacles, transition vertical to horizontal. Each elbow reduces flow
P-Trap1.5", 2"top-right (rotatable)0.90U-bend with horizontal exit to wall. Required at fixture drains where outlet runs to a wall pipe. Only drain sizes (no supply)
S-Trap1.5", 2"top-bottom0.92Inline vertical trap. Required at fixture drains where outlet continues downward to a floor or stack. Only drain sizes (no supply)
Tee1/2", 3/4", 1.5", 2"top-bottom-right0.88Branch junction. Where a branch drain meets the main, or where supply splits to serve multiple fixtures
Reducer2"→1.5", 1.5"→3/4", 3/4"→1/2"top-bottom0.90Size transition. Required when connecting different pipe sizes — without one, sizes won't match and flow fails
Coupling1/2", 3/4", 1.5", 2"top-bottom0.98Endpoint adapter. Required at START and END connection stubs to join new work to the existing system. Compliance rule endpoint-coupling-present enforces this
Clean-Out1.5", 2"top-bottom0.97Code-required access point. Must be placed within 3 cells of a direction change (elbow). Position-aware clean-out-present rule enforces placement

HVAC (7 types, up to 4 sizes each):

TypeSizesConnectionsEfficiencyReal-World Use
Rigid Duct6", 8", 10", 12"top-bottom1.0Main duct runs. 12" for trunk, stepping down through branches. Best airflow efficiency
Flex Duct6", 8"top-bottom0.80Flexible routing for tight spaces. Easier to route around obstacles but 20% less efficient than rigid
Duct Elbow6", 8", 10", 12"top-right (rotatable)0.85Direction change. Each elbow adds static pressure drop — minimize elbows for better airflow
Duct Tee8", 10", 12"top-bottom-right0.88Branch takeoff. Where a branch duct splits from the main trunk to serve a room
Duct Reducer12"→10", 10"→8", 8"→6"top-bottom0.90Size step-down. Trunk must be larger than branches — use reducers at each step-down
Register Boot6", 8"top only0.95End piece. Transitions from round/rectangular duct to the wall/floor register grille
Plenum10", 12"bottom only0.98Start piece. Connects to the air handler unit — the source of conditioned air

Size Matching Rules

  • Adjacent components must have matching sizes at their connection point — a 2" pipe cannot connect to a 1.5" pipe without a reducer in between
  • Mismatched sizes cause flow failure (spill at the junction point)
  • Reducers have different sizes on each end (size for the input, sizeOut for the output) — they must match the pipes on both sides
  • Endpoints (START/END) have a required size — the first/last component must match the endpoint size or flow fails with a size-mismatch error
  • Missing trap in plumbing zones causes flow failure (not just a compliance warning) — sewer gas protection is mandatory

Rotation

Each component has baseConnections (edges in default orientation). rotateEdge(edge, rotation) cycles through ["top", "right", "bottom", "left"]:

  • Straight pipe: top-bottom → left-right at 90°
  • Elbow: top-right → right-bottom → bottom-left → left-top
  • Tee: top-bottom-right → top-right-left → ... (3 active edges rotate together)

Inventory (Limited Components)

Each level provides a specific inventory via ConnectionConfig.inventory. On Easy, generous counts with the exact pieces needed plus extras. On Expert, tight budget with some decoy sizes. Practice mode includes all component types in generous quantities.

When to Use Each Plumbing Component

ScenarioComponents NeededWhy
Simple drain run (sink to stack)Straight 2" + S-Trap 2"Direct vertical run with inline trap for sewer gas protection (outlet goes downward)
Drain with horizontal exit (sink to wall pipe)Straight + P-Trap 2"P-trap exits horizontally to a wall pipe — use when outlet runs to the wall
Drain with direction changeStraight + Elbow + P-Trap or S-TrapRoute around joists, beams, or obstacles — choose trap type based on outlet direction
Fixture branch to main drainTee + Straight + P-Trap or S-TrapTee connects the fixture branch to the main drain; trap type depends on outlet direction
Transition from main to fixtureReducer + Straight (smaller)Main stack is 2", fixture drain is 1.5" — reducer bridges the gap
Supply line to fixtureStraight 1/2" or 3/4" + ElbowsSupply lines are smaller (pressurized, no slope needed)
Long drain run with direction changeStraight + Clean-Out + ElbowCode requires clean-out within 3 cells of each direction change
Connecting to existing systemCoupling at START + pipes + Coupling at ENDCouplings join new work to existing stubs — compliance requires them at endpoints
Multi-fixture bathroomTee + multiple branchesTee at the main to split into separate fixture drains

Diagnostic "Fix-It" Levels

Campaign levels 8, 10, and 12 use kind: "diagnostic":

  • System is pre-placed with intentional faults via prePlaced (wrong sizes, missing trap, undersized duct, wrong component type)
  • Player inspects the system, identifies faults, removes bad components, and replaces them from inventory
  • Diagnostic levels skip prep phases (Gear Up/Tool Match) — the player goes straight from dispatch to the connection challenge
  • Every fault type is unique to its level — no fault reason appears in more than one diagnostic level
  • Fault complexity escalates: L8 has 3 faults per zone (rotation, sizing, compliance), L10 has 4 plumbing + 3 HVAC faults (including removal-based fixes), L12 is the capstone with 5 faults per zone, locked correct components, and every compliance rule active
  • L12 uses locked: true on ~60% of correct pre-placed pieces — player must identify only the faults without removing correct work

Prep Phases

All use existing shared mini-games:

  • Gear Up (TapSelectPlayfield): Select correct PPE
  • Tool Match (MultiSelectPlayfield): Select correct tools
  • Safety Scan (CardJudgePlayfield): Judge SAFE vs HAZARD
  • Measurement (McqPlayfield): Sizing/calculation questions (Medium+)

Level Narratives & Difficulty Curve

13 levels total (0-12): a tutorial level followed by 12 campaign levels. All levels are full service calls with dispatch, customer conversations, prep phases, and dual-zone challenges. The progression follows a career arc from residential apprentice work → commercial jobs → institutional/industrial contracts → master-level diagnostics.

Structure: Tutorial (0), Easy (1-3), Medium (4-6), Hard (7-9), Expert (10-12) Level modes: Tutorial (first job, kind: "tutorial"), Standard (build from scratch), Diagnostic (inspect and fix a pre-built system — levels 8, 10, 12)

Narrative Arc

First service call → Residential apprentice → Commercial jobs → Institutional contracts → Master diagnostics
L0 (tutorial call) → L1-3 (home calls) → L4-6 (apt/office/restaurant) → L7-9 (school/inspection/hospital) → L10-12 (condo/warehouse/capstone)

Tutorial (Level 0) — First Service Call

Setting: Residential kitchen. Tone: Friendly, patient homeowner. Your very first service call as an apprentice. Teaching goal: Full game flow introduction — dispatch, prep, drag-and-drop, rotation, flow test, compliance. Simplest possible grids with generous inventory and full blueprint.

#TitleCustomerSettingStoryPlumbing TaskHVAC TaskNew Skills
0Kitchen EmergencyMaria GonzalezResidential KitchenSink won't drain, kitchen AC dead. Your very first call — the dispatcher walks you through it. Simple straight-line paths, full blueprint visible, generous inventory, no timer.5×3. Straight 2" drain with S-trap. 3 straights + 1 S-trap. Single straight path from START to END.5×3. Straight 8" duct run. 3 rigid ducts. Single straight path from START to END.Dispatch flow, palette selection, drag-to-grid, tap-to-place, rotation, flow test, trap concept (P-trap / S-trap), slope concept, compliance checklist
  • kind: "tutorial", full dispatch with Maria Gonzalez, Gear Up prep phase, no timer (parTimeSeconds: 0)
  • Minimal grids (5×3), generous inventory, straight-line paths — designed to be impossible to fail
  • Full blueprint always visible (not difficulty-gated)
  • Scene cards guide the player through each step
  • Compliance rules: slope-adequate and trap-present (plumbing), duct-sizing-adequate (HVAC)

Easy (Levels 1-3) — Residential, Single Runs

Setting: Homes. Tone: Friendly homeowners, straightforward problems. Building confidence after the tutorial. Teaching goal: Applying basics to real routing challenges — elbow rotations, obstacles, flex duct, supply vs drain, first reducer.

#TitleCustomerSettingStoryPlumbing TaskHVAC TaskNew Skills
1Bathroom BackupJames CarterResidential BathroomGurgling sink, stuffy bedroom. First level with direction changes and obstacles.6×5. Drain with routing choices around obstacles + P-trap (horizontal exit). Rotation matters.6×5. Route around beam using flex or rigid. Introduces flex duct trade-off.Elbow rotations (all 4), flex vs rigid efficiency trade-off, obstacles on grid
2Utility Room UpgradePatricia WilliamsResidential Utility RoomNew water heater needs connecting, dryer vent duct is disconnected.6×6. 3/4" supply line through wall corridor. No slope or trap required (supply line is pressurized).7×5. 8"→6" duct with reducer. Strategic reducer placement determines material needs.Reducer for size transitions, obstacle routing, supply vs drain distinction
3Basement LaundryDerek & Nina HowardResidential BasementWashing machine drain is backing up and the basement HVAC register blows weak air. Slightly larger grid, more routing options.7×6. 2" drain with P-trap (horizontal exit), multiple elbows, and a longer path through the basement around a support column and water heater.7×6. 8" duct with elbows and flex, routing around ductwork and a support beam. Longer run with more direction changes.Longer multi-turn paths, choosing between multiple valid routes, building speed before Medium

Level 2 note: The plumbing zone is a pressurized supply line, not a drain. slopeRequired should be false and no trap is needed. This teaches students that supply lines follow different rules than drain lines.

Prep phases: Gear Up (L1-2), Safety Scan (L3)


Medium (Levels 4-6) — Residential/Commercial Transition

Setting: Apartments and commercial spaces. Tone: Mix of homeowners and business owners with more urgency. Teaching goal: Size transitions, clean-outs, commercial code requirements, bigger grids, tool match prep phase.

#TitleCustomerSettingStoryPlumbing TaskHVAC TaskNew Skills
4Apartment RenovationDavid ChenResidential ApartmentBathroom remodel — drain needs rerouting around a floor joist, HVAC trunk needs step-down to the new room. First level with a reducer in plumbing.7×7. 2" drain with P-trap (horizontal exit to wall) and reducer strategy. Reducer placement determines routing.8×7. First tee fork-and-rejoin. Both branches route to END.Plumbing reducers, first tee branching, Tool Match prep
5Office Building HVACSarah Mitchell (office manager)Commercial OfficeBreak room sink is slow, main HVAC trunk lost a register. First true commercial setting — bigger grid, multi-step duct sizing.7×7. 1.5" drain with P-trap (horizontal exit) to the main stack. Conduit obstacle.8×8. Triple step-down: 12"→10"→8". Central wall block forces creative routing. Two column obstacles.Commercial scale, 3-size duct trunk, max-run-length compliance
6Restaurant KitchenRobert Taylor (owner)Commercial RestaurantGrease trap line needs clean-out for health code, kitchen ventilation ducting fell apart. First clean-out requirement.8×7. 2" drain with P-trap (horizontal exit) and clean-out near elbow. Gas line + conduit obstacles. 5 compliance rules.8×7. 10"→8" duct around exhaust fan and hood.Clean-out compliance, commercial kitchen hazards, Safety Scan prep

Prep phases: Gear Up + Tool Match (L4-5), Safety Scan + Tool Match (L6)


Hard (Levels 7-9) — Commercial/Institutional

Setting: Schools, homes (for inspection), hospitals. Tone: Higher stakes — code inspectors, hospital administrators, school boards. Teaching goal: Complex routing, full compliance suites, diagnostic mode introduction, multi-obstacle grids.

#TitleCustomerSettingStoryPlumbing TaskHVAC TaskNew Skills
7School Wing AdditionAngela Rivera (school facilities director)Commercial SchoolNew classroom wing needs plumbing for restrooms and HVAC for 3 classrooms. Tight schedule before the semester starts.8×8. Multi-path drain with tee junction, P-trap, clean-out. Joist obstacle.8×8. Full trunk-to-branch layout with tee. 12"→10"→8" step-down. Beam + column.Tee junctions in both zones, multi-compliance (5 rules), coupling at endpoints
8System InspectionMarcus Johnson (home inspector)Residential HomeDIAGNOSTIC. Home sale pending — inspector found problems. 3 unique plumbing faults (rotation, sizing, compliance) + 3 unique HVAC faults.8×8. Pre-placed system with 3 faults: wrong elbow rotation, undersized trap, clean-out too far from elbow.8×8. Pre-placed system with 3 faults: undersized duct elbow, rigid near structural element, wrong register orientation.Diagnostic inspection, understanding WHY things fail, subtle fault identification
9Hospital CorridorLisa Park (hospital facilities manager)Hospital WingCritical corridor duct and drain replacement. Zero tolerance — compliance must be perfect. Every rule is checked.9×8. Full-compliance drain with rule conflicts: clean-out proximity vs structural clearance.9×8. Trunk layout with max-run-length pressure. Flex duct tempting but risky.Full compliance suite, rule interaction, institutional-grade precision

Prep phases: Gear Up + Tool Match (L7, L9), none for diagnostic (L8 — goes straight to inspection)


Expert (Levels 10-12) — Industrial/Mixed-Use & Master Diagnostics

Setting: Condos, warehouses, mixed-use buildings. Tone: Expert-level peers, demanding facility managers, final exam stakes. Teaching goal: Full palette mastery, diagnostic skills, decoy components, tightest budgets, largest grids.

#TitleCustomerSettingStoryPlumbing TaskHVAC TaskNew Skills
10Condo DiagnosticThomas Wright (property manager)Residential Condo ComplexDIAGNOSTIC. Multiple units reporting slow drains and uneven heating. Inspect both systems for the full building.10×10. Pre-placed system with 3+ faults: undersized pipes, missing trap, wrong reducer placement. Decoy inventory.10×10. Pre-placed system with undersized trunk, missing reducer, wrong flex where rigid is needed.Complex diagnostics on large grids, decoy replacement parts, multi-fault identification
11Industrial FacilityKaren Lee (plant operations)Industrial WarehouseMechanical room needs full build-out. Process water drain and warehouse HVAC from scratch. Largest standard-build grid.10×10. Full system: tees, couplings, clean-out, reducer chain. 2 obstacles. Expert-tight inventory. Decoy sizes.10×10. Full palette: plenum start, register boot end, tee branches, flex + rigid mix. Expert-tight inventory.Full palette under tight budget, decoy filtering, industrial-scale systems
12Final InspectionMichael Brown (general contractor)Mixed-Use BuildingDIAGNOSTIC — Capstone. GC calls you for final sign-off before occupancy permit. Both systems have subtle faults across a large grid. Every compliance rule is active.10×10. Pre-placed full system with subtle faults: sizing off by one step, clean-out too far from elbow, wrong coupling size. All compliance rules active.10×10. Pre-placed full system with subtle faults: trunk undersized at one section, reducer in wrong direction, flex where rigid is code-required. All compliance rules active.Master-level fault detection, full code compliance capstone, career culmination

Prep phases: none for diagnostics (L10, L12), Gear Up + Tool Match (L11)


Difficulty Scaling Summary

SettingTutorial (0)Easy (1-3)Medium (4-6)Hard (7-9)Expert (10-12)
Grid size5×36×5 – 7×67×7 – 8×88×8 – 9×810×10
Component variety1-2 types2-3 types4-5 types, reducers6+ types, tight budgetFull palette, decoys
Blueprint detailFull (always)FullTypes onlyOutlineDispatch hints only
Compliance rules1-22-33-44-55+ (all rules for capstone)
Plumbing complexityStraight run + trapSingle drain with elbowsSize transitions, clean-outMulti-fixture, tee, couplingsFull system or multi-fault diagnostic
HVAC complexityStraight run, 1 sizeSingle run, flex, 1st reducerTrunk-branch, 2-3 sizesFull trunk with tees, flex choiceFull palette or multi-fault diagnostic
Time (per zone)None (no timer)120s150s180s240s
LocationResidentialResidentialResidential/CommercialCommercial/InstitutionalIndustrial/Mixed-Use
ModeTutorialStandardStandardStandard + Diagnostic (L8)Diagnostic (L10, L12) + Standard (L11)

Teaching Progression

L0:  Full game flow — drag, place, flow test, trap concept (P-trap / S-trap) (one mechanic only)
L1:  Rotation + route choice (short vs long), flex vs rigid efficiency trade-off
L2:  Reducer placement strategy, supply vs drain distinction
L3:  Tight inventory — must plan route before building
L4:  Multi-size routing, first tee fork-and-rejoin branch
L5:  Clean-out spatial constraint, structural clearance activation
L6:  Same-size-wrong-type decoys, efficiency vs ease trade-off
L7:  Full fork-and-rejoin branching in both zones, shared inventory
L8:  DIAGNOSTIC — unique subtle faults (rotation, sizing, compliance)
L9:  Compliance rule conflicts — rules interact and constrain each other
L10: DIAGNOSTIC — remove excess components, identify subtle sizing errors
L11: Multi-branch inventory management, genuinely tight budget
L12: DIAGNOSTIC CAPSTONE — 5 faults per zone, locked correct pieces, all rules

Customer Cast

LevelCustomerVoicePersonality
0Maria Gonzalezfemale-midFriendly, grateful, patient — your first customer as an apprentice
1James Cartermale-midCasual, slightly impatient but cooperative
2Patricia Williamsfemale-highWorried, detail-oriented, asks good follow-ups
3Derek & Nina Howardmale-mid / female-midYoung couple, easygoing, excited about fixing up their first home
4David Chenmale-midOrganized renter, knows what he wants from the remodel
5Sarah Mitchellfemale-midProfessional office manager, values efficiency
6Robert Taylormale-lowRestaurant owner under health code pressure, gruff but fair
7Angela Riverafemale-midSchool facilities director, tight deadline, community-minded
8Marcus Johnsonmale-midHome inspector, professional peer, matter-of-fact
9Lisa Parkfemale-highHospital facilities manager, zero-tolerance, precise
10Thomas WrightgruffCondo property manager, frustrated, managing multiple complaints
11Karen Leefemale-midPlant operations manager, technical, expects expertise
12Michael Brownmale-lowGeneral contractor, final sign-off, career-defining moment

Scoring

Connection Challenge Scoring (per zone, max 1000)

Multi-factor weighted scoring via calculateConnectionChallengeScore:

FactorWeightCalculation
Component Accuracy30%correctComponents / totalRequired
Connection Quality20%validConnections / totalConnections
Flow Efficiency20%Product of all component efficiencies along the path
Compliance15%complianceChecksPassed / totalChecks
Speed15%timeRemaining / timeLimit (always 1.0 in practice)
Rework PenaltydeductionEscalating: first 2 removes free, then -25, -50, -100 per remove
Par Bonusup to +100Awarded when placedCount <= parCount (optimal component count)

Prep Phase Scoring

Uses shared calculateWeightedScore with 20% completion / 50% accuracy / 30% time weights.

Level Score

Sum of all non-dispatch phase scores from both zones. Max level score = PHASE_MAX_SCORE × totalScoredPhases where scored phases = zone 1 non-dispatch phases + zone 2 phases (from connection-challenge onward). Varies by level (2000–5000).

Platform Score

Cumulative model — sum of all level bests. multiplier: 1 always.

Stars (per difficulty, ratio-based)

Stars use score-to-max ratio thresholds (matching Circuit Breaker and Trades Build Off) combined with accuracy requirements:

Difficulty3-star ratio / accuracy2-star ratio / accuracy
Easy90% / 95%65% / 80%
Medium85% / 90%60% / 80%
Hard80% / 85%55% / 70%
Expert75% / 75%50% / 60%

Grade Thresholds

Both minimum score AND minimum accuracy must be met (same base threshold table as Pipe Runner, scaled by scoredPhaseCount per level — see getGradeThresholds(difficulty, level)).

Competency Coverage

AreaWhere Taught
Basic SafetySafety Scan phase
PPE SelectionGear Up phase
Tool IdentificationTool Match phase
TroubleshootingDispatch questions, diagnostic fix-it levels
Plumbing BasicsPipe fitting selection, slope logic, trap requirement (P-trap / S-trap)
HVAC BasicsDuct sizing, trunk-branch layout, efficiency optimization
Blueprint ReadingBlueprint panel with difficulty-scaled detail
Professional CommunicationDispatch conversation
System ContinuityFlow test simulation with visual particle animation
Slope/Grade LogicPlumbing slope validation (uphill = failure)
Code CompliancePost-flow compliance checklist with educational explanations
Measurement & SizingMeasurement quick-check phase (Medium+)

Technical Architecture

Key Files

AreaFile
Typesgames/flow-state/types.ts
Configgames/flow-state/config.ts
Scoringgames/flow-state/scoring.ts
Storegames/flow-state/store.ts
Phase Metagames/flow-state/phase-meta.ts
Barrelgames/flow-state/index.ts
Levelsgames/flow-state/content/levels.ts
Image Promptsgames/flow-state/content/image-prompts.ts
Component Registrygames/flow-state/phases/connection-challenge/component-registry.ts
Component Imagesgames/flow-state/phases/connection-challenge/component-images.ts
Grid Logicgames/flow-state/phases/connection-challenge/grid.ts
Connection Validatorgames/flow-state/phases/connection-challenge/connection-validator.ts
Flow Simulationgames/flow-state/phases/connection-challenge/flow-simulation.ts
Compliance Checkergames/flow-state/phases/connection-challenge/compliance-checker.ts

UI Components

ComponentFilePurpose
Connection Challenge Phasephases/connection-challenge/connection-challenge-phase.tsxMain orchestrator: DnD context, grid state, flow test, compliance overlay
Placement Gridphases/connection-challenge/components/placement-grid.tsxResponsive grid with zoom/pan, ResizeObserver cell sizing
Placement Cellphases/connection-challenge/components/placement-cell.tsxIndividual cell: droppable, SVG pipe rendering, flow particles, issue badge
Component Palettephases/connection-challenge/components/component-palette.tsxAccordion-grouped draggable component tray
Compliance Panelphases/connection-challenge/components/compliance-panel.tsxPost-flow pass/fail checklist overlay
Blueprint Panelcomponents/blueprint-panel.tsxModal reference diagram with difficulty-scaled detail
Phase Runnercomponents/phase-runner.tsxDynamic import registry for all phase playfields
Task Selectorcomponents/task-selector.tsxDual-zone picker (plumbing/HVAC)
Level Listcomponents/level-list.tsxLevel selection grid with progress

Shared Components Used

  • LevelCard, Countdown, PauseMenu, ResultsScreen, SceneCard, PhaseCompleteCard
  • GameTimerRing, useGameCountdown, GameOverlayPanel
  • TapSelectPlayfield, MultiSelectPlayfield, CardJudgePlayfield, McqPlayfield
  • DispatchPlayfield (from lib/mini-games/dispatch/)
  • GameDndProvider (from lib/dnd/)

Image Assets

Component palette thumbnails use SVG icons from public/games/flow-state/components/. Grid cells render SVG pipe shapes procedurally (not image-based) for pixel-perfect tiling and rotation.

AI-generated assets (via @repo/image-gen):

  • Customer portraits: removeBackground: true, trim: true
  • Scene backgrounds: full-scene images
  • Blueprint diagrams: technical style
  • Palette icons: dark-background flat vector icons

Generate: cd apps/games && bun run generate:images:flow-state

Persistence

Storage key: flow-state-state

Save data shape:

{
  levelProgress: {
    level_1: { unlocked, bestScore, stars, bestAccuracy, attempts, completedAt },
    ...
  },
  lastPlayedLevel: number
}

Routing

/flow-state/              → Menu
/flow-state/levels/       → Level selection (13 levels: tutorial + 12 campaign)
/flow-state/play/[level]/ → Gameplay (level = 1-13)
/flow-state/practice/     → Practice mode selection
/flow-state/practice/plumbing/ → Practice plumbing (no timer)
/flow-state/practice/hvac/     → Practice HVAC (no timer)

Practice Mode

Practice levels (parTimeSeconds: 0) skip the timer, use generous inventories, and have empty targetLayout so the "X placed" counter shows count only (no denominator). Practice uses useGameStore.setState directly instead of the normal level flow.