Fix NPC interaction and event handling issues - Added a visual problem-solution summary for debugging NPC event handling. - Resolved cooldown bug in NPCManager by implementing explicit null/undefined checks. - Modified PersonChatMinigame to prioritize event parameters over state restoration. - Updated security guard dialogue in Ink scenarios to improve interaction flow. - Adjusted vault key parameters in npc-patrol-lockpick.json for consistency. - Changed inventory stylesheet references to hud.css in test HTML files for better organization. feat(combat): Integrate chair kicking with punch mechanic Update chair interaction to use the punch system instead of direct kicking: **Changes to interactions.js:** - Modified swivel chair interaction to trigger player punch instead of directly applying kick velocity - Simplified chair interaction handler to just call playerCombat.punch() **Changes to player-combat.js:** - Extended checkForHits() to detect chairs in punch range and direction - Added kickChair() method that applies the same velocity calculation: - Calculates direction from player to chair - Applies 1200 px/s kick force in that direction - Triggers spin direction calculation for visual rotation - Adds visual feedback (flash chair, light screen shake) - Chairs now respond to punch AOE damage like hostile NPCs Now clicking a chair or pressing 'E' near it triggers a punch, and if the chair is in punch range and facing direction, it gets kicked with the original velocity physics. Multiple chairs can be kicked with one punch. feat(combat): Implement hostile NPC behavior and final integration (Phase 6-7) Complete hostile NPC combat system with chase behavior and integration: **Phase 6: Hostile NPC Behavior** - Modified npc-behavior.js determineState() to check hostile state from npcHostileSystem - Implemented updateHostileBehavior() with chase and attack logic: - NPCs chase player when hostile and in aggro range - NPCs stop and attack when in attack range - NPCs use directional movement with proper animations - Integration with npcCombat system for attack attempts - Added KO state check to prevent KO'd NPCs from acting **Phase 7: Final Integration** - Modified player.js to disable movement when player is KO - Added visual KO effect (50% alpha) to NPC sprites in npc-hostile.js - Connected all combat systems end-to-end: - Ink dialogue → hostile tag → hostile state → chase behavior → combat - Player interaction → punch → NPC damage → KO → visual feedback - NPC chase → attack → player damage → HP UI → game over Full combat loop now functional: hostile NPCs chase and attack player, player can punch hostile NPCs, complete visual/audio feedback, game over on KO. feat(combat): Add feedback, UI, and combat mechanics (Phase 2-5) Implement comprehensive combat feedback, UI, and mechanics: **Phase 2: Enhanced Feedback Systems** - damage-numbers.js: Floating damage numbers with object pooling - screen-effects.js: Screen flash and shake for combat feedback - sprite-effects.js: Sprite tinting, flashing, and visual effects - attack-telegraph.js: Visual indicators for incoming NPC attacks **Phase 3: UI Components** - health-ui.js: Player health display as hearts (5 hearts, shows when damaged) - npc-health-bars.js: Health bars above hostile NPCs with color coding - game-over-screen.js: KO screen with restart/main menu options **Phase 4-5: Combat Mechanics** - player-combat.js: Player punch system with AOE directional damage - npc-combat.js: NPC attack system with telegraph and cooldowns - Modified interactions.js to trigger punch on hostile NPC interaction - Integrated all systems into game.js create() and update() loops Combat now functional with complete visual/audio feedback pipeline. Player can punch hostile NPCs, NPCs can attack player, health tracking works. feat(combat): Add hostile NPC system foundation (Phase 0-1) Implement core hostile NPC combat system infrastructure: - Add #hostile tag handler to chat-helpers.js for Ink integration - Fix security-guard.ink to use proper hub pattern with -> hub instead of -> END - Add #hostile:security_guard tags to hostile conversation paths - Create combat configuration system (combat-config.js) - Create combat event constants (combat-events.js) - Implement player health tracking system with HP and KO state - Implement NPC hostile state management with HP tracking - Add combat debug utilities for testing - Add error handling utilities for validation - Integrate combat systems into game.js create() method - Create test-hostile.ink for testing hostile tag system This establishes the foundation for hostile NPC behavior, allowing NPCs to become hostile through Ink dialogue and tracking health for both player and NPCs. docs(npc): Apply codebase-verified corrections to hostile NPC plans Apply critical corrections based on actual codebase verification: CORRECTIONS.md (Updated): - ✅ Confirms #exit_conversation tag ALREADY IMPLEMENTED * Location: person-chat-minigame.js line 537 * No handler needed in chat-helpers.js - ❌ Hostile tag still needs implementation in chat-helpers.js - Provides exact code for hostile tag handler - Clarifies tag format: #hostile:npcId or #hostile (uses current NPC) - Updated action items to reflect what's already working INTEGRATION_UPDATES.md (New): - Comprehensive correction document - Issue 1 Corrected: Exit conversation already works - Issue 6 Corrected: Punch mechanics are interaction-based with AOE - Details interaction-based punch targeting: * Player clicks hostile NPC OR presses 'E' nearby * Punch animation plays in facing direction * Damage applies to ALL NPCs in range + direction (AOE) * Can hit multiple enemies if grouped (strategic gameplay) - Provides complete implementation examples - Removes complexity of target selection systems - Uses existing interaction patterns quick_start.md (Updated): - Removed exit_conversation handler (already exists) - Updated hostile tag handler code - Added punch mechanics design section - Clarified interaction-based targeting - Added troubleshooting for exit_conversation Key Findings: ✅ Exit conversation tag works out of the box ✅ Punch targeting uses existing interaction system (simpler!) ✅ AOE punch adds strategic depth without complexity ❌ Only ONE critical task remains: Add hostile tag to chat-helpers.js Impact: - Less work required (don't need exit_conversation handler) - Simpler implementation (use existing interaction patterns) - Better gameplay (AOE punches, directional attacks) - Clear path forward with exact code examples docs(npc): Add critical corrections and codebase integration review Add comprehensive review of hostile NPC plans against actual codebase: CORRECTIONS.md: - Identifies critical Ink pattern error (-> END vs -> hub) - Documents correct hub-based conversation pattern - Provides corrected examples for all Ink files - Explains why -> hub is required after #exit_conversation FORMAT_REVIEW.md: - Validates JSON scenario format against existing scenarios - Reviews NPC object structure and required fields - Documents correct Ink hub pattern from helper-npc.ink - Proposes hostile configuration object for NPC customization - Provides complete format reference and checklists review2/integration_review.md: - Comprehensive codebase analysis by Explore agent - Identifies 2 critical blockers requiring immediate attention: * Missing tag handlers for #hostile and #exit_conversation * Incorrect Ink pattern (-> END) in planning documents - Documents 4 important integration differences: * Initialization in game.js not main.js * Event dispatcher already exists (window.eventDispatcher) * Room transition behavior needs design decision * Multi-hostile NPC targeting needs design decision - Confirms 8 systems are fully compatible with plan - Provides existing code patterns to follow - Corrects integration sequence review2/quick_start.md: - Step-by-step guide for Phase 0-1 implementation - Includes complete code examples for critical systems - Browser console test procedures - Common issues and solutions - Success criteria checklist Key Findings: ✅ 90% compatible with existing codebase ❌ Must add tag handlers to chat-helpers.js before implementation ❌ Must fix all Ink examples to use -> hub not -> END ⚠️ Should follow game.js initialization pattern not main.js ⚠️ Should use existing window.eventDispatcher ⚠️ Need design decisions on room transitions and multi-targeting All critical issues documented with solutions ready. Implementation can proceed with high confidence after corrections applied. docs(npc): Add comprehensive planning documents for hostile NPC system Add detailed implementation plans for hostile NPC feature including: - Complete implementation plan with phase-by-phase breakdown - Architecture overview with system diagrams and data flows - Detailed TODO list with 200+ actionable tasks - Phase 0 foundation with design decisions and base components - Enhanced combat feedback implementation guide - Implementation roadmap with 6-day schedule Add comprehensive review documents: - Implementation review with risk assessment and recommendations - Technical review analyzing code patterns and best practices - UX review covering player experience and game feel Key features planned: - NPC hostile state triggered via Ink tags - Player health system with heart-based UI - NPC health bars and combat mechanics - Punch combat for both player and NPCs - Strong visual/audio feedback for combat - Game over system and KO states - Attack telegraphing for fairness - Enhanced NPC chase behavior with LOS - Debug utilities and error handling - Comprehensive testing strategy
21 KiB
NPC Hostile State - Architecture Overview
System Architecture Diagram
┌─────────────────────────────────────────────────────────────────┐
│ Game Loop (main.js) │
│ ┌──────────────┐ ┌───────────────┐ ┌────────────────────┐ │
│ │ create() │ │ update() │ │ Event Listeners │ │
│ └──────────────┘ └───────────────┘ └────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│ │ │
│ Initialize │ Update │ React to Events
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌──────────────────┐
│ Health Systems │ │ Combat Systems │ │ UI Systems │
├─────────────────┤ ├─────────────────┤ ├──────────────────┤
│ Player Health │ │ Player Combat │ │ Player Health UI │
│ NPC Hostile │ │ NPC Combat │ │ NPC Health UI │
│ │ │ Combat Anims │ │ Game Over UI │
└─────────────────┘ └─────────────────┘ └──────────────────┘
│ │ │
└────────────────────┴────────────────────────┘
│
▼
┌──────────────────┐
│ NPC Behaviors │
├──────────────────┤
│ Patrol (Normal) │
│ Chase (Hostile) │
│ Attack (Combat) │
└──────────────────┘
│
▼
┌──────────────────┐
│ LOS System │
├──────────────────┤
│ Player Detection │
│ Visual Range │
└──────────────────┘
│
▼
┌──────────────────┐
│ Ink Integration │
├──────────────────┤
│ Tag Processing │
│ Hostile Trigger │
└──────────────────┘
Core Systems
1. Health Management
Player Health System (player-health.js)
- Responsibility: Track player HP, damage, healing, KO state
- Data: Current HP (0-100), max HP, KO flag
- Events Emitted:
player_hp_changed- When HP changesplayer_ko- When HP reaches 0
- Used By: Combat system, UI system, player controls
NPC Hostile State System (npc-hostile.js)
- Responsibility: Track hostile state and health for all NPCs
- Data Structure: Map of npcId → state object
isHostile: BooleancurrentHP: Number (0-maxHP)maxHP: Number (configurable per NPC)isKO: BooleanattackCooldown: Number (ms)chaseTarget: Reference to playerattackDamage: Number (configurable)
- Events Emitted:
npc_hostile_state_changed- When hostile state togglesnpc_ko- When NPC HP reaches 0
- Used By: Behavior system, combat system, UI system, Ink integration
2. Combat Systems
Player Combat System (player-combat.js)
- Responsibility: Handle player punching attacks
- State: Punch cooldown, isPunching flag
- Process Flow:
- Player inputs punch command (SPACE key)
- Check cooldowns and state
- Play punch animation (walk + red tint)
- Wait animation duration (500ms)
- Check target still in range
- Apply damage to NPC
- Update NPC health state
- Start cooldown
- Dependencies:
- Animation system
- NPC hostile system
- Combat config
- Player state
NPC Combat System (npc-combat.js)
- Responsibility: Handle NPC attacks on player
- State: Per-NPC attack cooldowns (in hostile state)
- Process Flow:
- NPC behavior detects player in range
- Check attack cooldown
- Stop NPC movement
- Play attack animation (walk + red tint)
- Wait animation duration
- Check player still in range
- Apply damage to player
- Update player health
- Start cooldown
- Resume NPC movement
- Dependencies:
- Animation system
- Player health system
- NPC hostile system
- Combat config
Combat Animation System (combat-animations.js)
- Responsibility: Play placeholder punch animations
- Technique: Reuse walk animations with red tint
- Future: Will be replaced with dedicated punch sprites
- Functions:
playPlayerPunchAnimation()- Returns promiseplayNPCPunchAnimation()- Returns promise- Both handle tinting, animation, and cleanup
3. Behavior System Integration
NPC Behavior Manager (npc-behavior.js - MODIFIED)
Current behavior modes:
- Normal Mode: Patrol within bounds, face player
- Hostile Mode (NEW): Chase player, attack when in range
Hostile Behavior Flow:
┌─────────────────────────┐
│ NPC Becomes Hostile │
└────────────┬────────────┘
│
▼
┌─────────────────────────┐
│ Enable LOS (360°) │
└────────────┬────────────┘
│
▼
┌─────────────────────────┐
│ Is Player in LOS? │
└────┬──────────────┬─────┘
│ Yes │ No
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Chase Player│ │ Keep Patrol │
└──────┬──────┘ └─────────────┘
│
▼
┌──────────────────────┐
│ Distance < Attack? │
└──┬──────────────┬────┘
│ Yes │ No
▼ ▼
┌──────────┐ ┌──────────┐
│ Attack │ │ Continue │
└──────────┘ └──────────┘
Integration Points:
updateNPCBehaviors()- Check hostile state before behaviorupdateHostileBehavior()- NEW function for chase/attackmoveNPCTowardsTarget()- NEW function using pathfinding- Uses existing pathfinding system
4. Line of Sight (LOS) System
LOS for Hostile NPCs (npc-los.js - EXTENDED)
Current System:
- Detects player in cone-shaped field of view
- Configurable range and angle
- Used for lockpicking detection
Hostile Extensions:
- Dynamic LOS enabling when NPC becomes hostile
- 360-degree vision for hostile NPCs (vs 120° normal)
- Continuous player tracking
- Integration with chase behavior
New Functions:
enableNPCLOS(npc, range, angle)- Turn on LOS dynamicallysetNPCLOSTracking(npc, isTracking)- Toggle tracking mode
5. UI Systems
Player Health UI (player-health-ui.js)
Display Method:
- Heart icons above inventory
- 5 hearts maximum
- Full heart = 20 HP
- Half heart = 10 HP
- Empty heart = 0 HP
Example Displays:
- 100 HP: ❤️❤️❤️❤️❤️
- 70 HP: ❤️❤️❤️💔🖤
- 30 HP: ❤️💔🖤🖤🖤
- 10 HP: 💔🖤🖤🖤🖤
Visibility:
- Hidden when HP = 100 (full health)
- Shows when HP < 100
- Updates in real-time on damage/healing
NPC Health Bar UI (npc-health-ui.js)
Display Method:
- Phaser Graphics object above NPC sprite
- Green fill for current HP
- Red/black background
- White border
- 60x6 pixels
- Positioned 40px above sprite
Lifecycle:
- Created when NPC becomes hostile
- Updated when NPC takes damage
- Follows NPC movement (updated each frame)
- Destroyed when NPC is KO
Game Over UI (game-over-ui.js)
Display:
- Full-screen overlay
- Semi-transparent black background
- Centered content box
- "GAME OVER" message
- Restart button
Triggered:
- Player HP reaches 0
- Player becomes KO
- Player movement disabled
6. Ink Dialogue Integration
Tag Processing (chat-helpers.js - MODIFIED)
New Tag: #hostile or #hostile:npcId
Processing Flow:
Ink Story Reaches Hostile Path
↓
Tag: #hostile:security_guard
↓
processGameActionTags()
↓
processHostileTag(tag, ui)
↓
Extract NPC ID from tag
↓
npcHostileSystem.setNPCHostile(npcId, true)
↓
Emit 'npc_became_hostile' event
↓
Exit conversation (#exit_conversation)
↓
Player back in game world
↓
NPC begins hostile behavior
Tag Usage in Ink:
=== escalate_conflict ===
# speaker:security_guard
You've crossed the line! This is a lockdown!
# hostile:security_guard
# exit_conversation
-> END
Security Guard Updates:
- All paths use hub pattern or
#exit_conversation - Hostile paths trigger
#hostiletag - Conversation exits immediately after hostile trigger
- No more dead-end
-> ENDwithout cleanup
Data Flow Diagrams
Player Damage Flow
NPC in Attack Range
↓
canNPCAttack() → true
↓
npcAttack(npcId, npc)
↓
Play Attack Animation (500ms)
↓
Check Player Still in Range
↓
damagePlayer(attackDamage)
↓
playerHP -= damage
↓
Emit 'player_hp_changed'
↓
updatePlayerHealthUI()
↓
Calculate Hearts from HP
↓
Render Hearts
↓
Check if HP <= 0
↓
setPlayerKO(true)
↓
Emit 'player_ko'
↓
showGameOver()
↓
Disable Player Movement
NPC Becomes Hostile Flow
Player Chooses Hostile Dialogue Option
↓
Ink Reaches Hostile Knot
↓
Tag: #hostile:security_guard
↓
processHostileTag(tag, ui)
↓
setNPCHostile('security_guard', true)
↓
Update npcHostileStates Map
↓
Emit 'npc_became_hostile'
↓
Event Listener Triggered
↓
enableNPCLOS(npc, 400, 360)
↓
createNPCHealthBar(npcId, npc)
↓
Exit Conversation
↓
Update Loop Detects Hostile State
↓
Switch to updateHostileBehavior()
↓
Check Player in LOS
↓
If Yes: Chase Player
↓
If in Attack Range: Attack Player
Player Punches NPC Flow
Player Near Hostile NPC
↓
Press SPACE Key
↓
canPlayerPunch() → true
↓
Get Facing Direction
↓
playPlayerPunchAnimation()
↓
Apply Red Tint + Walk Animation
↓
Wait 500ms
↓
Clear Tint + Return to Idle
↓
Check NPC Still in Range
↓
If Yes: damageNPC(npcId, damage)
↓
npcHP -= damage
↓
updateNPCHealthBar(npcId, currentHP, maxHP)
↓
Redraw Health Bar Fill
↓
Check if npcHP <= 0
↓
If Yes: setNPCKO(npcId, true)
↓
Emit 'npc_ko'
↓
replaceWithKOSprite(scene, npc)
↓
Gray Tinted + Rotated Sprite
↓
destroyNPCHealthBar(npcId)
↓
Disable NPC Behavior Updates
Configuration System
Central Configuration (combat-config.js)
All combat parameters in one place for easy tuning:
{
player: {
maxHP: 100,
punchDamage: 20,
punchRange: 60,
punchCooldown: 1000
},
npc: {
defaultMaxHP: 100,
defaultPunchDamage: 10,
chaseSpeed: 120,
attackRange: 50
},
ui: {
maxHearts: 5,
healthBarWidth: 60,
healthBarHeight: 6
}
}
Why Centralized?
- Easy balancing and tuning
- Consistent values across systems
- No magic numbers in code
- Quick iteration during playtesting
State Management
Global State Extensions
New Window Objects:
window.playerHealth- Player health system instancewindow.npcHostileSystem- NPC hostile state managerwindow.playerCombat- Player combat systemwindow.npcCombat- NPC combat systemwindow.currentPunchTarget- Currently targetable NPC for punch
Existing State Used:
window.player- Player sprite referencewindow.npcManager- NPC registrywindow.eventDispatcher- Event buswindow.currentRoom- Current room IDwindow.pathfinders- Pathfinding per room
Event System
New Events
| Event Name | Payload | Emitted By | Listeners |
|---|---|---|---|
player_hp_changed |
{ hp, maxHP } |
player-health.js | player-health-ui.js |
player_ko |
{ } |
player-health.js | game-over-ui.js, player.js |
npc_hostile_state_changed |
{ npcId, isHostile } |
npc-hostile.js | npc-behavior.js, npc-health-ui.js |
npc_became_hostile |
{ npcId } |
chat-helpers.js | main.js (setup LOS, health bar) |
npc_ko |
{ npcId } |
npc-hostile.js | npc-ko-sprites.js, npc-health-ui.js |
Event Flow Example
Player Takes Damage
↓
damagePlayer(10)
↓
playerHP: 100 → 90
↓
eventDispatcher.emit('player_hp_changed', { hp: 90, maxHP: 100 })
↓
player-health-ui.js receives event
↓
updatePlayerHealthUI()
↓
calculateHearts(90) → 4.5 hearts
↓
Render: ❤️❤️❤️❤️💔
↓
showPlayerHealthUI() (was hidden at 100 HP)
Module Dependencies
Dependency Graph
main.js
├─> player-health.js
│ └─> (no dependencies)
│
├─> player-health-ui.js
│ └─> player-health.js
│
├─> npc-hostile.js
│ └─> combat-config.js
│
├─> npc-health-ui.js
│ └─> npc-hostile.js
│
├─> game-over-ui.js
│ └─> (no dependencies)
│
├─> player-combat.js
│ ├─> player-health.js
│ ├─> npc-hostile.js
│ ├─> combat-animations.js
│ └─> combat-config.js
│
├─> npc-combat.js
│ ├─> player-health.js
│ ├─> npc-hostile.js
│ ├─> combat-animations.js
│ └─> combat-config.js
│
├─> combat-animations.js
│ └─> combat-config.js
│
├─> npc-ko-sprites.js
│ └─> (Phaser only)
│
└─> npc-behavior.js (MODIFIED)
├─> npc-hostile.js
├─> npc-los.js
├─> npc-pathfinding.js (existing)
└─> combat-config.js
Load Order
-
Configuration (no dependencies)
combat-config.js
-
Core Systems (config only)
player-health.jsnpc-hostile.js
-
Animation & Sprites
combat-animations.jsnpc-ko-sprites.js
-
Combat Mechanics (core + animation)
player-combat.jsnpc-combat.js
-
UI Systems (core + combat)
player-health-ui.jsnpc-health-ui.jsgame-over-ui.js
-
Behavior Extensions (all above)
npc-behavior.js(modified)npc-los.js(modified)
-
Integration (all above)
interactions.js(modified)player.js(modified)chat-helpers.js(modified)main.js(modified)
Performance Considerations
Update Loop Optimization
Every Frame:
- Check hostile NPC interactions (limited to current room)
- Update NPC health bar positions (only for hostile NPCs)
- Player/NPC collision detection (existing)
Throttled Updates (existing 50ms):
- NPC behavior updates
- Pathfinding calculations
On-Demand:
- Health UI updates (only on HP change events)
- Game over screen (only on player KO)
- Hostile state changes (only via Ink tags or events)
Memory Management
Cleanup When:
- NPC becomes KO → Destroy health bar graphics
- Player leaves room → Health bars for that room
- Game restarts → Reset all combat state
Persistent State:
- Hostile state per NPC (persists across rooms)
- Player HP (persists across rooms)
- NPC HP (persists while NPC exists)
Optimization Strategies
- Lazy Initialization: Health bars only created when hostile
- Event-Driven UI: Updates only on state changes
- Spatial Partitioning: Only check NPCs in current room
- Object Pooling: Reuse graphics objects when possible
- Throttling: Behavior updates at 50ms intervals
Extension Points
Future Enhancements
Easy to Add:
- Different NPC types with different HP/damage
- Weapons that modify player damage
- Power-ups that heal player
- Special attacks with different animations
- Block/dodge mechanics
- Combo system
Requires More Work:
- Multiplayer combat
- Ranged attacks
- Cover system
- Stealth kills
- Different damage types
- Status effects (stun, slow, etc.)
Customization Per NPC
NPCs can be configured with custom combat stats:
// In scenario JSON
{
"id": "tough_guard",
"hostile": {
"maxHP": 150,
"attackDamage": 15,
"attackRange": 60,
"chaseSpeed": 140
}
}
System will use these values instead of defaults from config.
Testing Strategy
Unit Testing Focus
-
Health Systems
- HP bounds checking (0-100)
- Damage calculation
- Healing calculation
- KO state triggers
-
Combat Systems
- Cooldown timers
- Range checks
- Animation timing
- Damage application
-
State Management
- Hostile state toggle
- State persistence
- State retrieval
Integration Testing Focus
-
Ink → Hostile State
- Tag processing
- State update
- Event emission
-
Hostile → Behavior
- LOS activation
- Chase logic
- Attack triggers
-
Combat → UI
- Health display updates
- Health bar rendering
- Game over trigger
Manual Testing Focus
-
Gameplay Feel
- Combat responsiveness
- Animation clarity
- Visual feedback
- Difficulty balance
-
Edge Cases
- Rapid attacks
- Out-of-range attempts
- Multiple hostile NPCs
- Room transitions
Security Considerations
Input Validation
- Damage values clamped to reasonable ranges
- HP values bounded (0-max)
- NPC IDs validated before state access
- Cooldowns enforced client-side
State Integrity
- HP cannot go negative
- HP cannot exceed max
- Cooldowns cannot be bypassed
- KO state immutable until reset
Cheat Prevention
Not a focus for single-player game, but architecture allows:
- Server-authoritative HP (if multiplayer added)
- Damage verification
- Cooldown verification
- State synchronization
Troubleshooting Guide
Common Issues
Hearts Not Showing
- Check: HP < 100?
- Check: playerHealthUI initialized?
- Check: CSS z-index correct?
- Check: Event listener attached?
NPC Not Chasing
- Check: NPC is hostile?
- Check: LOS enabled?
- Check: Player in LOS range?
- Check: Pathfinder for room exists?
Punch Not Working
- Check: Near hostile NPC?
- Check: Cooldown finished?
- Check: Player not KO?
- Check: SPACE key bound?
Health Bar Missing
- Check: NPC is hostile?
- Check: Health bar created on hostile event?
- Check: Graphics visible in scene?
- Check: Positioned correctly?
Debug Helpers
Add these to window for debugging:
window.debugCombat = {
getPlayerHP: () => window.playerHealth.getPlayerHP(),
setPlayerHP: (hp) => window.playerHealth.setPlayerHP(hp),
makeHostile: (npcId) => window.npcHostileSystem.setNPCHostile(npcId, true),
getNPCState: (npcId) => window.npcHostileSystem.getNPCHostileState(npcId),
showAllHealthBars: () => { /* force show all */ },
resetCombat: () => { /* reset all combat state */ }
};
Summary
This architecture provides:
- Modular Design: Each system has clear responsibilities
- Event-Driven: Loose coupling between systems
- Extensible: Easy to add new features
- Configurable: Tunable parameters for balancing
- Testable: Clear interfaces and dependencies
- Performant: Optimized update loops and cleanup
- Maintainable: Clear code organization and documentation