← Back
Play

Circuit Breaker

A service-call-driven electrical game where each level is a job dispatched to the player. The core loop is: receive a customer complaint, prep for the job, then wire, fix, or diagnose a circuit under time pressure. The circuit challenge is the main event (~70% of gameplay time), supported by a short prep phase and an unscored customer dispatch narrative. Features a three-outcome breaker toggle mechanic (works / trips / incomplete) with a load device visual that activates when the circuit is correct.

Micro-credential: Electrical Systems Specialist

Game Flow

Menu → Level Selection → Dispatch Board → Customer Call → [Scene Card] → Prep Phase → [Scene Card] → Circuit Challenge → Job Report (Results)
  • Menu: Hero screen with how-to-play instructions and a Play button
  • Level Selection: 20 levels grouped by difficulty (Easy/Medium/Hard/Expert). Shows stars, best score, skills tags, and cumulative total
  • Dispatch Board: Themed level intro — incoming service call with customer info, job location, problem summary, difficulty, skills tags, stats. "Answer the Call" button (user-controlled)
  • Customer Call: Unscored narrative phase. Customer speech bubble describes the problem. Player picks a diagnostic question from 3 options. Customer responds. Best question reveals a contextual hint for the circuit challenge. "Head to the Job" button (user-controlled)
  • Scene Card: Atmospheric transition between phases — fullscreen illustration with brief text and a "Continue" button (user-controlled, never auto-advance)
  • Prep Phase: One short scored phase per level — Gear Up (PPE selection), Tool Match (task-to-tool matching), or Safety Scan (hazard identification). Rotates per level to teach different skills without stacking MCQs
  • Circuit Challenge: The main event. Wire a circuit from a blueprint (Build), compare wiring to a diagram and fix errors (Match & Fix), or use a virtual multimeter to diagnose faults (Diagnose). Full-screen interactive workspace. Scored
  • Job Report: Results screen themed as a completed service report. Score, grade, breakdown, replay/next/exit

Unlock Logic

  • Level 1 always unlocked
  • Completing any level unlocks the next (linear progression)

Gameplay

Dispatch (Unscored Narrative Phase)

The dispatch is a two-step interaction that frames the level's story and teaches diagnostic communication skills without scoring pressure.

Step 1 — Dispatch Board (acts as LevelIntro):

ElementDescription
Header"INCOMING SERVICE CALL" with phone/alert animation
CustomerAvatar (AI-generated portrait) + name
LocationSetting tag: "Residential — Kitchen", "Commercial — Office Floor", etc.
Problem1-2 sentence customer complaint
StatsDifficulty badge, circuit complexity indicator, time limit
Skills2-4 skills tags from the level's learning objectives
TipsHow-to-play tips (expandable, same pattern as other games)
Action"Answer the Call" button

Uses the shared LevelIntro component with a themed skin. All elements are visible before the player advances — no auto-advance.

Step 2 — Customer Call:

A conversational screen with the customer's portrait and a speech bubble containing more detail about their problem. Below the speech bubble, three diagnostic questions appear:

  • Best question: Narrows down the root cause. Customer responds with useful context that becomes a hint during the circuit challenge (displayed on the blueprint reference panel).
  • Decent question: Somewhat helpful. Customer gives a partial response. No hint.
  • Poor question: Doesn't narrow the cause. Customer gives a vague response. No hint.

After the customer responds, a "Head to the Job" button appears. The player reads the response and advances when ready.

Example (Level 12 — Flickering Lights):

Customer: "The kitchen lights keep flickering. It's been happening for about a week."

OptionQualityCustomer Response
"Do they flicker when you turn on a specific appliance?"Best"Now that you mention it, they flicker every time I use the microwave." → Hint: "Shared circuit — check kitchen circuit loading"
"How old is the wiring in your house?"Decent"The house was built in the 90s, so maybe 30 years?"
"What kind of light bulbs do you have?"Poor"Just regular LEDs, nothing fancy."

The dispatch teaches the "asking the right questions" skill from the ABC Skills GPS without the pressure of scoring. The reward is informational — better questions = more context = easier circuit challenge.

Scene Transitions

Between phases, a scene card appears — a fullscreen or hero illustration with:

  • A brief heading ("Arriving at the Site", "Opening the Panel", "Checking Your Tools")
  • 1-2 lines of contextual text (optional tip related to the next phase)
  • A "Continue" button (user-controlled, never auto-advance)

Scene cards use GameOverlayPanel with a scene illustration background. They are functionally equivalent to TBO's PhaseTransition component but themed as job-site arrival moments rather than station transitions.

Each level has 2 scene cards:

  1. Before the prep phase (e.g., "Arriving at the job — Let's check your gear")
  2. Before the circuit challenge (e.g., "Opening the panel — Check the blueprint and wire it up")

Prep Phases (Shared)

Each level includes exactly one short prep phase. These are reused from the shared phase library (being extracted from TBO as part of the globalization effort). The prep phase rotates across levels so students encounter each type multiple times without any single level feeling like a quiz marathon.

Prep TypeMechanicDurationUsed In
Gear UpTap-to-select correct PPE from a grid. Insulated gloves, safety glasses, arc flash suit, face shield. Decoys scale with difficulty20-30sLevels 1, 4, 7, 10, 13, 16, 19
Tool MatchMulti-select tools and materials for the job card. Wire strippers, multimeter, voltage tester, correct wire gauge20-30sLevels 2, 5, 8, 11, 14, 17, 20
Safety ScanCard-based judgment — identify electrical hazards (exposed wires, water near outlets, overloaded circuits). Tap SAFE or HAZARD20-30sLevels 3, 6, 9, 12, 15, 18

Prep phases are scored (0-1000) using the shared phase scoring formula. They're short by design — the circuit challenge is the star.

Circuit Challenge (Core Mechanic)

The circuit challenge is the game's signature phase. It occupies 60-70% of each level's gameplay time and carries the bulk of the scoring weight. The workspace is rendered with PixiJS for drag-based wire routing, particle effects, and smooth zoom/pan on complex panels. UI chrome (timer, wire tray, breaker toggle, blueprint panel) is React/DOM overlaid on the canvas — same architecture split as TBO's site walk.

Workspace Layout

┌─────────────────────────────────┐
│ [📋 Blueprint]  Timer  [⏸ ][?] │  React overlay: toggleable blueprint, timer, pause
├─────────────────────────────────┤
│                                 │
│      ┌─────┐     ┌─────┐  💡   │  PixiJS canvas: device sprites with terminal hit zones
│      │ ● H │     │ ● H │       │  Wire connections rendered as PixiJS Graphics paths
│      │ ● N │─────│ ● N │       │  Load device (light bulb, outlet indicator, fan)
│      │ ● G │     │ ● G │       │  Particle effects for breaker test / trip
│      └─────┘     └─────┘       │  Pinch-to-zoom + drag-to-pan (Hard/Expert)
│         PANEL       OUTLET     │
│                                 │
├─────────────────────────────────┤
│ [■ BLK][■ WHT][■ GRN][■ RED]   │  React overlay: wire color selection buttons
│                                 │
│    [ ⚡ Breaker ON ] or         │  React overlay: breaker toggle (ON/OFF)
│    [ ✓ Complete Job ]           │  React overlay: appears after successful test
└─────────────────────────────────┘
LayerTechnologyContents
Canvas (PixiJS)usePixiApp + CircuitRendererDevice sprites, terminal hit areas, wire drag routing, load device indicator, breaker test particle flow, breaker trip sparks, multimeter probe glow, zoom/pan
HUD overlay (React/DOM)Standard componentsTimer ring, wire tray buttons, breaker toggle, "Complete Job" button, breaker trip counter, "Breaker ON" badge, phase indicator, pause button
Panels (React/DOM)Standard componentsBlueprint reference sidebar/overlay, math prompt MCQs, multimeter readings log

