Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | 2x 2x 96x 96x 96x 96x 53x 96x 96x 53x 53x 53x 53x 96x 96x 96x 96x 96x 96x 96x 83x 45x 45x 45x 45x 96x 31x 96x 29x 29x 29x 29x 29x 29x 96x 96x 41x 55x 246x 246x 217x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 5x 5x 5x 5x 5x 5x 18x 18x 18x 18x 6x 5x 6x 6x 6x 29x 29x 246x 246x 55x 96x | /**
* useAICombat Hook - AI Combat System Integration
*
* Custom hook for AI combat behavior with strategic decision-making.
*
* Manages AI opponent behavior including:
* - Strategic decision-making via DecisionTree
* - Combo attack sequences
* - Adaptive difficulty based on player skill
* - Performance monitoring (<10ms target for decisions)
*
* Side effects:
* - Manages internal state for AI actions and aggression
* - Sets up intervals/timers for AI action scheduling
* - Updates state in response to combat events and round status
*
* @param config Configuration object for AI combat behavior.
* @param config.player The AI-controlled player state.
* @param config.opponent The opponent player state.
* @param config.personality The AI's personality archetype.
* @param config.adaptiveDifficulty Adaptive difficulty system instance.
* @param config.arenaBounds Arena boundaries for movement validation.
* @param config.roundStarted Whether the combat round has started.
* @param config.roundEnded Whether the combat round has ended.
* @param config.isPaused Whether the game is paused.
* @param config.onExecuteAction Callback to execute AI actions.
* @param config.onStanceChange Callback to handle stance changes.
*
* @returns AI combat state and control functions
*
* @example
* ```typescript
* const { aiState } = useAICombat({
* player: aiPlayer,
* opponent: humanPlayer,
* personality: AI_PERSONALITIES.AGGRESSIVE_STRIKER,
* adaptiveDifficulty,
* arenaBounds,
* roundStarted,
* roundEnded,
* isPaused,
* onExecuteAction: handleAction,
* onStanceChange: handleStanceChange,
* });
* ```
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { PlayerState } from "@/systems/player";
import { Position, TrigramStance } from "@/types";
import {
AIPersonality,
AIComboSystem,
AdaptiveDifficulty,
AIDecisionTree,
AIActionType,
CombatContext,
} from "@/systems/ai";
// Performance monitoring constants
const AI_DECISION_THRESHOLD_MS = 10; // Threshold for slow decision warnings
const WARNING_THROTTLE_MS = 5000; // Throttle performance warnings to every 5 seconds
/**
* AI state management
*/
interface AIState {
nextAction: number;
targetPosition: Position;
lastActionType: string;
consecutiveAttacks: number;
actionCooldown: number;
aggressionLevel: number;
}
/**
* AI combat hook configuration
*/
interface UseAICombatConfig {
readonly player: PlayerState;
readonly opponent: PlayerState;
readonly personality: AIPersonality;
readonly adaptiveDifficulty: AdaptiveDifficulty;
readonly isPaused: boolean;
readonly roundStarted: boolean;
readonly roundEnded: boolean;
readonly arenaBounds: {
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
};
readonly onExecuteAction: (action: string, targetPosition?: Position) => void;
readonly onStanceChange?: (stance: TrigramStance) => void;
}
/**
* AI combat hook return type
*/
interface UseAICombatReturn {
readonly aiState: AIState;
readonly comboSystem: AIComboSystem;
readonly decisionTree: AIDecisionTree;
readonly adjustedPersonality: AIPersonality;
readonly executeAIAction: (action: string, targetPosition?: Position) => void;
}
/**
* Custom hook for AI combat behavior
*/
export function useAICombat(config: UseAICombatConfig): UseAICombatReturn {
const {
player,
opponent,
personality,
adaptiveDifficulty,
isPaused,
roundStarted,
roundEnded,
arenaBounds,
onExecuteAction,
onStanceChange,
} = config;
// Initialize AI systems (persist across renders)
const comboSystem = useMemo(() => new AIComboSystem(), []);
const decisionTree = useMemo(() => new AIDecisionTree(), []);
// Adjust personality based on player skill
const adjustedPersonality = useMemo(
() => adaptiveDifficulty.adjustAIPersonality(personality),
[adaptiveDifficulty, personality]
);
// Update AI difficulty level based on adaptive difficulty (only when skill level meaningfully changes)
const lastSkillLevelRef = useRef(0.5);
useEffect(() => {
const newSkillLevel = adaptiveDifficulty.calculatePlayerSkill();
// Only update if skill level changed by more than 1%
Eif (Math.abs(newSkillLevel - lastSkillLevelRef.current) > 0.01) {
lastSkillLevelRef.current = newSkillLevel;
decisionTree.setDifficultyLevel(newSkillLevel);
}
}, [adaptiveDifficulty, decisionTree]);
// AI state
const [aiState, setAiState] = useState<AIState>({
nextAction: Date.now(),
targetPosition: player.position,
lastActionType: "idle",
consecutiveAttacks: 0,
actionCooldown: 500,
aggressionLevel: adjustedPersonality.aggressionLevel,
});
// Performance tracking
const lastDecisionTimeRef = useRef(0);
const matchStartTimeRef = useRef(Date.now());
const previousDamageRef = useRef(0);
const nextActionRef = useRef(Date.now());
const lastWarningTimeRef = useRef(0);
// Initialize previousDamageRef when round starts (issue #2529728007)
useEffect(() => {
if (roundStarted) {
matchStartTimeRef.current = Date.now();
previousDamageRef.current = player.totalDamageReceived;
decisionTree.reset();
comboSystem.resetCombo();
}
}, [roundStarted, decisionTree, comboSystem, player.totalDamageReceived]);
/**
* Execute AI action callback
*/
const executeAIAction = useCallback(
(action: string, targetPosition?: Position) => {
onExecuteAction(action, targetPosition);
},
[onExecuteAction]
);
/**
* Build combat context for decision-making
*/
const buildCombatContext = useCallback((): CombatContext => {
const dx = player.position.x - opponent.position.x;
const dy = player.position.y - opponent.position.y;
const distance = Math.sqrt(dx * dx + dy * dy);
// Calculate recent damage taken (fix for issue #2529467021)
const recentDamageTaken = Math.max(
0,
player.totalDamageReceived - previousDamageRef.current
);
previousDamageRef.current = player.totalDamageReceived;
return {
playerPosition: player.position,
opponentPosition: opponent.position,
playerHealth: player.health,
playerMaxHealth: player.maxHealth,
playerKi: player.ki,
playerMaxKi: player.maxKi,
playerStamina: player.stamina,
playerMaxStamina: player.maxStamina,
opponentHealth: opponent.health,
opponentStance: opponent.currentStance,
playerStance: player.currentStance,
distanceToOpponent: distance,
timeInMatch: Date.now() - matchStartTimeRef.current,
isOpponentAttacking: opponent.combatState === "attacking",
recentDamageTaken,
arenaBounds,
};
}, [player, opponent, arenaBounds]);
/**
* AI decision loop (fixed memory leak - issue #2529466989)
*/
useEffect(() => {
if (isPaused || !roundStarted || roundEnded) {
return;
}
const aiInterval = setInterval(() => {
const now = Date.now();
// Respect next action time using ref (prevents stale closure)
if (now < nextActionRef.current) {
return;
}
// Performance: track decision time
const decisionStart = performance.now();
// Build combat context
const context = buildCombatContext();
// Make strategic decision
const decision = decisionTree.makeDecision(
context,
adjustedPersonality,
comboSystem
);
// Performance: warn if decision took too long with time-based throttle (issue #2529466997, #2529728019)
const decisionTime = performance.now() - decisionStart;
Iif (decisionTime > AI_DECISION_THRESHOLD_MS) {
const now = Date.now();
if (now - lastWarningTimeRef.current > WARNING_THROTTLE_MS) {
// Only warn every 5 seconds
console.warn(`AI decisions running slow: ${decisionTime.toFixed(2)}ms`);
lastWarningTimeRef.current = now;
}
}
lastDecisionTimeRef.current = decisionTime;
// Execute decision
let actionType = "idle";
let newTargetPosition = aiState.targetPosition;
let newConsecutiveAttacks = aiState.consecutiveAttacks;
switch (decision.action) {
case AIActionType.ATTACK:
actionType = "attack";
newConsecutiveAttacks++;
break;
case AIActionType.TECHNIQUE:
actionType = "technique";
newConsecutiveAttacks++;
break;
case AIActionType.COMBO:
// Start or continue combo
Eif (!comboSystem.isComboActive()) {
comboSystem.startCombo(player, opponent, adjustedPersonality);
}
Iif (comboSystem.shouldContinueCombo(player, opponent, adjustedPersonality)) {
const technique = comboSystem.getNextComboTechnique();
actionType = technique ? "technique" : "attack";
newConsecutiveAttacks++;
} else {
comboSystem.resetCombo();
actionType = "idle";
}
break;
case AIActionType.DEFEND:
actionType = "defend";
newConsecutiveAttacks = 0;
break;
case AIActionType.COUNTER:
actionType = "counter";
newConsecutiveAttacks = 0;
break;
case AIActionType.RETREAT:
actionType = "retreat";
newTargetPosition = decision.targetPosition ?? aiState.targetPosition;
newConsecutiveAttacks = 0;
break;
case AIActionType.APPROACH:
actionType = "approach";
newTargetPosition = decision.targetPosition ?? opponent.position;
newConsecutiveAttacks = 0;
break;
case AIActionType.CIRCLE:
actionType = "circle";
newTargetPosition = decision.targetPosition ?? aiState.targetPosition;
newConsecutiveAttacks = 0;
break;
case AIActionType.STANCE_CHANGE:
if (decision.targetStance && onStanceChange) {
onStanceChange(decision.targetStance);
}
actionType = "idle";
newConsecutiveAttacks = 0;
break;
case AIActionType.FEINT:
actionType = "feint";
newConsecutiveAttacks = 0;
break;
case AIActionType.WAIT:
default:
actionType = "idle";
newConsecutiveAttacks = 0;
break;
}
// Execute action
executeAIAction(actionType, newTargetPosition);
// Calculate next action cooldown
const actionCooldown =
actionType === "attack" || actionType === "technique" ? 600 : 400;
// Update next action time using ref (prevents stale closure)
nextActionRef.current = now + actionCooldown + Math.random() * 200;
// Update AI state
setAiState({
nextAction: nextActionRef.current,
targetPosition: newTargetPosition,
lastActionType: actionType,
consecutiveAttacks: newConsecutiveAttacks,
actionCooldown,
aggressionLevel: adjustedPersonality.aggressionLevel,
});
}, 50); // 50ms loop for responsive AI
return () => clearInterval(aiInterval);
}, [
isPaused,
roundStarted,
roundEnded,
buildCombatContext,
decisionTree,
adjustedPersonality,
comboSystem,
executeAIAction,
onStanceChange,
player,
opponent,
aiState,
]);
return {
aiState,
comboSystem,
decisionTree,
adjustedPersonality,
executeAIAction,
};
}
|