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):
| Element | Description |
|---|---|
| Header | "INCOMING SERVICE CALL" with phone/alert animation |
| Customer | Avatar (AI-generated portrait) + name |
| Location | Setting tag: "Residential — Kitchen", "Commercial — Office Floor", etc. |
| Problem | 1-2 sentence customer complaint |
| Stats | Difficulty badge, circuit complexity indicator, time limit |
| Skills | 2-4 skills tags from the level's learning objectives |
| Tips | How-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."
| Option | Quality | Customer 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:
- Before the prep phase (e.g., "Arriving at the job — Let's check your gear")
- 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 Type | Mechanic | Duration | Used In |
|---|---|---|---|
| Gear Up | Tap-to-select correct PPE from a grid. Insulated gloves, safety glasses, arc flash suit, face shield. Decoys scale with difficulty | 20-30s | Levels 1, 4, 7, 10, 13, 16, 19 |
| Tool Match | Multi-select tools and materials for the job card. Wire strippers, multimeter, voltage tester, correct wire gauge | 20-30s | Levels 2, 5, 8, 11, 14, 17, 20 |
| Safety Scan | Card-based judgment — identify electrical hazards (exposed wires, water near outlets, overloaded circuits). Tap SAFE or HAZARD | 20-30s | Levels 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
└─────────────────────────────────┘
| Layer | Technology | Contents |
|---|---|---|
| Canvas (PixiJS) | usePixiApp + CircuitRenderer | Device 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 components | Timer ring, wire tray buttons, breaker toggle, "Complete Job" button, breaker trip counter, "Breaker ON" badge, phase indicator, pause button |
| Panels (React/DOM) | Standard components | Blueprint 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:
| Device | Terminals | Introduced |
|---|---|---|
| Duplex Outlet | HOT (brass), NEUTRAL (silver), GROUND (green) | Level 1 |
| Single-Pole Switch | COMMON, SWITCHED-HOT, GROUND | Level 2 |
| Breaker Panel | HOT-BUS, NEUTRAL-BAR, GROUND-BAR + individual breaker slots | Level 3 |
| GFCI Outlet | LINE-HOT, LINE-NEUTRAL, LOAD-HOT, LOAD-NEUTRAL, GROUND | Level 6 |
| Ceiling Fan | FAN-HOT, LIGHT-HOT, NEUTRAL, GROUND | Level 7 |
| Weatherproof Box | Same as Duplex Outlet terminals, outdoor-rated enclosure | Level 9 |
| 3-Way Switch | COMMON, TRAVELER-1, TRAVELER-2, GROUND | Level 11 |
| 240V Outlet (NEMA 14-50) | HOT-A (black), HOT-B (red), NEUTRAL (white), GROUND (green) | Level 13 |
| Junction Box | Wire-nut splice points (grouped terminals) | Level 16 |
| Sub-Panel | MAIN-HOT-A, MAIN-HOT-B, MAIN-NEUTRAL, MAIN-GROUND + branch breakers | Level 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)
| Color | Function | Taught Via |
|---|---|---|
| Black | Hot (ungrounded conductor) | Level 1+ |
| White | Neutral (grounded conductor) | Level 1+ |
| Green / Bare | Ground (grounding conductor) | Level 1+ |
| Red | Second hot (240V circuits, travelers, fan light) | Level 7+ |
| Blue | Traveler (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.
- 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). - 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 PixiJSGraphicsbezier that redraws every frame. - 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.
- Release near a valid terminal: Wire is placed instantly as a permanent
Graphicsbezier 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). - Release on empty space: Drag cancelled, wire disappears. No penalty.
- Remove a wire: Single-tap on a placed wire (within
WIRE_HIT_DISTof its bezier path) removes it instantly. Terminal visuals revert to unconnected state. - Hover feedback: Cursor changes to "pointer" over terminals and wires. An amber ring highlights the hovered terminal even when not dragging.
- 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:
| Outcome | Condition | What Happens | Penalty |
|---|---|---|---|
| Circuit works | All connections correct, none wrong | Load device activates (light glows, fan spins, outlet indicator turns green). "Complete Job" button appears. | None |
| Breaker trips | Any wrong connection present | Spark animation, camera shake, breaker auto-flips back to OFF. "+Xs BREAKER TRIP!" penalty. Player continues. | Time penalty |
| Nothing happens | Missing connections but nothing wrong | Load 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):
- Load device activates (light bulb glows warm yellow, outlet indicator turns green, etc.)
- All wires tint green
- 3 electricity dots per wire travel along the bezier paths (staggered sizes, trailing afterglow)
- Wires pulse with oscillating alpha (glow effect, 500ms)
- 24-particle radial burst from canvas center (green + yellow, expanding outward)
- Terminal dots flash green sequentially
- "POWER ON!" text scales in at center
onBreakerTestcallback fires immediately (score uses time at "Complete Job" press, not breaker flip)- "Complete Job" button appears — player confirms completion
On trip (any connection wrong — 1.5s animation):
- Canvas overlay darkens (alpha 0→0.6 in 100ms)
- Camera shake: stage position oscillates for 300ms via sine wave, decaying to zero
- 20 spark particles burst from the midpoint of the first wrong wire (4 color variants: orange, yellow, white, deep orange) with gravity decay
- Red glow strokes drawn along wrong wire bezier paths
- Wrong wires flash red/white rapidly (6 blinks in 550ms)
- "BREAKER TRIP!" text flashes at center
- Breaker auto-flips to OFF after animation completes
- "+Xs" penalty badge appears in the React HUD (animated bounce, auto-dismisses after 2s)
- Timer adds penalty seconds to elapsed time via
penaltyMsRefadded tosubtractElapsedMs - 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 | Teststep 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:
- Tap Terminal A on the canvas → red probe sprite (labeled "A") appears on the terminal
- A pulsing "A" badge appears on the Probe button in the HUD to indicate the player should tap a second terminal
- Tap Terminal B → black probe sprite (labeled "B") appears. The reading is looked up from the level's
multimeterReadingsconfig and displayed as a floating green label above the probed area (e.g., "120 V", "0 Ω", "OL") - 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
- Tapping a third terminal clears the existing probes and starts a new reading cycle
- 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:
- "This circuit has a problem" — explains the pre-wired fault concept
- "Probe with the multimeter" — tap two terminals to get a reading
- "Spot the fault" — interpret abnormal readings in the Blueprint log
- "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):
- Canvas overlay sprite darkens the scene (alpha 0→0.7 in 100ms)
- Spark particle burst at the fault point — orange/yellow particles with velocity decay
- "BZZT" electrical pop SFX
- Breaker device sprite plays flip animation
- Wrong wire
Graphicsobjects flash red with rapid glow pulses (3× in 500ms) - Canvas overlay brightens back (alpha 0.7→0 in 300ms)
- "+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.
| ID | Badge | Service Call | Difficulty | Prep Phase | Circuit Mode | Skills Tags |
|---|---|---|---|---|---|---|
| 1 | Tutorial | Dead Outlet | Easy | Gear Up | Build: 3-wire outlet (Panel → Outlet) | Safety, PPE, Basic Wiring |
| 2 | Level 1 | New Light Switch | Easy | Tool Match | Build: Switch + light (Panel → Switch → Light) | Tool ID, Basic Circuits |
| 3 | Level 2 | Dedicated Microwave Circuit | Easy | Safety Scan | Build: Dedicated 20A circuit | Hazard ID, Basic Theory |
| 4 | Level 3 | Bathroom Fan + Light | Easy | Gear Up | Build: Branching circuit (Panel → Switch → Fan + Light) | Safety, Basic Circuits |
| 5 | Level 4 | Bedroom Outlet Run | Easy | Tool Match | Build: 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.
| ID | Badge | Service Call | Difficulty | Prep Phase | Circuit Mode | Skills Tags |
|---|---|---|---|---|---|---|
| 6 | Level 5 | GFCI Kitchen Outlet | Medium | Safety Scan | Build: GFCI (LINE/LOAD chain) | NEC Code, GFCI |
| 7 | Level 6 | Ceiling Fan Install | Medium | Gear Up | Build: Fan/light dual switches | Tool Use, Circuits |
| 8 | Level 7 | Panel Inspection | Medium | Tool Match | Match & Fix: Panel vs diagram | Blueprints, NEC Code |
| 9 | Level 8 | Outdoor Patio Circuit | Medium | Safety Scan | Build: Outdoor GFCI + weatherproof | NEC Code, Routing |
| 10 | Level 9 | Kitchen Rewire Check | Medium | Gear Up | Match & Fix: Audit contractor work | Blueprints, Hazard ID |
Hard (Levels 11-15) — "Reputation Growing": Manual color + decoys. Diagnose mode introduced.
| ID | Badge | Service Call | Difficulty | Prep Phase | Circuit Mode | Skills Tags |
|---|---|---|---|---|---|---|
| 11 | Level 10 | Three-Way Stairway Switch | Hard | Tool Match | Build: 3-way pair w/ travelers | Circuits, Blueprints |
| 12 | Level 11 | Flickering Lights | Hard | Safety Scan | Diagnose: Loose neutral | Troubleshooting, Multimeter |
| 13 | Level 12 | EV Charger Install | Hard | Gear Up | Build: 240V circuit + 2-pole breaker | NEC Code, 240V, Routing |
| 14 | Level 13 | Handyman Wiring Audit | Hard | Tool Match | Match & Fix: Residential audit | Blueprints, NEC Code |
| 15 | Level 14 | Storm Damage: Dead Circuits | Hard | Safety Scan | Diagnose: 2 faults, multi-room | Diagnostics, Multimeter |
Expert (Levels 16-20) — "Going Pro": All skills stacked. Dense panels, commercial, Ohm's Law.
| ID | Badge | Service Call | Difficulty | Prep Phase | Circuit Mode | Skills Tags |
|---|---|---|---|---|---|---|
| 16 | Level 15 | Workshop Sub-Panel | Expert | Gear Up | Build: Sub-panel + branches + junction box | Circuits, Math, NEC Code |
| 17 | Level 16 | Restaurant Kitchen Audit | Expert | Tool Match | Match & Fix: Commercial multi-circuit | Commercial, Blueprints |
| 18 | Level 17 | Office Lighting Retrofit | Expert | Safety Scan | Build: Multi-circuit commercial | Commercial, Routing |
| 19 | Level 18 | Apartment Building Troubleshoot | Expert | Gear Up | Diagnose: Multi-fault + math prompts | Diagnostics, Ohm's Law |
| 20 | Level 19 | Full Service Diagnostic | Expert | Tool Match | Diagnose: 3-4 faults + Ohm's Law | Diagnostics, Ohm's Law, Professional |
Bonus — "Master Electrician": Unlocked after completing all 20 levels. The capstone build.
| ID | Badge | Service Call | Difficulty | Prep Phase | Circuit Mode | Skills Tags |
|---|---|---|---|---|---|---|
| 21 | Level 20 | Master Electrician Build-Out | Expert | Safety Scan | Build: 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 Range | New Mechanics | New Devices | New Wire Colors |
|---|---|---|---|
| 1-5 (Easy) | Build mode, auto-color, drag-to-connect, breaker test, branching circuits, daisy chaining | Duplex Outlet, Single-Pole Switch, Breaker Panel | BLK, WHT, GRN (auto-selected) |
| 6-10 (Medium) | Manual wire color selection, Match & Fix mode | GFCI Outlet, Ceiling Fan, Weatherproof Box | RED (Level 7) |
| 11-15 (Hard) | Diagnose mode, multimeter, decoy wire colors, 240V wiring, traveler wiring | 3-Way Switch, 240V Outlet (NEMA 14-50) | — (manual + decoys) |
| 16-20 (Expert) | Ohm's Law math prompts, zoom/pan, commercial context | Sub-Panel, Junction Box | BLU (Level 17) |
| 21 (Bonus) | All mechanics stacked, capstone build with every device type and all 5 wire colors | All device types combined | All 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
| Setting | Easy | Medium | Hard | Expert |
|---|---|---|---|---|
| Connections per circuit | 3-6 | 5-7 | 7-9 | 10-14 |
| Wire color selection | Auto | Manual | Manual + decoys | Manual + decoys |
| Breaker test feedback | Hints shown | Wrong highlighted only | Wrong highlighted only | Wrong flash briefly |
| Faults (Diagnose mode) | N/A | N/A | 1-2 | 3-4 |
| Math prompts | None | None | Rare | Required |
| Zoom / pan | Disabled (fits screen) | Enabled | Enabled | Required (dense panels) |
| Prep phase time | 30s | 30s | 25s | 20s |
| Circuit challenge time | 90s | 120s | 150s | 180s |
| Decoy quality (prep) | Obvious | Plausible | Near-miss | Near-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:
| Difficulty | Penalty | % of timer |
|---|---|---|
| Easy | +5s | 5.6% of 90s |
| Medium | +6s | 5.0% of 120s |
| Hard | +8s | 5.3% of 150s |
| Expert | +10s | 5.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):
| Difficulty | 3 Stars | 2 Stars | 1 Star |
|---|---|---|---|
| Easy | 90%+ | 65%+ | Completed |
| Medium | 85%+ | 60%+ | Completed |
| Hard | 80%+ | 55%+ | Completed |
| Expert | 75%+ | 50%+ | Completed |
Accuracy
accuracy = max(0, 100 - totalBreakerTrips × 15)
Grade Thresholds
Both minimum score AND minimum accuracy must be met:
| Grade | Easy | Medium | Hard | Expert |
|---|---|---|---|---|
| S | 1800 / 95% | 1750 / 90% | 1650 / 85% | 1500 / 75% |
| A | 1500 / 80% | 1450 / 75% | 1350 / 70% | 1200 / 60% |
| B | 1100 / 65% | 1050 / 60% | 950 / 50% | 850 / 40% |
| C | 700 / 40% | 650 / 35% | 600 / 25% | 500 / 15% |
| D | 0 / 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 Area | Where Taught |
|---|---|
| Basic electrical safety | Gear Up (PPE), Safety Scan (hazards) |
| Identifying electrical hazards | Safety Scan, scene cards |
| Choosing correct PPE | Gear Up |
| Tool identification & proper use | Tool Match |
| Basic electrical theory (V/I/R) | Diagnose mode, math prompts |
| Unit conversion & measuring | Math prompts in Diagnose mode |
| Understanding circuits | Build mode (all levels) |
| NEC code awareness | GFCI levels, wire color rules, outdoor requirements |
| Asking the right questions | Dispatch diagnostic questions |
| Translating symptoms to issues | Dispatch + Diagnose mode |
| Narrowing down root causes | Diagnose mode (multimeter probing) |
| Professional communication | Dispatch customer interaction |
| Reading wiring diagrams | Blueprint reference panel (all levels) |
| Identifying installation mistakes | Match & Fix mode |
| Routing and organizing layouts | Build mode on complex levels |
Orchestrator Architecture
Phase Machine
menu → levelIntro → dispatch → phaseIntro → countdown → phaseActive → phaseComplete → [next or results]
| From | Event | To |
|---|---|---|
menu | START_RUN | levelIntro |
levelIntro | ACCEPT_JOB | dispatch |
dispatch | HEAD_TO_JOB | phaseIntro |
phaseIntro | BEGIN_COUNTDOWN | countdown |
countdown | BEGIN_PHASE | phaseActive |
phaseActive | COMPLETE | phaseComplete |
phaseActive | PAUSE | paused |
phaseComplete | ADVANCE | phaseIntro (next phase) or results |
paused | RESUME | (previousPhase) |
results | START_RUN | levelIntro |
Global transitions: RESTART → levelIntro (requires currentLevel), RESET_MENU → menu.
Store uses createTransitionEngine from @/lib/stores. Pause time compensation uses computePauseCompensationMs.
Phase Structure Per Level
Every level has exactly 3 phases, 2 scored:
| Index | Phase | Scored | Component Source |
|---|---|---|---|
| 0 | Dispatch | No | games/circuit-breaker/phases/dispatch/ |
| 1 | Prep (Gear Up / Tool Match / Safety Scan) | Yes | @/lib/phases/* (shared) |
| 2 | Circuit Challenge (Build / Match & Fix / Diagnose) | Yes | games/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)
| Module | Purpose |
|---|---|
circuit-canvas.tsx | React 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.ts | Single 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.ts | Pure 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)
| Component | Purpose |
|---|---|
circuit-challenge-phase.tsx | Phase 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.tsx | Toggleable wiring diagram overlay (AnimatePresence modal). Shows blueprint image, progress bar (wires/total), dispatch hint callout if earned |
how-to-play-circuit.tsx | Multi-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.tsx | Multi-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.tsx | Transition between phases. Illustration + heading + text + Continue button |
phase-runner.tsx | Renders the active phase via dynamic import registry (next/dynamic, ssr: false). Handles prefetch for all level phases |
run-hud.tsx | Top bar: phase label, breaker trip count, restart/pause buttons |
job-report.tsx | Themed ResultsScreen wrapper |
level-list.tsx | 20-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
| Category | Count | Style | Notes |
|---|---|---|---|
| Customer avatars | 20+ | Portrait, diverse | One per level minimum. Warm, approachable |
| Scene transition illustrations | 40+ | Flat/isometric | 2 per level: arrival + workspace entry |
| Device backgrounds | 10+ | Technical illustration | Panel box, outlet box, junction box, weatherproof box, 240V outlet interiors |
| Blueprint diagrams | 20 | Technical drawing | Per-level wiring diagrams. Use high-quality model override for accuracy |
| Electrical PPE | 4-6 | Sprite (removeBackground) | Insulated gloves, arc flash suit, face shield, rubber mat |
| Electrical tools | 8-10 | Sprite (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)
usePixiAppowns the PixiJSApplicationlifecycle: creation, canvas mount, resize listener, and cleanup. ReturnsappRefandreadyRef. The canvas container hastouch-noneCSS.CircuitCanvasis dynamically imported (next/dynamic,ssr: false). It pollsreadyRefvia async loop, then creates theCircuitRendererand bridges React state viacallbacksRefpattern.CircuitRendereris a single class (~1100 lines) that manages everything:
| Layer (bottom → top) | Contents |
|---|---|
| Background | Dot grid + panel box interior (programmatic Graphics) |
| Devices | Device 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 |
| Effects | Breaker 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):
| Direction | Mechanism | Example |
|---|---|---|
| React → Canvas | Ref method calls | rendererRef.current.setActiveColor("red"), rendererRef.current.testCircuit(), rendererRef.current.setBreakerOn(true) |
| React → Canvas | Prop-driven useEffect | activeWireColor changes trigger setActiveColor(), breakerOn changes trigger setBreakerOn() |
| Canvas → React | Callback 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 Asset | Import | Usage |
|---|---|---|
ResultsScreen | @/components/global/results-screen | Wrapped by job-report.tsx |
Countdown | @/components/global/countdown | Pre-phase 3-2-1-GO |
GameTimerRing + useGameCountdown | @/components/global/... | Phase timer display |
PauseMenu | @/components/global/pause-menu | Pause overlay |
LevelCard | @/components/global/level-card | Level selection grid |
GameOverlayPanel | @/components/global/game-overlay-panel | Scene cards, dispatch conversation |
| Shared prep phases | @/lib/phases/* | Gear Up, Tool Match, Safety Scan |
useGameActionsBase | @/lib/hooks/use-game-actions | Persistence base |
calculateAccuracy | @/lib/scoring | Delegated by circuit scoring |
assignGrade, getGradeStyle | @/lib/scoring | Grade assignment in results |
sharedImage | @/lib/images/registry | Shared PPE/tool image paths |
createTransitionEngine | @/lib/stores | Phase machine |
computePauseCompensationMs | @/lib/stores/pause | Timer 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:
- All required connections present — every edge in the target exists in the player's graph
- No incorrect connections — no edges in the player's graph that aren't in the target
- 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 answers | Hint tier | Example |
|---|---|---|
| 0 | None | No hint on blueprint |
| 1 | Basic | "Check the breaker panel connections." |
| 2 | Detailed | "A high-wattage appliance may have tripped the breaker. Focus on the HOT wire." |
| 3 | Full | "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)