Desktop: Blueprint reference panel is a persistent sidebar (left). Canvas center. Wire tray and breaker toggle bottom.

Mobile: Blueprint reference is a toggleable top panel (tap to expand/collapse). Canvas fills the screen. Wire tray and breaker toggle are fixed at the bottom. Pinch-to-zoom enabled on Medium+ levels.

Devices

Each device is a PixiJS Container (sprite group) with child sprites for the device body, terminal hit zones, and labels:

DeviceTerminalsIntroduced
Duplex OutletHOT (brass), NEUTRAL (silver), GROUND (green)Level 1
Single-Pole SwitchCOMMON, SWITCHED-HOT, GROUNDLevel 2
Breaker PanelHOT-BUS, NEUTRAL-BAR, GROUND-BAR + individual breaker slotsLevel 3
GFCI OutletLINE-HOT, LINE-NEUTRAL, LOAD-HOT, LOAD-NEUTRAL, GROUNDLevel 6
Ceiling FanFAN-HOT, LIGHT-HOT, NEUTRAL, GROUNDLevel 7
Weatherproof BoxSame as Duplex Outlet terminals, outdoor-rated enclosureLevel 9
3-Way SwitchCOMMON, TRAVELER-1, TRAVELER-2, GROUNDLevel 11
240V Outlet (NEMA 14-50)HOT-A (black), HOT-B (red), NEUTRAL (white), GROUND (green)Level 13
Junction BoxWire-nut splice points (grouped terminals)Level 16
Sub-PanelMAIN-HOT-A, MAIN-HOT-B, MAIN-NEUTRAL, MAIN-GROUND + branch breakersLevel 16

Device bodies are programmatic PixiJS Graphics objects with per-type styling (dark fill for panels, light beige for outlets, etc.) and interior art (outlet slots, panel bus bars, switch rockers, GFCI buttons) drawn at subtle alpha. Each device has a header strip with the device label. Terminals render as screw-like Graphics circles with NEC-accurate coloring (brass for hot, silver for neutral, green for ground) and a connected/unconnected visual state. Terminals are centered vertically within the device body.

Wire Colors (NEC Conventions)

ColorFunctionTaught Via
BlackHot (ungrounded conductor)Level 1+
WhiteNeutral (grounded conductor)Level 1+
Green / BareGround (grounding conductor)Level 1+
RedSecond hot (240V circuits, travelers, fan light)Level 7+
BlueTraveler (commercial applications)Level 17+

Difficulty scaling for wire selection:

  • Easy: Wire color auto-selected based on terminal type. Player just connects terminals. Teaches spatial relationships without color confusion.
  • Medium: Wire tray active. Player must select the correct color before connecting. Wrong color on breaker test = breaker trip with explanation ("Black connects to hot terminals, not neutral").
  • Hard/Expert: Full wire selection required. Tray may include decoy colors (e.g., wrong gauge wire options). NEC color conventions are critical.

240V circuits (Level 13+):

Standard 120V circuits use one hot conductor + neutral. 240V circuits use two hot conductors from opposite bus bars in the panel — each carries 120V relative to neutral, combining for 240V between them. A 2-pole breaker occupies two adjacent slots and trips both simultaneously.

  • Pure 240V loads (baseboard heaters, well pumps): HOT-A (black) + HOT-B (red) + GROUND (green). No neutral needed.
  • 120/240V loads (dryers, ranges, EV chargers): HOT-A (black) + HOT-B (red) + NEUTRAL (white) + GROUND (green). The NEMA 14-50 receptacle used for EV chargers follows this 4-wire configuration.

The 240V Outlet device type has terminals HOT-A, HOT-B, NEUTRAL, and GROUND. The breaker panel device gains a second hot bus connection (HOT-BUS-B) for 240V circuits.

Interaction Model (Drag-to-Route)

The core interaction is press → drag → release. All pointer events are handled at the stage level using distance-based hit detection (terminalAt(), wireAt()), not per-object PixiJS events. This ensures reliable interaction across all browsers and devices.

  1. Select a wire color: Tap a color in the React wire tray (Medium+) or skip this step (Easy, auto-selected via resolveColor() which looks up the target connection). Wire tray shows color buttons with labels (BLK, WHT, GRN, RED, BLU).
  2. Press near a terminal: Touch/click within TERM_HIT_R (28px) of a terminal. The origin terminal scales up (1.25x). All valid target terminals (on other devices) show pulsing blue glow rings. A wire "lead" appears attached to the pointer — a PixiJS Graphics bezier that redraws every frame.
  3. Drag across the workspace: The wire follows the finger/cursor in real-time, curving with a subtle S-curve and gentle gravity sag. In auto-color mode the drag wire renders in neutral gray; in manual mode it uses the selected color. A snap indicator ring appears around the nearest valid target terminal when the pointer approaches.
  4. Release near a valid terminal: Wire is placed instantly as a permanent Graphics bezier in the wire layer. Connection dots mark both endpoints. The terminal screw visuals update to show a "connected" state (green center dot, no slot line).
  5. Release on empty space: Drag cancelled, wire disappears. No penalty.
  6. Remove a wire: Single-tap on a placed wire (within WIRE_HIT_DIST of its bezier path) removes it instantly. Terminal visuals revert to unconnected state.
  7. Hover feedback: Cursor changes to "pointer" over terminals and wires. An amber ring highlights the hovered terminal even when not dragging.
  8. Breaker test: Tap the breaker toggle to flip it ON and test the circuit (see below). While breaker is ON, wire interaction is disabled (cursor shows not-allowed). Flip OFF to continue wiring.

Wires are rendered as PixiJS Graphics cubic bezier curves with 4 layers: color glow (wide, semi-transparent), shadow, main stroke (round caps), and highlight. Color-coded by wire type. Invalid connection attempts (same terminal, same device, duplicate connection) are silently rejected — no penalty.

The "Breaker Test" Moment

The breaker toggle is the game's signature interaction. Instead of a "submit answer" button, the player flips a breaker ON to test their circuit — just like a real electrician. The test produces one of three outcomes based on the validation result. All visual effects run in the PixiJS canvas layer.

Three-outcome model:

OutcomeConditionWhat HappensPenalty
Circuit worksAll connections correct, none wrongLoad device activates (light glows, fan spins, outlet indicator turns green). "Complete Job" button appears.None
Breaker tripsAny wrong connection presentSpark animation, camera shake, breaker auto-flips back to OFF. "+Xs BREAKER TRIP!" penalty. Player continues.Time penalty
Nothing happensMissing connections but nothing wrongLoad stays dead. Breaker stays on (it's safe, just incomplete). No animation. Player observes "it's not working yet" and flips back to OFF to continue wiring.None

This teaches a real electrical concept: an incomplete circuit is not dangerous — it just doesn't work. A mis-wired circuit IS dangerous — it trips the breaker.

Wire locking: While the breaker is ON, wire interaction is disabled on the canvas. Cursor shows not-allowed. A "Breaker ON" badge appears in the HUD. The player must flip OFF before making changes.

On success (all connections correct — 2s animation):

  1. Load device activates (light bulb glows warm yellow, outlet indicator turns green, etc.)
  2. All wires tint green
  3. 3 electricity dots per wire travel along the bezier paths (staggered sizes, trailing afterglow)
  4. Wires pulse with oscillating alpha (glow effect, 500ms)
  5. 24-particle radial burst from canvas center (green + yellow, expanding outward)
  6. Terminal dots flash green sequentially
  7. "POWER ON!" text scales in at center
  8. onBreakerTest callback fires immediately (score uses time at "Complete Job" press, not breaker flip)
  9. "Complete Job" button appears — player confirms completion

On trip (any connection wrong — 1.5s animation):

  1. Canvas overlay darkens (alpha 0→0.6 in 100ms)
  2. Camera shake: stage position oscillates for 300ms via sine wave, decaying to zero
  3. 20 spark particles burst from the midpoint of the first wrong wire (4 color variants: orange, yellow, white, deep orange) with gravity decay
  4. Red glow strokes drawn along wrong wire bezier paths
  5. Wrong wires flash red/white rapidly (6 blinks in 550ms)
  6. "BREAKER TRIP!" text flashes at center
  7. Breaker auto-flips to OFF after animation completes
  8. "+Xs" penalty badge appears in the React HUD (animated bounce, auto-dismisses after 2s)
  9. Timer adds penalty seconds to elapsed time via penaltyMsRef added to subtractElapsedMs
  10. Player continues working. Can flip breaker ON again when animation finishes

On incomplete (only missing, no wrong): No animation. The breaker stays on but nothing works. The load device remains dim/off. The player can flip the breaker OFF and continue wiring. No penalty is applied.

Multiple breaker test attempts are allowed. Each wrong attempt = 1 breaker trip.

Build Mode

The player wires a circuit from scratch following a blueprint reference.

  • Blueprint panel shows the target wiring diagram
  • Workspace starts empty — devices are placed but no wires connected
  • Goal: Connect all required wires to match the blueprint
  • Breaker test: Flip breaker ON to test all connections at once

Used in: Levels 1-7, 9, 11, 13, 16, 18

Complexity scales from 3 connections (Level 1, simple outlet) to 12+ connections (Level 16, sub-panel with branch circuits).

Match & Fix Mode

The player inspects a pre-wired circuit, compares it to the blueprint, and corrects errors.

  • Blueprint panel shows the correct wiring diagram
  • Workspace starts with a pre-wired circuit (some connections wrong)
  • Goal: Identify mismatches and fix them — remove wrong wires, add correct ones
  • Breaker test: Flip breaker ON to test the corrected circuit

Used in: Levels 8, 10, 14, 17

Teaches blueprint reading and error identification. The number of errors scales with difficulty (2 errors on Medium, 3-4 on Expert).

Diagnose Mode

The player uses a virtual multimeter to find faults in a broken circuit, then fixes them. This mode has a two-phase workflow: Probe (take readings to find the fault) then Fix (correct the wiring and test).

  • Blueprint panel shows what the circuit SHOULD look like
  • Workspace shows a pre-wired circuit with hidden faults (missing connections, wrong connections, or broken wires)
  • Two-phase HUD: A Probe | Fix | Test step indicator replaces the wire tray. The player starts in Probe mode and switches to Fix mode once they've identified the fault
  • Goal: Take measurements to isolate faults, then fix the wiring (drag new connections, remove bad ones), then test with the breaker

Used in: Levels 12, 15, 19, 20

Probe mode workflow:

The circuit starts in Probe mode. Wire interaction (drag, tap-to-connect) is completely disabled. Only terminal probing works:

  1. Tap Terminal A on the canvas → red probe sprite (labeled "A") appears on the terminal
  2. A pulsing "A" badge appears on the Probe button in the HUD to indicate the player should tap a second terminal
  3. Tap Terminal B → black probe sprite (labeled "B") appears. The reading is looked up from the level's multimeterReadings config and displayed as a floating green label above the probed area (e.g., "120 V", "0 Ω", "OL")
  4. The reading is logged in the Blueprint panel's "Multimeter Log" section with a numbered entry. A badge count on the Blueprint button flashes to indicate a new reading was added
  5. Tapping a third terminal clears the existing probes and starts a new reading cycle
  6. If no reading is defined for the probed terminal pair, "OL" (open line) is displayed

Reading lookup: lookupReading() is a pure function in circuit-validator.ts that searches config.multimeterReadings for a matching terminal pair (direction-independent — A→B and B→A both match). Returns { value, unit, found }. Tested via unit tests.

Fix mode workflow:

The player switches to Fix mode via the Fix button in the HUD. Probe sprites are cleared. Normal wire interaction resumes (drag-to-connect, tap-to-connect, wire removal). The wire color tray appears below the mode buttons.

After fixing the wiring, the player flips the breaker ON to test — same three-outcome model as Build and Match & Fix modes.

How-to-play walkthrough:

A dedicated HowToPlayDiagnose walkthrough (4 steps) auto-opens on the first Diagnose level encounter, gated by cb-htp-diagnose-seen localStorage key. Steps:

  1. "This circuit has a problem" — explains the pre-wired fault concept
  2. "Probe with the multimeter" — tap two terminals to get a reading
  3. "Spot the fault" — interpret abnormal readings in the Blueprint log
  4. "Fix and test" — switch to Fix mode, correct wiring, breaker test

The "?" help button in the HUD reopens the Diagnose walkthrough (not the Build walkthrough) when in Diagnose mode. Timer pauses while the walkthrough is open.

Level config for Diagnose mode:

circuitChallenge: {
  mode: "diagnose",
  autoSelectColor: false,
  availableWireColors: ["black", "white", "green"],
  devices: [...],
  preWiredConnections: [...],   // The faulty wiring the player sees on load
  targetConnections: [...],     // The correct wiring (the answer)
  multimeterReadings: [         // Lookup table for probe readings
    {
      terminalA: { deviceId: "panel", terminalId: "hot-bus" },
      terminalB: { deviceId: "outlet", terminalId: "hot" },
      reading: "0",
      unit: "Ω",
    },
    // ... all probeable terminal pairs
  ],
}

Ohm's Law integration (Expert — planned):

During Diagnose mode on Expert levels, inline math prompts appear within the workspace as cards:

  • "You read 120V across a 15Ω element. What current flows?" → MCQ (8A — V=IR)
  • "A 1500W heater on a 120V circuit draws how many amps?" → MCQ (12.5A — P=VI)
  • "The breaker is 20A rated. Can this circuit handle a 2400W load at 120V?" → Yes/No (No — 2400/120 = 20A, at limit)

Correct answers unlock additional diagnostic context. Wrong answers don't penalize the score but the student loses the contextual help. This integrates math naturally into the diagnostic flow rather than as a separate quiz phase.

Breaker Trip Mechanic

The breaker trip is the game's core penalty system. It's the equivalent of a "wrong answer" but delivered as a visceral, electrically-themed experience.

Trigger: Flip breaker ON with any incorrect connections (wrong wires or wrong wire colors). Incomplete circuits (missing connections only) do NOT trigger a trip — they simply don't work.

Consequences:

  • +5 seconds added to elapsed time (affects time score component)
  • Counts against accuracy (accuracy = correct / (correct + trips))
  • Both effects compound — same double-hit pattern as TMR's wrong activation

Animation (~1.5 seconds total, all in PixiJS canvas):

  1. Canvas overlay sprite darkens the scene (alpha 0→0.7 in 100ms)
  2. Spark particle burst at the fault point — orange/yellow particles with velocity decay
  3. "BZZT" electrical pop SFX
  4. Breaker device sprite plays flip animation
  5. Wrong wire Graphics objects flash red with rapid glow pulses (3× in 500ms)
  6. Canvas overlay brightens back (alpha 0.7→0 in 300ms)
  7. "+5s BREAKER TRIP" badge appears in the React HUD overlay

Fast enough to not kill momentum. Dramatic enough to feel consequential. The particle burst is the signature visual — it should feel like a real spark, not a CSS opacity change.

Level Structure

21 levels: 20 across four difficulty tiers (5 per tier) plus a bonus capstone level. Each level has exactly 3 phases: Dispatch (unscored) → Prep (scored) → Circuit Challenge (scored).

Skills Tags

Each level displays 2-4 skills tags on the LevelCard and Dispatch Board. Tags map to the ABC Skills GPS competency areas:

Safety · PPE · Hazard ID · Tool ID · Tool Use · Basic Wiring · Basic Theory · Circuits · NEC Code · GFCI · Math · Ohm's Law · Troubleshooting · Multimeter · Diagnostics · Blueprints · Routing · Communication · Commercial · Professional · 240V

Level Table

Easy (Levels 1-5) — "First Week on the Job": All Build mode. Auto-color wires. Residential settings.

IDBadgeService CallDifficultyPrep PhaseCircuit ModeSkills Tags
1TutorialDead OutletEasyGear UpBuild: 3-wire outlet (Panel → Outlet)Safety, PPE, Basic Wiring
2Level 1New Light SwitchEasyTool MatchBuild: Switch + light (Panel → Switch → Light)Tool ID, Basic Circuits
3Level 2Dedicated Microwave CircuitEasySafety ScanBuild: Dedicated 20A circuitHazard ID, Basic Theory
4Level 3Bathroom Fan + LightEasyGear UpBuild: Branching circuit (Panel → Switch → Fan + Light)Safety, Basic Circuits
5Level 4Bedroom Outlet RunEasyTool MatchBuild: Daisy chain (Panel → Outlet → Outlet)Tool Use, Basic Wiring

Medium (Levels 6-10) — "Getting Your Name Out There": Manual wire color selection. Match & Fix introduced.

IDBadgeService CallDifficultyPrep PhaseCircuit ModeSkills Tags
6Level 5GFCI Kitchen OutletMediumSafety ScanBuild: GFCI (LINE/LOAD chain)NEC Code, GFCI
7Level 6Ceiling Fan InstallMediumGear UpBuild: Fan/light dual switchesTool Use, Circuits
8Level 7Panel InspectionMediumTool MatchMatch & Fix: Panel vs diagramBlueprints, NEC Code
9Level 8Outdoor Patio CircuitMediumSafety ScanBuild: Outdoor GFCI + weatherproofNEC Code, Routing
10Level 9Kitchen Rewire CheckMediumGear UpMatch & Fix: Audit contractor workBlueprints, Hazard ID

Hard (Levels 11-15) — "Reputation Growing": Manual color + decoys. Diagnose mode introduced.

IDBadgeService CallDifficultyPrep PhaseCircuit ModeSkills Tags
11Level 10Three-Way Stairway SwitchHardTool MatchBuild: 3-way pair w/ travelersCircuits, Blueprints
12Level 11Flickering LightsHardSafety ScanDiagnose: Loose neutralTroubleshooting, Multimeter
13Level 12EV Charger InstallHardGear UpBuild: 240V circuit + 2-pole breakerNEC Code, 240V, Routing
14Level 13Handyman Wiring AuditHardTool MatchMatch & Fix: Residential auditBlueprints, NEC Code
15Level 14Storm Damage: Dead CircuitsHardSafety ScanDiagnose: 2 faults, multi-roomDiagnostics, Multimeter

Expert (Levels 16-20) — "Going Pro": All skills stacked. Dense panels, commercial, Ohm's Law.

IDBadgeService CallDifficultyPrep PhaseCircuit ModeSkills Tags
16Level 15Workshop Sub-PanelExpertGear UpBuild: Sub-panel + branches + junction boxCircuits, Math, NEC Code
17Level 16Restaurant Kitchen AuditExpertTool MatchMatch & Fix: Commercial multi-circuitCommercial, Blueprints
18Level 17Office Lighting RetrofitExpertSafety ScanBuild: Multi-circuit commercialCommercial, Routing
19Level 18Apartment Building TroubleshootExpertGear UpDiagnose: Multi-fault + math promptsDiagnostics, Ohm's Law
20Level 19Full Service DiagnosticExpertTool MatchDiagnose: 3-4 faults + Ohm's LawDiagnostics, Ohm's Law, Professional

Bonus — "Master Electrician": Unlocked after completing all 20 levels. The capstone build.

IDBadgeService CallDifficultyPrep PhaseCircuit ModeSkills Tags
21Level 20Master Electrician Build-OutExpertSafety ScanBuild: Full bakery (240V + sub-panel + GFCI + 3-way + junction, 16 connections, 7 devices, all 5 wire colors)Circuits, NEC Code, 240V, GFCI, Professional

Mode Distribution

  • Build: 13 levels (IDs 1-7, 9, 11, 13, 16, 18, 21) — 62%
  • Match & Fix: 4 levels (IDs 8, 10, 14, 17) — 19%
  • Diagnose: 4 levels (IDs 12, 15, 19, 20) — 19%

Maximum gap between same-mode appearances: Match & Fix = 4 levels, Diagnose = 4 levels.

Progressive Mechanic Introduction

Level RangeNew MechanicsNew DevicesNew Wire Colors
1-5 (Easy)Build mode, auto-color, drag-to-connect, breaker test, branching circuits, daisy chainingDuplex Outlet, Single-Pole Switch, Breaker PanelBLK, WHT, GRN (auto-selected)
6-10 (Medium)Manual wire color selection, Match & Fix modeGFCI Outlet, Ceiling Fan, Weatherproof BoxRED (Level 7)
11-15 (Hard)Diagnose mode, multimeter, decoy wire colors, 240V wiring, traveler wiring3-Way Switch, 240V Outlet (NEMA 14-50)— (manual + decoys)
16-20 (Expert)Ohm's Law math prompts, zoom/pan, commercial contextSub-Panel, Junction BoxBLU (Level 17)
21 (Bonus)All mechanics stacked, capstone build with every device type and all 5 wire colorsAll device types combinedAll 5 colors required

Narrative Arc

The customer cast follows a career progression:

  • Easy: Everyday residential clients with relatable, low-stakes problems. Humor-forward (Marcus's dying phone, Darnell's microwave obsession, Tyler and Jordan's gaming setup needs more outlets)
  • Medium: More trusting clients, code-compliance themes. First-time homeowners (Priya), real estate prep (Brooke), checking other people's work (Helen)
  • Hard: Specialized calls, referrals, institutional clients. A school coach (Davis), an EV owner (Dr. Foster), auditing amateur wiring (Greg), storm damage recovery (the Johnsons)
  • Expert: Commercial and multi-unit. A retired carpenter building his dream workshop (Uncle Pete), a restaurant owner with the health inspector coming (Chef Rosa), an office energy audit (Kwame), overwhelmed property managers (James, Diane)
  • Bonus: The capstone. A GC building out a bakery/cafe from scratch (Elena) — every device type, every wire color, the ultimate "reputation" job

Level Details

Tutorial — "Dead Outlet" (ID 1)

Customer: Marcus — "My bathroom outlet is completely dead."

Prep: Gear Up — select insulated gloves, safety glasses. Decoys: regular work gloves, sunglasses, flip-flops, sneakers.

Circuit: Build Mode — Wire a standard duplex outlet (Panel → Outlet). 3 connections: black→HOT (brass), white→NEUTRAL (silver), green→GROUND (green screw). Wire color auto-selected (Easy). Blueprint shows a simple outlet wiring diagram.

Scene cards: "Arriving at the Job" → "Opening the Outlet Box"

Teaching focus: This is the tutorial. A multi-step how-to-play walkthrough modal (HowToPlayCircuit) shows on first entry to the circuit challenge phase (gated by localStorage cb-htp-seen key). The walkthrough explains wire color selection, drag-to-connect, blueprint reference, wire removal, the breaker toggle, and breaker trip penalties. Timer pauses while the modal is open. A "?" help button in the HUD allows replaying the walkthrough.

Level 2 — "Dedicated Microwave Circuit" (ID 3)

Customer: Darnell Williams — "Every time I run my microwave and the toaster at the same time, the breaker trips."

Prep: Safety Scan — identify hazards: overloaded kitchen outlet strip with multiple high-wattage appliances (HAZARD), properly grounded outlet (SAFE), microwave plugged into shared circuit (HAZARD), GFCI outlet near sink (SAFE).

Circuit: Build Mode — Wire a dedicated 20A circuit from the panel to a new kitchen outlet. 4-5 connections. Introduces the concept of dedicated circuits and breaker amperage ratings. Blueprint highlights the 20A breaker slot and dedicated wire run.

Scene cards: "Arriving at the Kitchen" → "Opening the Panel"

Teaching focus: Why dedicated circuits exist. High-wattage appliances (microwaves, toasters, space heaters) need their own circuit to avoid overloading shared wiring. The narrative connects directly to the Build action — the customer's problem is the lack of a dedicated circuit, so the player installs one.

Level 5 — "GFCI Kitchen Outlet" (ID 6)

Customer: Priya Patel — "I just bought this house and the home inspector flagged the kitchen outlets."

Prep: Safety Scan — identify hazards: non-GFCI outlet within 6 feet of kitchen sink (HAZARD), properly grounded outdoor outlet (SAFE), missing outlet cover plate (HAZARD), correctly wired GFCI in bathroom (SAFE).

Circuit: Build Mode — Wire a GFCI outlet with LINE and LOAD connections (Panel → GFCI LINE → Outlet LOAD). 5-6 connections. First level with manual wire color selection. Blueprint clearly labels LINE vs LOAD terminals.

Teaching focus: GFCI protection (NEC 210.8) and LINE vs LOAD wiring. The most common GFCI installation error is swapping LINE and LOAD — if the player does this, the circuit will test as "incomplete" (GFCI non-functional) rather than trip, which is electrically accurate.

Level 7 — "Panel Inspection" (ID 8)

Customer: Brooke Adams (real estate agent) — "I need a panel inspection cleared before the sale closes on Friday."

Prep: Tool Match — select voltage tester, flashlight, clipboard/checklist, screwdriver. Decoys: wire strippers, conduit bender, soldering iron.

Circuit: Match & Fix Mode — First appearance of this mode. Panel is pre-wired with 2 errors (wrong wire color on a neutral, missing ground connection). Player compares the wiring to the blueprint, identifies mismatches, removes wrong wires, and adds correct ones. 5-6 connections total, 2 faults.

Teaching focus: Blueprint reading and error identification. Teaches students to systematically compare actual wiring against the reference diagram — a critical skill for panel inspections.

Level 10 — "Three-Way Stairway Switch" (ID 11)

Customer: Coach Davis — "I want to control the gym stairway light from both the top and bottom of the stairs."

Prep: Tool Match — select 3-way switches, 14/3 Romex (for travelers), wire strippers, voltage tester. Decoys: single-pole switch, 14/2 wire, pipe wrench.

Circuit: Build Mode — Wire a 3-way switch pair. 7-8 connections including travelers (red wires). Blueprint shows standard 3-way wiring with COMMON and TRAVELER terminals labeled. Wire color selection required with decoy colors in the tray (Hard).

Diagnostic question hint: "Does the light work from either switch right now?" → "It only works from the bottom switch." → Hint: "The top switch may be a single-pole — check for missing traveler connections"

Level 11 — "Flickering Lights" (ID 12)

Customer: Carlos Mendez — "The kitchen lights keep flickering. It's been happening for about a week."

Prep: Safety Scan — identify hazards: overloaded outlet strip near sink (HAZARD), GFCI outlet in correct location (SAFE), exposed wire splice with no junction box (HAZARD), properly mounted smoke detector (SAFE).

Circuit: Diagnose Mode — First appearance. Pre-wired kitchen circuit with a loose neutral connection. Multimeter readings: 120V between hot and ground (correct), fluctuating 110-118V between hot and neutral (indicates bad neutral), 0Ω between neutral bar and ground bar at panel (correct). Student must identify the loose neutral at the outlet splice, tighten/reconnect it, and flip the breaker ON to test.

Teaching focus: Introduction to the multimeter and systematic diagnosis. The loose neutral is the #1 cause of flickering lights in real residential work — educationally accurate.

Level 12 — "EV Charger Install" (ID 13)

Customer: Dr. Aisha Foster — "I just got an electric car and I need a Level 2 charger in my garage."

Prep: Gear Up — select insulated gloves rated for 240V work, safety glasses, arc flash face shield, voltage tester. Decoys: standard work gloves, earplugs, dust mask.

Circuit: Build Mode — Wire a 240V circuit from the main panel to a NEMA 14-50 outlet in the garage. 8-9 connections using a 2-pole 50A breaker. Two hot conductors (black and red) carry 120V each relative to neutral, combining for 240V. Blueprint shows the 4-wire configuration: HOT-A (black), HOT-B (red), NEUTRAL (white), GROUND (green).

Teaching focus: 240V circuits. Unlike 120V circuits that use one hot + one neutral, 240V uses two hots from opposite bus bars in the panel. The 2-pole breaker trips both poles simultaneously. This is one of the fastest-growing residential electrical jobs due to EV adoption — topical and career-relevant.

Level 15 — "Workshop Sub-Panel" (ID 16)

Customer: Uncle Pete (Pete Kowalski) — "I'm building my dream workshop in the garage and I need real power out there."

Prep: Gear Up — full PPE for panel work (arc flash suit, face shield, insulated gloves, rubber mat). Decoys scale to near-miss quality (Expert).

Circuit: Build Mode — Wire a sub-panel fed from the main panel, plus 2-3 branch circuits. 10-12 connections including junction box splice points. Introduces the sub-panel rule: neutral and ground bars must be separate (bonded only at the main panel per NEC 250.32). Blueprint shows the 4-wire feeder and branch circuit routing.

Teaching focus: Sub-panel installation, neutral-ground separation, and junction box splicing. Complex routing with multiple devices.

Level 19 — "Full Service Diagnostic" (ID 20)

Customer: Building manager Diane Park — "Three different tenants are reporting electrical problems. None of it makes sense."

Prep: Tool Match — select multimeter, amp clamp, voltage tester, circuit tracer, safety glasses, insulated gloves. Decoys: pipe wrench, plumber's tape, stud finder.

Circuit: Diagnose Mode — Commercial panel with 3-4 faults across interconnected circuits. 14 connections across 6 devices. Requires systematic multimeter probing and Ohm's Law calculations. Inline math prompts: "Suite 103's laser printer draws 1800W at 120V. What current?" (15A). "20A breaker with 1000W heater — how much capacity remains?" (1400W). "120V across 8Ω heating element — what current?" (15A — I = V/R).

Level 20 — "Master Electrician Build-Out" (ID 21)

Customer: Elena Vargas (GC) — "I need the entire electrical system wired for my new bakery. Every circuit, every outlet, before the final inspection Monday."

Prep: Safety Scan — identify hazards in a new construction build-out site.

Circuit: Build Mode — Wire an entire bakery/cafe from scratch. 16 connections across 7 devices using all 5 wire colors. Four circuit groups: (1) 240V 50A oven circuit (NEMA 14-50, black + red + white + green), (2) Sub-panel feeder (black + white + green, neutral/ground separate), (3) GFCI outlet via junction box from sub-panel branch circuit, (4) Dining room lights with 3-way switch using blue commercial traveler. Every device type in the game appears: panel, sub-panel, junction box, 240V outlet, GFCI, 3-way switch, light fixture. This is the boss level — all skills stacked.

Scene cards: "Arriving at the Build-Out" → "Opening the Panel"

Difficulty Scaling

SettingEasyMediumHardExpert
Connections per circuit3-65-77-910-14
Wire color selectionAutoManualManual + decoysManual + decoys
Breaker test feedbackHints shownWrong highlighted onlyWrong highlighted onlyWrong flash briefly
Faults (Diagnose mode)N/AN/A1-23-4
Math promptsNoneNoneRareRequired
Zoom / panDisabled (fits screen)EnabledEnabledRequired (dense panels)
Prep phase time30s30s25s20s
Circuit challenge time90s120s150s180s
Decoy quality (prep)ObviousPlausibleNear-missNear-miss

Scoring

Per-Phase Scoring

Same formula as TBO — each scored phase normalizes to 0-1000:

completionScore = (tasksCompleted / totalRequired) × 200       // 20%
accuracyScore   = (tasksCompleted / totalRequired) × 500       // 50% — clean ratio, trips don't reduce this
timeScore       = (timeRemaining / timeLimit) × 300             // 30% — trips reduce this via time penalty
phaseScore      = completionScore + accuracyScore + timeScore

For prep phases: tasksCompleted = correct PPE / tools / hazards identified. penaltyCount = wrong selections (passed to shared formula).

For circuit challenges: tasksCompleted = correct connections when "Complete Job" is pressed (or partial correct on timeout). penaltyCount = 0 (trips only cost time). On timeout, the validator runs against the player's current wires to award partial credit. Breaker trips only occur from wrong connections — incomplete circuits (missing connections only) carry no penalty.

Breaker Trip Penalty

Each breaker trip (failed breaker test) adds a time penalty that scales with difficulty:

DifficultyPenalty% of timer
Easy+5s5.6% of 90s
Medium+6s5.0% of 120s
Hard+8s5.3% of 150s
Expert+10s5.6% of 180s

Trips affect score through the time component only (30% weight). They do NOT double-dip into the accuracy formula. This keeps the penalty system simple and understandable: "trips cost time, time costs points."

Level Score

levelScore = prepPhaseScore + circuitChallengeScore    // max 2000

Every level produces the same max (2000) since every level has exactly 2 scored phases. Grade thresholds are fixed per difficulty.

Stars (Difficulty-Scaled)

Based on level score as percentage of max (2000):

Difficulty3 Stars2 Stars1 Star
Easy90%+65%+Completed
Medium85%+60%+Completed
Hard80%+55%+Completed
Expert75%+50%+Completed

Accuracy

accuracy = max(0, 100 - totalBreakerTrips × 15)

Grade Thresholds

Both minimum score AND minimum accuracy must be met:

GradeEasyMediumHardExpert
S1800 / 95%1750 / 90%1650 / 85%1500 / 75%
A1500 / 80%1450 / 75%1350 / 70%1200 / 60%
B1100 / 65%1050 / 60%950 / 50%850 / 40%
C700 / 40%650 / 35%600 / 25%500 / 15%
D0 / 0%0 / 0%0 / 0%0 / 0%

Platform Score

Cumulative score model. After each level, the sum of best scores across all completed levels is posted to the platform's score table. TNW_COMPLETE fires once on the player's first-ever level completion.

Competencies

Skill AreaWhere Taught
Basic electrical safetyGear Up (PPE), Safety Scan (hazards)
Identifying electrical hazardsSafety Scan, scene cards
Choosing correct PPEGear Up
Tool identification & proper useTool Match
Basic electrical theory (V/I/R)Diagnose mode, math prompts
Unit conversion & measuringMath prompts in Diagnose mode
Understanding circuitsBuild mode (all levels)
NEC code awarenessGFCI levels, wire color rules, outdoor requirements
Asking the right questionsDispatch diagnostic questions
Translating symptoms to issuesDispatch + Diagnose mode
Narrowing down root causesDiagnose mode (multimeter probing)
Professional communicationDispatch customer interaction
Reading wiring diagramsBlueprint reference panel (all levels)
Identifying installation mistakesMatch & Fix mode
Routing and organizing layoutsBuild mode on complex levels

Orchestrator Architecture

Phase Machine

menu → levelIntro → dispatch → phaseIntro → countdown → phaseActive → phaseComplete → [next or results]
FromEventTo
menuSTART_RUNlevelIntro
levelIntroACCEPT_JOBdispatch
dispatchHEAD_TO_JOBphaseIntro
phaseIntroBEGIN_COUNTDOWNcountdown
countdownBEGIN_PHASEphaseActive
phaseActiveCOMPLETEphaseComplete
phaseActivePAUSEpaused
phaseCompleteADVANCEphaseIntro (next phase) or results
pausedRESUME(previousPhase)
resultsSTART_RUNlevelIntro

Global transitions: RESTARTlevelIntro (requires currentLevel), RESET_MENUmenu.

Store uses createTransitionEngine from @/lib/stores. Pause time compensation uses computePauseCompensationMs.

Phase Structure Per Level

Every level has exactly 3 phases, 2 scored:

IndexPhaseScoredComponent Source
0DispatchNogames/circuit-breaker/phases/dispatch/
1Prep (Gear Up / Tool Match / Safety Scan)Yes@/lib/phases/* (shared)
2Circuit Challenge (Build / Match & Fix / Diagnose)Yesgames/circuit-breaker/phases/circuit-challenge/

The phase-runner loads components via a registry, same pattern as TBO. Prep phases are imported from the shared phase library. The Circuit Challenge and Dispatch are game-specific.

File Structure

games/circuit-breaker/
├── store.ts                      # Orchestrator Zustand store (createTransitionEngine)
├── config.ts                     # Scoring config, difficulty settings, timers, grade thresholds
├── types.ts                      # GamePhase, DeviceConfig, TerminalDef, WireConnectionDef, CircuitChallengeConfig, etc.
├── scoring.ts                    # calculatePhaseScore, calculatePhaseAccuracy (delegates to shared calculateWeightedScore)
├── phase-meta.ts                 # Phase display metadata (icons, names, taglines, howToPlay text)
├── index.ts                      # Barrel export
├── image-gen.config.ts           # Image pipeline config
├── phases/
│   ├── dispatch/                 # Customer call (unscored narrative)
│   │   └── dispatch-playfield.tsx # Multi-round conversation UI with speech bubbles + diagnostic questions
│   ├── gear-up.tsx               # Prep phase adapter — wraps shared TapSelectPlayfield
│   ├── tool-match.tsx            # Prep phase adapter — wraps shared MultiSelectPlayfield
│   ├── safety-scan.tsx           # Prep phase adapter — wraps shared CardJudgePlayfield
│   └── circuit-challenge/        # The main event (Build / Match & Fix / Diagnose)
│       ├── circuit-canvas.tsx    # React wrapper — mounts PixiJS canvas via usePixiApp, bridges React↔renderer via callbacksRef
│       ├── circuit-renderer.ts   # Single PixiJS class: layers, device rendering, wire interaction, breaker test animations, load device (all-in-one)
│       ├── circuit-challenge-phase.tsx  # Phase component — timer, wire tray (inline), HUD, how-to-play trigger, scoring
│       ├── circuit-validator.ts  # Pure function — graph matching (player connections vs target). Returns { correct, wrong, missing }
│       └── index.ts
├── components/                   # React UI (orchestrator chrome + overlays)
│   ├── phase-runner.tsx          # Renders active phase via dynamic import registry (next/dynamic, ssr: false)
│   ├── scene-card.tsx            # Transition illustrations with Continue button (GameOverlayPanel)
│   ├── dispatch-board.tsx        # Multi-step level intro (incoming call themed, tutorial vs standard variants)
│   ├── blueprint-panel.tsx       # Toggleable wiring diagram overlay — shows blueprint image, progress bar, dispatch hint
│   ├── how-to-play-circuit.tsx   # Multi-step GameOverlayPanel walkthrough (6 visual steps, localStorage gating, timer freeze)
│   ├── run-hud.tsx               # Top bar: phase label, breaker trip count, pause/restart buttons
│   ├── job-report.tsx            # Themed ResultsScreen wrapper
│   └── level-list.tsx            # 20-level grid with difficulty grouping, skills tags, stars, best score
├── hooks/
│   ├── use-game-actions.ts       # Persistence (wraps useGameActionsBase, level progress, cumulative score)
│   ├── use-game-audio.ts         # BGM/SFX lifecycle (wraps shared useGameAudio)
│   └── use-pixi-app.ts           # PixiJS Application lifecycle — async init, resizeTo container, cleanup
├── content/
│   ├── levels.ts                 # Level configs (devices, terminals, target connections, dispatch content, scene cards)
│   ├── dispatch-scripts.ts       # Shared dispatch script helpers
│   └── image-prompts.ts          # AI image generation prompts
└── tests/
    ├── circuit-validator.test.ts # Validator graph matching tests
    ├── config.test.ts            # Scoring + grade threshold tests
    └── store-transitions.test.ts # Phase machine transition tests

Components

PixiJS (Canvas Layer)

ModulePurpose
circuit-canvas.tsxReact wrapper that mounts the PixiJS canvas via usePixiApp, creates CircuitRenderer, and bridges React state to the renderer via callbacksRef. Contains the BreakerControls component (breaker toggle + Complete Job button). Dynamically imported (ssr: false)
circuit-renderer.tsSingle PixiJS class that handles everything: 5-layer scene (background → devices → wires → active wire → effects), device creation with per-type art (drawDeviceArt), terminal screw rendering with connected/unconnected states, stage-level pointer event handling (terminalAt/wireAt distance detection), wire placement/removal with connection tracking, drag wire preview with snap indicator, hover highlighting, auto-color resolution, load device rendering (light bulb, outlet indicator, fan), breaker state + wire locking, and breaker test animations (success: electricity dots + particle burst + load device activation; trip: screen darken + camera shake + sparks). Exposes testCircuit(), setBreakerOn(), activateLoadDevice(), deactivateLoadDevice(), setActiveColor(), getPlacedWireCount(), resize(), destroy()
circuit-validator.tsPure functions (no PixiJS dependency). validateCircuit: graph matching — compares player's connection set against the target. Returns { isComplete, correct, wrong, missing, totalRequired }. categorizeBreakerTest: interprets a ValidationResult into a three-outcome BreakerTestOutcome (works / trip / incomplete)

React (DOM Layer)

ComponentPurpose
circuit-challenge-phase.tsxPhase wrapper — owns timer (useGameCountdown), wire tray (inline color buttons with BLK/WHT/GRN/RED/BLU labels), wire count HUD, breaker trip counter, "Breaker ON" badge, "+Xs" penalty flash badge, "?" help button, blueprint button. Manages three-outcome breaker test flow (works → Complete Job, trip → penalty + continue, incomplete → no penalty). Handles scoring on "Complete Job" press and time expiry. Integrates how-to-play modal with timer freeze
blueprint-panel.tsxToggleable wiring diagram overlay (AnimatePresence modal). Shows blueprint image, progress bar (wires/total), dispatch hint callout if earned
how-to-play-circuit.tsxMulti-step GameOverlayPanel walkthrough — welcome splash + 6 visual steps (wire color, drag-to-connect, blueprint, wire removal, breaker toggle, scoring). Shows on first circuit challenge entry (localStorage cb-htp-seen). "?" HUD button reopens it. Timer pauses while open via htpPausedMsRef
dispatch-board.tsxMulti-step level intro carousel — tutorial variant (5 screens explaining the game + mission) and standard variant (2 screens with mission briefing). "Answer the Call" CTA with pulse animation
scene-card.tsxTransition between phases. Illustration + heading + text + Continue button
phase-runner.tsxRenders the active phase via dynamic import registry (next/dynamic, ssr: false). Handles prefetch for all level phases
run-hud.tsxTop bar: phase label, breaker trip count, restart/pause buttons
job-report.tsxThemed ResultsScreen wrapper
level-list.tsx20-level grid with difficulty grouping, skills tags, stars, best score

Uses shared components: LevelCard, Countdown, PauseMenu, ResultsScreen, GameError, LoadingScreen, GameShell, GameHeader, GameTimerRing, useGameCountdown, GameOverlayPanel.

Routing

/circuit-breaker/                          → Menu (hero + Play + Practice Mode buttons)
/circuit-breaker/levels/                   → Level selection (20 levels)
/circuit-breaker/play/[level]/             → Gameplay (level = 1-20)
/circuit-breaker/practice/                 → Practice mode index (phase list)
/circuit-breaker/practice/[phaseId]/       → Direct practice play (bypasses store flow, no scores saved)

Practice Mode

Practice mode at /circuit-breaker/practice/circuit-challenge/ renders the circuit challenge phase directly without dispatch, scene cards, or countdowns. The practice page sets currentLevel in the store via setState() and renders CircuitChallengePhase at Expert difficulty with a complex 4-device, 10-connection, 5-color circuit. A prominent Reset button in the header re-initializes the store and remounts the phase. Practice scores are not saved. Practice config lives in app/(games)/circuit-breaker/practice/[phaseId]/practice-config.ts.

Persistence

Storage key: circuit-breaker-state

Save data:

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

Score submitted via submitScore(cumulativeScore, metadata). Completion signaled via signalComplete() on first-ever level completion only.

Image Assets

AI-Generated

CategoryCountStyleNotes
Customer avatars20+Portrait, diverseOne per level minimum. Warm, approachable
Scene transition illustrations40+Flat/isometric2 per level: arrival + workspace entry
Device backgrounds10+Technical illustrationPanel box, outlet box, junction box, weatherproof box, 240V outlet interiors
Blueprint diagrams20Technical drawingPer-level wiring diagrams. Use high-quality model override for accuracy
Electrical PPE4-6Sprite (removeBackground)Insulated gloves, arc flash suit, face shield, rubber mat
Electrical tools8-10Sprite (removeBackground)Wire strippers, multimeter, voltage tester, fish tape, conduit bender

Many PPE and tool images already exist in the shared image registry (lib/images/registry.ts). Use sharedImage() where possible; only generate game-specific assets for items not already in the shared pool.

Blueprint diagrams should use the per-prompt model override (google/gemini-3-pro-image-preview) for technical accuracy, same as TBO.

PixiJS Device Assets

Device renderings combine AI-generated sprite textures (for the device body — outlet face, panel interior, switch plate) with programmatic PixiJS elements (terminal dots, labels, hit zones, glow filters). This hybrid gives visual richness from the sprites while keeping terminal interaction precise and data-driven.

Wire rendering is fully programmatic (Graphics bezier curves) — not sprite-based. This allows real-time redraw during drag interaction and dynamic color/glow changes.

Particle effects (breaker test flow, breaker sparks) use PixiJS particle emitters with lightweight texture atlases (small spark/dot sprites).

Circuit Workspace (PixiJS)

The circuit workspace is a 2D interactive canvas rendered with PixiJS v8. It handles all wiring interaction, device rendering, and visual effects. UI chrome (timer, wire tray, breaker toggle, blueprint panel) is React/DOM overlaid on the canvas.

Architecture

hooks/use-pixi-app.ts                    # PixiJS Application lifecycle — async init, resizeTo, cleanup
phases/circuit-challenge/
├── circuit-canvas.tsx                    # React wrapper — canvas mount, callbacksRef bridge, BreakerControls
├── circuit-renderer.ts                  # All-in-one PixiJS class: rendering, interaction, animation
├── circuit-challenge-phase.tsx           # React phase component — timer, wire tray, HUD, scoring
└── circuit-validator.ts                 # Pure graph matching (no PixiJS dependency)
  • usePixiApp owns the PixiJS Application lifecycle: creation, canvas mount, resize listener, and cleanup. Returns appRef and readyRef. The canvas container has touch-none CSS.
  • CircuitCanvas is dynamically imported (next/dynamic, ssr: false). It polls readyRef via async loop, then creates the CircuitRenderer and bridges React state via callbacksRef pattern.
  • CircuitRenderer is a single class (~1100 lines) that manages everything:
Layer (bottom → top)Contents
BackgroundDot grid + panel box interior (programmatic Graphics)
DevicesDevice containers with header, body, interior art, terminal screws, labels
Wires (placed)Graphics bezier curves with 4-layer rendering (glow + shadow + main + highlight)
Wires (active)Live drag wire following the pointer + snap indicator ring
EffectsBreaker test animations (electricity dots, particle bursts, "POWER ON!" text), trip animations (overlay, sparks, shake), load device glow

All pointer events are handled at the stage level (app.stage.on("pointerdown/move/up")) with distance-based hit detection via terminalAt() and wireAt(). No per-object event listeners. Cursor management via app.canvas.style.cursor. Wire state (placed wires, connection counts per terminal) lives entirely in the renderer. destroy() cleans up event listeners, layers, and terminal/wire arrays.

React ↔ PixiJS Bridge

Communication uses the callback-ref pattern (no shared Zustand state for wire data):

DirectionMechanismExample
React → CanvasRef method callsrendererRef.current.setActiveColor("red"), rendererRef.current.testCircuit(), rendererRef.current.setBreakerOn(true)
React → CanvasProp-driven useEffectactiveWireColor changes trigger setActiveColor(), breakerOn changes trigger setBreakerOn()
Canvas → ReactCallback refs (callbacksRef)onWireCompleted(), onWireRemoved(), onBreakerTest(result), onAnimationDone()

Wire count, breaker trips, and penalty time are tracked in the React phase component (CircuitChallengePhase) via useState and useRef. The renderer is the source of truth for visual state (wire graphics, device positions, animation state). The Zustand orchestrator store manages only phase transitions and level config.

Shared Platform Usage

Shared AssetImportUsage
ResultsScreen@/components/global/results-screenWrapped by job-report.tsx
Countdown@/components/global/countdownPre-phase 3-2-1-GO
GameTimerRing + useGameCountdown@/components/global/...Phase timer display
PauseMenu@/components/global/pause-menuPause overlay
LevelCard@/components/global/level-cardLevel selection grid
GameOverlayPanel@/components/global/game-overlay-panelScene cards, dispatch conversation
Shared prep phases@/lib/phases/*Gear Up, Tool Match, Safety Scan
useGameActionsBase@/lib/hooks/use-game-actionsPersistence base
calculateAccuracy@/lib/scoringDelegated by circuit scoring
assignGrade, getGradeStyle@/lib/scoringGrade assignment in results
sharedImage@/lib/images/registryShared PPE/tool image paths
createTransitionEngine@/lib/storesPhase machine
computePauseCompensationMs@/lib/stores/pauseTimer fairness

Notable Mechanics

Circuit Validator

The circuit validator is a graph matching function. The player's connections (a set of { from, to, wireColor } edges) are compared to the target circuit (the "answer"). Validation checks:

  1. All required connections present — every edge in the target exists in the player's graph
  2. No incorrect connections — no edges in the player's graph that aren't in the target
  3. Correct wire colors — each connection uses the right wire color (Medium+)

This is a set comparison, not a circuit simulation. We don't need to model current flow — just verify the wiring matches the blueprint. A thin categorizeBreakerTest() function interprets the validation result into three outcomes: works (all correct), trip (any wrong), or incomplete (only missing, no wrong).

For Match & Fix mode, the validator identifies which pre-wired connections are wrong (the "faults" the player needs to find).

For Diagnose mode, the validator is used on breaker test to confirm the player's fix is correct. The multimeter readings are pre-computed lookup tables, not real-time circuit simulation.

Dispatch Hint System (Graduated)

The dispatch phase has 3 rounds of diagnostic questions. Each "best" answer earns a progressively more detailed hint that appears on the blueprint panel during the Circuit Challenge:

Best answersHint tierExample
0NoneNo hint on blueprint
1Basic"Check the breaker panel connections."
2Detailed"A high-wattage appliance may have tripped the breaker. Focus on the HOT wire."
3Full"The 1500W space heater overloaded the circuit. The HOT wire from panel to outlet is the key connection."

Each level's DispatchConfig has a hints: [string, string, string] array (one per tier). The store holds the highest-tier hint earned as a single dispatchHint: string | null. The blueprint panel displays it as a green callout.

After each customer response, a quality feedback badge shows: "Great question -- hint earned!" (green/best), "Okay question -- that helps a bit" (amber/decent), or "That didn't narrow things down" (muted/poor). This teaches diagnostic communication skill without scoring pressure.

Tutorial Guidance (Level 1)

The tutorial uses two layers of guidance:

Dispatch Board intro: On the tutorial level (kind === "tutorial"), the DispatchBoard component shows a 5-step carousel that teaches the full game flow before gameplay starts. Steps explain what service calls are, how the prep phase works, how the circuit challenge works, and then present the level-specific mission briefing.

How-to-play walkthrough: On first entry to the circuit challenge phase, a multi-step GameOverlayPanel walkthrough (HowToPlayCircuit) auto-opens. It has 6 visual steps with mock UI elements: wire color selection, drag-to-connect, blueprint reference, wire removal, breaker toggle (three-outcome), and scoring/penalties. Gated by localStorage key cb-htp-seen — shows once, never again unless the "?" help button in the HUD is tapped to reopen. The game timer pauses while the walkthrough is open (accumulated via htpPausedMsRef added to subtractElapsedMs).

Both layers are non-intrusive — dismissible at any step via "Skip" or "Got it".

Zoom and Pan (Hard/Expert) — Planned

Not yet implemented. Currently all levels auto-center devices in the viewport via computeOffset(). Future work for Hard/Expert levels with dense panels:

  • Pinch-to-zoom + two-finger drag-to-pan
  • Mini-map indicator
  • Auto-zoom on probe placement (Diagnose mode)