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 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 | 3x 3x 13x 13x 13x 93x 93x 93x 93x 93x 93x 93x 13x 13x 14x 7x 13x 28x 28x 28x 28x 28x 28x 28x 28x 28x 2x 2x 2x 140x 2x 2x 2x 74x 2x 2x 210x 210x 210x 210x 210x 210x 210x 2x 420x 420x 420x 13x 13x 13x 13x 13x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 11x 6x 5x 11x 11x 2x 2x 11x 2x 2x 11x 2x 2x 9x 9x 9x 24x 24x 14x 14x 14x 14x 100x 2x 2x 13x 13x 13x 13x 13x 11x 11x 13x 13x 11x 11x 171x 11x 11x 11x 13x 2x 13x 2x 2x 2x 2x 2x 2x 2x 2x 11x 196x 196x 196x 196x 114x 196x 196x 114x 114x 88x 88x 196x 89x 196x 89x 196x 196x 196x 196x 89x 89x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 196x 89x 1756x 196x 196x 196x 123x 81x 81x 81x 81x 81x 81x 81x 196x 124x 47x 77x 196x 124x 47x 77x 77x 44x 44x 44x 44x 44x 44x 44x 77x 77x 77x 77x 196x 89x 196x 3764x 196x 196x 3762x 3762x 3762x 3762x 3762x 3762x 3762x 196x 196x 47x 149x 18631x 18631x 14869x 3762x 3762x 3762x 3762x 3762x 3762x 3762x 3762x 3762x 3762x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 11x 11x 11x 11x 11x 11x 11x 2x 2x 2x 2x 2x 2x 8x 8x 8x 8x 890x 890x 890x 890x 10x 10x 10x 10x 2839x 2839x 2839x 3762x 3762x 18631x 18631x 3762x 3762x 2x 2x 3762x 18631x 149x 196x | /**
* 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 { getArchetypePhysicalAttributes } from "@/data/archetypePhysicalAttributes";
import {
AdaptiveDifficulty,
AIActionType,
AIComboSystem,
AIDecisionTree,
AIPersonality,
CombatContext,
DifficultyParameters,
getArchetypeBehavior,
getNextComboTechnique,
getSignatureMove,
interpolateDifficultyParameters,
shouldExecuteSignatureMove,
} from "@/systems/ai";
import { physicalReachCalculator } from "@/systems/physics";
import { PlayerState } from "@/systems/player";
import { KoreanTechniquesSystem } from "@/systems/trigram/KoreanTechniques";
import { KOREAN_VITAL_POINTS } from "@/systems/vitalpoint/KoreanVitalPoints";
import { KoreanTechnique } from "@/systems/vitalpoint/types";
import {
CombatAttackType,
DamageType,
PlayerArchetype,
Position,
TrigramStance,
} from "@/types";
import { STANCE_REACH_MODIFIERS } from "@/types/physics";
import { getBalanceState } from "@/utils/player3DHelpers";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
// 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
/**
* Technique range system (physics-first: meters)
* All distances and ranges are in meters - no pixel conversions for game logic
*
* Each technique has a reachConfig with baseExtension multiplier
* Applied to archetype's limb length: reach = (limbLength/100) × baseExtension × stanceModifier
*
* @korean 기술 범위 시스템 (물리 우선: 미터)
*/
/**
* Get viable techniques based on distance, stance, and stamina
*
* Filters techniques that:
* - Match current stance
* - Are within effective range of opponent
* - Have sufficient stamina to execute
* - Applies selection bias against recently used techniques (avoid >70% repetition)
*
* @korean 거리, 자세, 체력에 따른 실행 가능한 기술 선택
*
* @param distance - Distance to opponent in meters (physics-first)
* @param stance - Current trigram stance
* @param stamina - Available stamina
* @param archetype - Player archetype for specialized techniques
* @param recentTechniques - Array of recently used technique IDs (for variation)
* @returns Array of viable techniques sorted by effectiveness with variation bias
*/
function getViableTechniques(
distance: number,
stance: TrigramStance,
stamina: number,
archetype: PlayerState["archetype"],
recentTechniques: string[] = [],
): readonly KoreanTechnique[] {
// Get all available techniques for stance and archetype
const stanceTechniques = KoreanTechniquesSystem.getAllAvailableTechniques(
stance,
archetype,
);
// Early return if no techniques available
Iif (stanceTechniques.length === 0) {
return [];
}
// Filter techniques that are viable for current situation
const viableTechniques = stanceTechniques.filter((tech) => {
// Calculate technique effective range using Physical ReachCalculator
// Get AI player's physical attributes
const physicalAttributes = getArchetypePhysicalAttributes(archetype);
// Calculate maximum reach for this technique
// Use animationType if available, otherwise derive from reachConfig
const animType = tech.animationType;
let maxReach: number;
if (animType) {
// Use PhysicalReachCalculator with animation timing
maxReach = physicalReachCalculator.calculateMaxReach(
physicalAttributes,
animType,
stance,
);
} else E{
// Fallback: Calculate reach directly from reachConfig
// This ensures consistency with technique definitions when no animation type
const limbLength =
tech.reachConfig.bodyPart === "leg"
? physicalAttributes.legLength
: physicalAttributes.armLength;
// Apply body pivot/offset based on technique type (matching PhysicalReachCalculator logic)
// Kicks: hip rotation + torso lean = 0.25m
// Punches: shoulder offset + torso rotation = shoulderWidth/2 + 0.1m
let bodyPivot: number;
if (tech.reachConfig.bodyPart === "leg") {
bodyPivot = 0.25; // meters for kicks
} else {
// Arm-based: shoulder offset + torso rotation
const shoulderOffset = physicalAttributes.shoulderWidth / 2 / 100;
const torsoRotation = 0.1;
bodyPivot = shoulderOffset + torsoRotation;
}
// Apply stance modifier using actual stance-specific modifiers
const stanceModifier = STANCE_REACH_MODIFIERS[stance];
// Convert cm to meters, add body pivot, and apply modifiers
maxReach =
(limbLength / 100 + bodyPivot) *
tech.reachConfig.baseExtension *
stanceModifier;
}
// All distances are in METERS - no pixel conversion needed
// Check if opponent is within technique range
const inRange = distance <= maxReach;
// Check if player has sufficient stamina
const hasStamina = stamina >= tech.staminaCost;
return inRange && hasStamina;
});
// Pre-compute recent use counts for efficiency (avoid O(n²×m) in sort)
const recentUseCounts = new Map<string, number>();
for (const tech of viableTechniques) {
recentUseCounts.set(
tech.id,
recentTechniques.filter((id) => id === tech.id).length,
);
}
// Sort by effectiveness with variation bias
return viableTechniques.sort((a, b) => {
// Base effectiveness: damage × accuracy
const baseEffectivenessA = (a.damage ?? 0) * (a.accuracy ?? 0.8);
const baseEffectivenessB = (b.damage ?? 0) * (b.accuracy ?? 0.8);
// Apply penalty for recently used techniques (avoid repetition)
const recentUsesA = recentUseCounts.get(a.id) ?? 0;
const recentUsesB = recentUseCounts.get(b.id) ?? 0;
// Penalty: 20% reduction per recent use (max 60% penalty for 3+ uses)
const penaltyA = Math.min(0.6, recentUsesA * 0.2);
const penaltyB = Math.min(0.6, recentUsesB * 0.2);
const finalEffectivenessA = baseEffectivenessA * (1 - penaltyA);
const finalEffectivenessB = baseEffectivenessB * (1 - penaltyB);
return finalEffectivenessB - finalEffectivenessA;
});
}
/**
* Select optimal vital point for attack based on stance compatibility and archetype priority
*
* Prioritizes vital points by:
* 1. Archetype vital target priority (health/pain/consciousness/balanced)
* 2. Stance compatibility (must be in effectiveStances array)
* 3. Base damage threshold (>25 damage preferred)
* 4. Targeting difficulty vs AI skill level
*
* @korean 자세 효과 및 원형 우선순위에 따른 최적 급소 선택
*
* @param stance - Current trigram stance
* @param difficultyLevel - AI difficulty level (0.0-1.0)
* @param archetype - Player archetype for priority targeting
* @returns Vital point ID or null if no suitable target
*/
function selectOptimalVitalPoint(
stance: TrigramStance,
difficultyLevel: number,
archetype: PlayerState["archetype"],
): string | null {
// Guard: Ensure vital points are available
Iif (KOREAN_VITAL_POINTS.length === 0) {
return null;
}
// Get archetype behavior for vital point priority
const behavior = getArchetypeBehavior(archetype);
// Filter vital points effective for current stance
const effectivePoints = KOREAN_VITAL_POINTS.filter((point) =>
point.effectiveStances?.includes(stance),
);
Iif (effectivePoints.length === 0) {
// Fallback: select any vital point if no stance-specific ones available
const fallbackPoint =
KOREAN_VITAL_POINTS[
Math.floor(Math.random() * KOREAN_VITAL_POINTS.length)
];
return fallbackPoint?.id ?? null;
}
// Damage threshold for high-priority targets
const HIGH_DAMAGE_THRESHOLD = 25;
// Filter by damage threshold (prefer high-damage vital points)
const highDamagePoints = effectivePoints.filter(
(point) => (point.baseDamage ?? 0) > HIGH_DAMAGE_THRESHOLD,
);
const targetPoints =
highDamagePoints.length > 0 ? highDamagePoints : effectivePoints;
// Sort by targeting suitability based on AI difficulty AND archetype priority
const sortedPoints = [...targetPoints].sort((a, b) => {
// Calculate base suitability score
const baseSuitabilityA =
(a.baseDamage ?? 0) *
(1 - Math.abs(difficultyLevel - a.targetingDifficulty));
const baseSuitabilityB =
(b.baseDamage ?? 0) *
(1 - Math.abs(difficultyLevel - b.targetingDifficulty));
// Apply archetype priority multiplier
const priorityMultiplierA = getVitalPointPriorityScore(
a,
behavior.vitalTargetPriority,
);
const priorityMultiplierB = getVitalPointPriorityScore(
b,
behavior.vitalTargetPriority,
);
const finalSuitabilityA = baseSuitabilityA * priorityMultiplierA;
const finalSuitabilityB = baseSuitabilityB * priorityMultiplierB;
return finalSuitabilityB - finalSuitabilityA;
});
// Select top-rated target
return sortedPoints[0]?.id ?? null;
}
/**
* Calculate priority score for vital point based on archetype targeting preference
*
* @korean 원형 타격 우선순위 점수 계산
*
* @param vitalPoint - Vital point to score
* @param priority - Archetype vital target priority
* @returns Priority multiplier (1.0 = neutral, >1.0 = preferred, <1.0 = deprioritized)
*/
function getVitalPointPriorityScore(
vitalPoint: (typeof KOREAN_VITAL_POINTS)[0],
priority: import("@/systems/ai/AIPersonality").VitalTargetPriority,
): number {
// Import effect types to check vital point effects
const effects = vitalPoint.effects ?? [];
switch (priority) {
case "health":
// Jojik - prioritize high base damage
return (vitalPoint.baseDamage ?? 0) > 30 ? 1.5 : 1.0;
case "pain":
// Jeongbo - prioritize pain-inducing effects
// Check if effects include pain or disorientation
const hasPainEffect = effects.some(
(e) =>
String(e).toLowerCase().includes("pain") ||
String(e).toLowerCase().includes("disorientation"),
);
return hasPainEffect ? 1.5 : 1.0;
case "consciousness":
// Amsalja - prioritize consciousness-affecting strikes
// Check if effects include unconsciousness, stun, or breathlessness
const hasConsciousnessEffect = effects.some(
(e) =>
String(e).toLowerCase().includes("unconscious") ||
String(e).toLowerCase().includes("stun") ||
String(e).toLowerCase().includes("breathless"),
);
return hasConsciousnessEffect ? 1.5 : 1.0;
case "balanced":
default:
// Musa, Hacker - balanced approach
return 1.0;
}
}
/**
* Check if a technique is a signature move for the given archetype
*
* Signature techniques are identified by:
* - Damage type and attack type matching archetype preferences
* - Ki/Stamina costs indicating advanced techniques
* - Specific technique characteristics (e.g., nerve strikes for Amsalja)
*
* @korean 원형 대표 기술 확인
*
* @param technique - Technique to check
* @param archetype - Player archetype
* @returns True if technique is signature for the archetype
*/
function isSignatureTechnique(
technique: KoreanTechnique,
archetype: PlayerState["archetype"],
): boolean {
const damageType = technique.damageType;
const attackType = technique.type;
const isAdvanced =
(technique.kiCost ?? 0) >= 10 || (technique.staminaCost ?? 0) >= 15;
switch (archetype) {
case PlayerArchetype.MUSA:
// Musa: Joint manipulation (JOINT damage) and bone strikes (CRUSHING/BLUNT)
return (
damageType === DamageType.JOINT ||
damageType === DamageType.CRUSHING ||
(damageType === DamageType.BLUNT && isAdvanced)
);
case PlayerArchetype.AMSALJA:
// Amsalja: Nerve strikes (NERVE damage) and silent takedowns (pressure points)
return (
damageType === DamageType.NERVE ||
damageType === DamageType.PRESSURE ||
attackType === CombatAttackType.NERVE_STRIKE ||
attackType === CombatAttackType.PRESSURE_POINT
);
case PlayerArchetype.HACKER:
// Hacker: Anatomical analysis (INTERNAL/NERVE) and calculated strikes
return (
damageType === DamageType.INTERNAL ||
damageType === DamageType.NERVE ||
(isAdvanced && (technique.accuracy ?? 0) >= 0.8) // High accuracy represents calculation
);
case PlayerArchetype.JEONGBO_YOWON:
// Jeongbo: Psychological pressure (PRESSURE) and submission techniques (JOINT)
return (
damageType === DamageType.PRESSURE ||
damageType === DamageType.JOINT ||
attackType === CombatAttackType.GRAPPLE
);
case PlayerArchetype.JOJIK_POKRYEOKBAE:
// Jojik: Dirty techniques (any high-damage strike) and environmental usage
return (
(technique.damage ?? 0) >= 30 || // High raw damage
damageType === DamageType.SLASHING || // Brutal cutting
damageType === DamageType.PIERCING // Dirty stabbing techniques
);
default:
return false;
}
}
/**
* Update technique usage frequency and rotation queue
*
* Tracks technique usage for diversity enforcement:
* 1. Updates usage frequency counter
* 2. Adds to recent techniques queue (last 5)
* 3. Marks as used in current match
* 4. Resets "all used" when all 4 archetype techniques completed
*
* @korean 기술 사용 빈도 및 순환 큐 업데이트
*
* @param techniqueId - ID of technique just used
* @param rotationQueue - Technique rotation tracking object
* @param archetypeTechniqueIds - All technique IDs for this archetype (for reset detection)
*/
function updateTechniqueRotation(
techniqueId: string,
rotationQueue: TechniqueRotationQueue,
archetypeTechniqueIds: Set<string>,
): void {
// Update frequency counter
const current = rotationQueue.frequency.get(techniqueId) ?? 0;
rotationQueue.frequency.set(techniqueId, current + 1);
// Increment total attacks
rotationQueue.totalAttacks++;
// Add to recent queue (last 5)
rotationQueue.used.push(techniqueId);
Iif (rotationQueue.used.length > 5) {
rotationQueue.used.shift(); // Keep only last 5
}
// Mark as used in this match
rotationQueue.allUsed.add(techniqueId);
// Reset "all used" if all archetype techniques have been used
// This ensures AI cycles through full arsenal repeatedly
let allTechniquesUsed = true;
for (const techId of archetypeTechniqueIds) {
Eif (!rotationQueue.allUsed.has(techId)) {
allTechniquesUsed = false;
break;
}
}
Iif (allTechniquesUsed) {
rotationQueue.allUsed.clear();
}
}
/**
* Check if technique is overused (exceeds 40% threshold)
*
* Enforces variety by identifying techniques that have been
* used more than 40% of total attacks.
*
* @korean 기술 과다 사용 확인 (40% 임계값)
*
* @param techniqueId - Technique ID to check
* @param rotationQueue - Technique rotation tracking object
* @returns True if technique exceeds 40% usage threshold
*/
function isOverused(
techniqueId: string,
rotationQueue: TechniqueRotationQueue,
): boolean {
if (rotationQueue.totalAttacks === 0) {
return false;
}
const uses = rotationQueue.frequency.get(techniqueId) ?? 0;
const percentage = uses / rotationQueue.totalAttacks;
return percentage > 0.4; // >40% threshold
}
/**
* Select technique with rotation bias for diversity
*
* Prioritizes techniques in this order:
* 1. Never used in this match (highest priority)
* 2. Not used in last 5 techniques (avoid repetition)
* 3. Any viable technique (fallback)
*
* Within each priority tier, selects by effectiveness (damage × accuracy).
*
* @korean 다양성을 위한 순환 편향 기술 선택
*
* @param viableTechniques - Techniques that are viable (range, stamina, stance)
* @param rotationQueue - Technique rotation tracking object
* @returns Best technique with rotation bias applied
*/
function selectTechniqueWithRotation(
viableTechniques: readonly KoreanTechnique[],
rotationQueue: TechniqueRotationQueue,
): KoreanTechnique | undefined {
Iif (viableTechniques.length === 0) {
return undefined;
}
// Filter out overused techniques (>40% threshold)
const balancedTechniques = viableTechniques.filter(
(t) => !isOverused(t.id, rotationQueue),
);
// If all techniques overused (rare), reset frequency tracking and use any
const candidates =
balancedTechniques.length > 0 ? balancedTechniques : viableTechniques;
Iif (balancedTechniques.length === 0 && rotationQueue.totalAttacks > 0) {
// Reset frequency to allow reuse and realign total count
rotationQueue.frequency.clear();
rotationQueue.totalAttacks = 0;
}
// Priority 1: Never used in this match
const neverUsed = candidates.filter((t) => !rotationQueue.allUsed.has(t.id));
Eif (neverUsed.length > 0) {
// Sort by effectiveness within never-used tier
return [...neverUsed].sort((a, b) => {
const effA = (a.damage ?? 0) * (a.accuracy ?? 0.8);
const effB = (b.damage ?? 0) * (b.accuracy ?? 0.8);
return effB - effA;
})[0];
}
// Priority 2: Not in last 5 techniques
const unusedRecently = candidates.filter(
(t) => !rotationQueue.used.includes(t.id),
);
if (unusedRecently.length > 0) {
// Sort by effectiveness within unused-recently tier
return [...unusedRecently].sort((a, b) => {
const effA = (a.damage ?? 0) * (a.accuracy ?? 0.8);
const effB = (b.damage ?? 0) * (b.accuracy ?? 0.8);
return effB - effA;
})[0];
}
// Priority 3: Any viable technique (all used recently)
// Sort by effectiveness
return [...candidates].sort((a, b) => {
const effA = (a.damage ?? 0) * (a.accuracy ?? 0.8);
const effB = (b.damage ?? 0) * (b.accuracy ?? 0.8);
return effB - effA;
})[0];
}
/**
* Filter techniques by cooldown availability
*
* Returns only techniques that are off cooldown and ready to use.
* If all techniques are on cooldown, returns empty array.
*
* @korean 재사용 대기시간별 기술 필터링
*
* @param techniques - Techniques to filter
* @param cooldownMap - Map of technique ID to last use timestamp
* @returns Techniques that are off cooldown
*/
function filterByCooldown(
techniques: readonly KoreanTechnique[],
cooldownMap: TechniqueCooldownMap,
): readonly KoreanTechnique[] {
const now = Date.now();
return techniques.filter((t) => {
const lastUsed = cooldownMap.get(t.id) ?? 0;
const cooldown = (t.recoveryTime ?? 0) + (t.executionTime ?? 0); // Total cooldown time
const timeSinceUse = now - lastUsed;
return timeSinceUse >= cooldown;
});
}
/**
* Get all techniques for an archetype (for cross-stance usage)
*
* Returns all 4 techniques available to the archetype,
* regardless of stance requirements.
*
* @korean 원형의 모든 기술 가져오기 (교차 자세 사용)
*
* @param archetype - Player archetype
* @returns All techniques for the archetype
*/
function getAllArchetypeTechniques(
archetype: PlayerState["archetype"],
): readonly KoreanTechnique[] {
// Use KoreanTechniquesSystem to efficiently get all techniques for archetype
// This avoids iterating through all 8 stances
return KoreanTechniquesSystem.getTechniquesByArchetype(archetype);
}
/**
* Apply cross-stance damage modifier to technique
*
* Creates a modified copy of the technique with 80% damage for cross-stance usage.
* This prevents mutation of the original technique object.
*
* **Design Rationale for 80% Effectiveness:**
* Cross-stance techniques are performed from a non-optimal stance, reducing
* power generation and body mechanics efficiency. The 80% modifier reflects:
* - Suboptimal weight transfer and leverage
* - Reduced muscle engagement from non-ideal positioning
* - Decreased stability and balance during execution
*
* This is consistent with Korean martial arts philosophy where proper stance
* (자세) is fundamental to technique effectiveness. Other properties like
* accuracy and execution time remain unchanged as the technique mechanics
* themselves are unchanged, only the power generation is affected.
*
* @korean 교차 자세 피해 배율 적용 (80% 효과)
*
* @param technique - Original technique
* @param isCrossStance - Whether technique is from different stance
* @returns Modified technique with 80% damage if cross-stance, original otherwise
*/
function applyCrossStanceDamageModifier(
technique: KoreanTechnique,
isCrossStance: boolean,
): KoreanTechnique {
Eif (!isCrossStance || !technique.damage) {
return technique;
}
// Create modified copy with 80% damage
return {
...technique,
damage: Math.floor(technique.damage * 0.8),
};
}
/**
* Helper to select technique for AI action with rotation and cooldown awareness
*
* Enhanced technique selection with:
* - Technique rotation queue for diversity (prevents >70% repetition → targets <40%)
* - Cooldown-aware filtering (prioritizes ready techniques)
* - Cross-stance fallback (uses other techniques at 80% effectiveness)
* - Archetype signature bias (maintains 40%+ signature technique usage)
*
* @korean 순환 및 재사용 대기시간을 고려한 기술 선택
*
* @param isSpecialTechnique - Whether to filter for high-cost special techniques
* @param context - Current combat context
* @param player - AI player state
* @param adaptiveDifficulty - Adaptive difficulty system
* @param rotationQueue - Technique rotation tracking object
* @param cooldownMap - Technique cooldown tracking map
* @returns Selected technique, vital point, action type, and cross-stance flag
*/
function selectTechniqueForAction(
isSpecialTechnique: boolean,
context: CombatContext,
player: PlayerState,
adaptiveDifficulty: AdaptiveDifficulty,
rotationQueue: TechniqueRotationQueue,
cooldownMap: TechniqueCooldownMap,
): {
technique?: KoreanTechnique;
vitalPoint?: string;
actionType: string;
isCrossStance?: boolean;
} {
// Check for signature move condition (Issue #enforce-distinct-combat-philosophies)
// This provides archetype-specific finishing moves under specific conditions
Iif (shouldExecuteSignatureMove(player.archetype, context)) {
const signatureMoveId = getSignatureMove(player.archetype);
const allTechniques = getAllArchetypeTechniques(player.archetype);
const signatureTechnique = allTechniques.find(
(t) => t.id === signatureMoveId,
);
if (signatureTechnique) {
// Check if signature move is off cooldown
const now = Date.now();
const lastUsed = cooldownMap.get(signatureMoveId) ?? 0;
// Use consistent cooldown calculation (same as filterByCooldown)
// Cooldown = recoveryTime + executionTime for KoreanTechnique
const techniqueCooldown =
(signatureTechnique.recoveryTime ?? 0) +
(signatureTechnique.executionTime ?? 0);
const cooldownRemaining = Math.max(
0,
techniqueCooldown - (now - lastUsed),
);
// Only execute signature if off cooldown and have resources
if (
cooldownRemaining === 0 &&
player.stamina >= signatureTechnique.staminaCost &&
player.ki >= signatureTechnique.kiCost
) {
console.log(
`[AI] Executing signature move: ${signatureMoveId} for ${player.archetype}`,
);
const difficultyLevel = adaptiveDifficulty.calculatePlayerSkill();
const vitalPoint =
selectOptimalVitalPoint(
player.currentStance,
difficultyLevel,
player.archetype,
) ?? undefined;
return {
technique: signatureTechnique,
vitalPoint,
actionType: "signature_move",
isCrossStance: signatureTechnique.stance !== player.currentStance,
};
}
}
}
// Get viable techniques for current stance
const viableTechniques = getViableTechniques(
context.distanceToOpponent,
player.currentStance,
player.stamina,
player.archetype,
rotationQueue.used, // Pass recent techniques for penalty
);
// Filter by cooldown availability
const readyTechniques = filterByCooldown(viableTechniques, cooldownMap);
// Use ready techniques if available, otherwise check cooldowns
let candidates =
readyTechniques.length > 0 ? readyTechniques : viableTechniques;
// Filter for special techniques if requested
if (isSpecialTechnique) {
const specialCandidates = candidates.filter(
(tech) => tech.kiCost >= 10 || tech.staminaCost >= 15,
);
candidates = specialCandidates.length > 0 ? specialCandidates : candidates;
}
// If no viable techniques for current stance, try cross-stance techniques
let isCrossStance = false;
if (candidates.length === 0) {
const allTechniques = getAllArchetypeTechniques(player.archetype);
const crossStanceTechniques = allTechniques.filter(
(t) =>
t.stance !== player.currentStance &&
// Physics-first: Compare meters to meters
context.distanceToOpponent <= (t.reachConfig?.baseExtension ?? 1.0) &&
player.stamina >= t.staminaCost &&
!isOverused(t.id, rotationQueue), // Apply rotation diversity to cross-stance
);
// Filter by cooldown for cross-stance techniques too
const readyCrossStance = filterByCooldown(
crossStanceTechniques,
cooldownMap,
);
candidates =
readyCrossStance.length > 0 ? readyCrossStance : crossStanceTechniques;
isCrossStance = candidates.length > 0;
}
if (candidates.length > 0) {
// Filter signature techniques once for efficiency
const signatureTechniques = candidates.filter((tech) =>
isSignatureTechnique(tech, player.archetype),
);
// Apply 60% bias toward signature techniques
// Determine category first, then select best technique within category
const useSignature = signatureTechniques.length > 0 && Math.random() < 0.6;
const selectedCandidates = useSignature ? signatureTechniques : candidates;
const technique = selectTechniqueWithRotation(
selectedCandidates,
rotationQueue,
);
Eif (technique) {
const difficultyLevel = adaptiveDifficulty.calculatePlayerSkill();
const vitalPoint =
selectOptimalVitalPoint(
player.currentStance,
difficultyLevel,
player.archetype,
) ?? undefined;
// Apply cross-stance damage modifier if needed
const finalTechnique = applyCrossStanceDamageModifier(
technique,
isCrossStance,
);
return {
technique: finalTechnique,
vitalPoint,
actionType: isSpecialTechnique ? "technique" : "attack",
isCrossStance,
};
}
}
return { actionType: "idle" };
}
/**
* Determine if AI should switch stance laterality based on personality and tactical situation.
*
* Strategic laterality decisions in Korean martial arts:
* - **Aggressive personality**: Prefers matched stances (same laterality) for offensive advantage
* Matched stances expose centerlines, creating attack opportunities
* - **Defensive personality**: Prefers mismatched stances (opposite laterality) for protection
* Mismatched stances naturally guard centerlines with lead hand
* - **Health-based modifier**: Low health increases defensive preference
*
* @param aiLaterality - AI's current stance laterality
* @param opponentLaterality - Opponent's stance laterality
* @param personality - AI personality archetype
* @param aiHealth - AI's current health (0-100)
* @param lastSwitchTime - Timestamp of last laterality switch
* @param currentTime - Current timestamp for cooldown check
* @returns true if AI should switch laterality, false otherwise
*
* @korean AI 측면성 전환 결정
*/
function shouldAISwitchLaterality(
aiLaterality: "left" | "right",
opponentLaterality: "left" | "right",
personality: AIPersonality,
aiHealth: number,
lastSwitchTime: number,
currentTime: number,
): boolean {
// Cooldown: Don't switch more than once per 3 seconds
const LATERALITY_COOLDOWN = 3000;
if (currentTime - lastSwitchTime < LATERALITY_COOLDOWN) {
return false;
}
const isMatched = aiLaterality === opponentLaterality;
// Aggressive AI: Prefer matched stances (offensive advantage)
// Defensive AI: Prefer mismatched stances (defensive protection)
const aggressionFactor = personality.aggressionLevel;
const defenseFactor = personality.defensePreference;
// Health-based modifier: Lower health increases defensive behavior
const healthFactor = aiHealth / 100;
const effectiveAggression = aggressionFactor * Math.max(0.3, healthFactor);
const effectiveDefense = defenseFactor * (1.2 - healthFactor * 0.2);
// Aggressive AI wants matched stances
if (effectiveAggression > 0.6 && !isMatched) {
return Math.random() < 0.3; // 30% chance to switch to matched
}
// Defensive AI wants mismatched stances
if (effectiveDefense > 0.6 && isMatched) {
return Math.random() < 0.25; // 25% chance to switch to mismatched
}
// Low health emergency: Switch to defensive mismatch
if (aiHealth < 30 && isMatched) {
return Math.random() < 0.4; // 40% chance when critically low health
}
return false;
}
/**
* AI state management
*/
interface AIState {
nextAction: number;
targetPosition: Position;
lastActionType: string;
consecutiveAttacks: number;
actionCooldown: number;
aggressionLevel: number;
selectedTechnique?: KoreanTechnique;
targetVitalPoint?: string;
recentTechniques: string[]; // Track last 5 techniques for variation
}
/**
* Technique rotation queue for enforcing variety
*
* Tracks technique usage to prevent repetitive patterns:
* - Last 5 techniques used (for immediate variation)
* - All techniques used in current match (for full arsenal tracking)
* - Usage frequency per technique (for 40% threshold enforcement)
* - Total attacks counter (for percentage calculation)
*
* @korean 기술 순환 큐 (다양성 강화)
*/
interface TechniqueRotationQueue {
used: string[]; // Last 5 technique IDs (FIFO)
allUsed: Set<string>; // All techniques used this match
frequency: Map<string, number>; // Usage count per technique ID
totalAttacks: number; // Total attack count for percentage calculation
}
/**
* Technique cooldown tracking
*
* Maps technique ID to timestamp of last use
* Used for cooldown-aware technique selection
*
* @korean 기술 재사용 대기시간 추적
*/
type TechniqueCooldownMap = Map<string, 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 scale?: number;
readonly worldWidthMeters: number; // Arena width in meters for physics calculations
readonly worldDepthMeters: number; // Arena depth in meters for physics calculations
};
readonly onExecuteAction: (
action: string,
targetPosition?: Position,
selectedTechnique?: KoreanTechnique,
targetVitalPoint?: string,
) => void;
readonly onStanceChange?: (stance: TrigramStance) => void;
readonly onLateralityChange?: () => void;
readonly playerLaterality?: "left" | "right";
readonly opponentLaterality?: "left" | "right";
}
/**
* 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,
selectedTechnique?: KoreanTechnique,
targetVitalPoint?: string,
) => void;
readonly currentDifficultyParams: DifficultyParameters;
readonly updateDifficultyTarget: (newParams: DifficultyParameters) => void;
}
/**
* Custom hook for AI combat behavior
*/
export function useAICombat(config: UseAICombatConfig): UseAICombatReturn {
const {
player,
opponent,
personality,
adaptiveDifficulty,
isPaused,
roundStarted,
roundEnded,
arenaBounds,
onExecuteAction,
onStanceChange,
onLateralityChange,
playerLaterality,
opponentLaterality,
} = 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%
if (Math.abs(newSkillLevel - lastSkillLevelRef.current) > 0.01) {
lastSkillLevelRef.current = newSkillLevel;
decisionTree.setDifficultyLevel(newSkillLevel);
}
}, [adaptiveDifficulty, decisionTree]);
// Difficulty parameters with smooth interpolation
// Using useState with lazy initializer instead of useMemo since it only runs once
const [currentParams, setCurrentParams] = useState<DifficultyParameters>(() =>
adaptiveDifficulty.getDifficultyParameters(),
);
const [targetParams, setTargetParams] = useState<DifficultyParameters>(() =>
adaptiveDifficulty.getDifficultyParameters(),
);
const startParamsRef = useRef<DifficultyParameters>(currentParams);
const transitionStartTimeRef = useRef<number>(0);
const transitionDurationMs = 10000; // 10 seconds for smooth transition
// AI state - use useState lazy initializer for Date.now()
const [aiState, setAiState] = useState<AIState>(() => {
const now = Date.now();
return {
nextAction: now,
targetPosition: player.position,
lastActionType: "idle",
consecutiveAttacks: 0,
actionCooldown: 500,
aggressionLevel: adjustedPersonality.aggressionLevel,
selectedTechnique: undefined,
targetVitalPoint: undefined,
recentTechniques: [],
};
});
// Performance tracking - use useState lazy initializer for refs that need Date.now()
const lastDecisionTimeRef = useRef(0);
const [initialMatchTime] = useState(() => Date.now());
const matchStartTimeRef = useRef(initialMatchTime);
const previousDamageRef = useRef(0);
const [initialActionTime] = useState(() => Date.now());
const nextActionRef = useRef(initialActionTime);
const lastWarningTimeRef = useRef(0);
const lastLateralitySwitchRef = useRef(0); // Track last laterality switch for cooldown
// Technique rotation queue and cooldown tracking (Issue #expand-technique-selection-diversity)
// Enforce technique variety: all 4 techniques used, no technique >40% usage
const techniqueRotationQueueRef = useRef<TechniqueRotationQueue>({
used: [],
allUsed: new Set(),
frequency: new Map(),
totalAttacks: 0,
});
const techniqueCooldownMapRef = useRef<TechniqueCooldownMap>(new Map());
// Get all technique IDs for current archetype (for reset detection)
const archetypeTechniqueIds = useMemo(() => {
const allTechs = getAllArchetypeTechniques(player.archetype);
return new Set(allTechs.map((t) => t.id));
}, [player.archetype]);
// Stance fatigue tracking (Issue #dynamic-ai-stance-rotation Phase 4)
// Tracks how long AI has been in current stance to encourage dynamic switching
// Use useState lazy initializer for Date.now() to avoid impure function call during render
const [initialStanceFatigue] = useState(() => ({
currentStance: player.currentStance,
lastSwitchTime: Date.now(),
}));
const stanceFatigueRef = useRef(initialStanceFatigue);
// Initialize previousDamageRef when round starts (issue #2529728007)
// player.currentStance and player.totalDamageReceived are intentionally excluded -
// this effect only initializes refs when a new round starts, not on every state change
useEffect(() => {
if (roundStarted) {
matchStartTimeRef.current = Date.now();
previousDamageRef.current = player.totalDamageReceived;
decisionTree.reset();
comboSystem.resetCombo();
// Reset stance fatigue tracking on round start
stanceFatigueRef.current = {
currentStance: player.currentStance,
lastSwitchTime: Date.now(),
};
// Reset technique rotation queue on round start (Issue #expand-technique-selection-diversity)
techniqueRotationQueueRef.current = {
used: [],
allUsed: new Set(),
frequency: new Map(),
totalAttacks: 0,
};
// Reset technique cooldown tracking on round start
techniqueCooldownMapRef.current.clear();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [roundStarted, decisionTree, comboSystem]);
// Monitor stance changes and update fatigue tracking (Issue #dynamic-ai-stance-rotation Phase 4)
// Detects when AI changes stance and resets fatigue timer
useEffect(() => {
if (!roundStarted || roundEnded || isPaused) {
return;
}
// Detect stance change and reset fatigue timer
Iif (player.currentStance !== stanceFatigueRef.current.currentStance) {
stanceFatigueRef.current = {
currentStance: player.currentStance,
lastSwitchTime: Date.now(),
};
}
}, [player.currentStance, roundStarted, roundEnded, isPaused]);
// Smooth interpolation of difficulty parameters using requestAnimationFrame
useEffect(() => {
if (isPaused || !roundStarted || roundEnded) {
return;
}
let animationFrameId: number;
let isComplete = false;
const animate = () => {
Iif (isComplete) return;
const now = Date.now();
const elapsed = now - transitionStartTimeRef.current;
const progress = Math.min(1.0, elapsed / transitionDurationMs);
Iif (progress < 1.0) {
// Still interpolating from captured start params to target
const interpolated = interpolateDifficultyParameters(
startParamsRef.current,
targetParams,
progress,
);
setCurrentParams(interpolated);
animationFrameId = requestAnimationFrame(animate);
} else {
// Transition complete - snap to target and stop
setCurrentParams(targetParams);
isComplete = true;
}
};
animationFrameId = requestAnimationFrame(animate);
return () => {
Eif (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
};
}, [isPaused, roundStarted, roundEnded, targetParams, transitionDurationMs]);
// Pass current difficulty parameters to DecisionTree
useEffect(() => {
decisionTree.setDifficultyParameters(currentParams);
}, [decisionTree, currentParams]);
/**
* Execute AI action callback
*
* Passes technique and vital point directly to avoid React state async issues
*
* @korean AI 행동 실행 콜백
*/
const executeAIAction = useCallback(
(
action: string,
targetPosition?: Position,
selectedTechnique?: KoreanTechnique,
targetVitalPoint?: string,
) => {
onExecuteAction(action, targetPosition, selectedTechnique, targetVitalPoint);
},
[onExecuteAction],
);
/**
* Update difficulty target parameters
* Triggers smooth interpolation to new difficulty level
*
* @korean 난이도 목표 매개변수 업데이트
*/
const updateDifficultyTarget = useCallback(
(newParams: DifficultyParameters) => {
// Capture current params as start point for smooth transition
startParamsRef.current = currentParams;
transitionStartTimeRef.current = Date.now();
setTargetParams(newParams);
},
[currentParams],
);
/**
* Build combat context for decision-making.
*
* **Physics-first**: Positions are now in METERS, so distance is already in meters.
* No scale conversion needed - direct physics-based calculations.
*
* @korean 전투 컨텍스트 구축
*/
const buildCombatContext = useCallback((): CombatContext => {
const dx = player.position.x - opponent.position.x;
const dy = player.position.y - opponent.position.y;
// Physics-first: positions are in meters, so distance is directly in meters
const distanceInMeters = 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;
// Convert opponent balance number to balance state for kill mode detection
// Uses getBalanceState() from player3DHelpers.ts to ensure consistency
// Thresholds: >=80 READY, >=50 SHAKEN, >=20 VULNERABLE, <20 HELPLESS
const opponentBalance = getBalanceState(opponent.balance);
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: distanceInMeters, // Physics-first: distance in meters
timeInMatch: Date.now() - matchStartTimeRef.current,
isOpponentAttacking: opponent.combatState === "attacking",
recentDamageTaken,
opponentBalance, // Added for kill mode detection
opponentStamina: opponent.stamina, // Added for vulnerability exploitation (Issue #enhance-intelligence-operative-ai)
opponentMaxStamina: opponent.maxStamina, // Added for vulnerability exploitation
opponentKi: opponent.ki, // Added for vulnerability exploitation (Issue #enhance-intelligence-operative-ai)
opponentMaxKi: opponent.maxKi, // Added for vulnerability exploitation
stanceFatigue: {
// Compute time in stance on-demand instead of polling with setInterval
timeInStance: Date.now() - stanceFatigueRef.current.lastSwitchTime,
},
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 with technique and vital point selection
let actionType = "idle";
let newTargetPosition = aiState.targetPosition;
let newConsecutiveAttacks = aiState.consecutiveAttacks;
let selectedTechnique: KoreanTechnique | undefined;
let targetVitalPoint: string | undefined;
switch (decision.action) {
case AIActionType.ATTACK:
{
const result = selectTechniqueForAction(
false,
context,
player,
adaptiveDifficulty,
techniqueRotationQueueRef.current,
techniqueCooldownMapRef.current,
);
selectedTechnique = result.technique;
targetVitalPoint = result.vitalPoint;
actionType = result.actionType;
// Update rotation queue and cooldown tracking if technique selected
// Note: Cross-stance damage modifier already applied in selectTechniqueForAction()
Eif (selectedTechnique) {
updateTechniqueRotation(
selectedTechnique.id,
techniqueRotationQueueRef.current,
archetypeTechniqueIds,
);
// Record cooldown start time
techniqueCooldownMapRef.current.set(
selectedTechnique.id,
Date.now(),
);
// Check for signature combo continuation (Issue #expand-technique-selection-diversity)
const nextComboTechnique = getNextComboTechnique(
selectedTechnique.id,
player.archetype,
);
// If this technique starts a combo, store next technique for consideration
Iif (nextComboTechnique) {
// Store combo hint for next decision (combo system can use this)
// The decision tree will naturally consider this in the next cycle
comboSystem.startCombo(player, opponent, adjustedPersonality);
}
}
Eif (actionType === "attack") {
newConsecutiveAttacks++;
}
}
break;
case AIActionType.TECHNIQUE:
{
const result = selectTechniqueForAction(
true,
context,
player,
adaptiveDifficulty,
techniqueRotationQueueRef.current,
techniqueCooldownMapRef.current,
);
selectedTechnique = result.technique;
targetVitalPoint = result.vitalPoint;
actionType = result.actionType;
// Update rotation queue and cooldown tracking if technique selected
// Note: Cross-stance damage modifier already applied in selectTechniqueForAction()
Iif (selectedTechnique) {
updateTechniqueRotation(
selectedTechnique.id,
techniqueRotationQueueRef.current,
archetypeTechniqueIds,
);
// Record cooldown start time
techniqueCooldownMapRef.current.set(
selectedTechnique.id,
Date.now(),
);
// Check for signature combo continuation (Issue #expand-technique-selection-diversity)
const nextComboTechnique = getNextComboTechnique(
selectedTechnique.id,
player.archetype,
);
// If this technique starts a combo, store next technique for consideration
if (nextComboTechnique) {
// Store combo hint for next decision (combo system can use this)
comboSystem.startCombo(player, opponent, adjustedPersonality);
}
}
Iif (actionType === "attack" || 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;
}
// Check for strategic laterality switch (Phase 8)
// AI decides whether to switch stance side based on personality and tactical situation
Iif (onLateralityChange && playerLaterality && opponentLaterality) {
const shouldSwitch = shouldAISwitchLaterality(
opponentLaterality, // Laterality for player index 1 (AI-controlled in this hook)
playerLaterality, // Laterality for player index 0 (human-controlled in this hook)
adjustedPersonality,
player.health,
lastLateralitySwitchRef.current,
now,
);
if (shouldSwitch) {
onLateralityChange();
lastLateralitySwitchRef.current = now;
}
}
// Calculate next action cooldown - expert fighters attack rapidly
// Attack/technique: 200-350ms for fast-paced combat (was 600-800ms)
// Other actions: 150-300ms for quick repositioning (was 400-600ms)
const actionCooldown =
actionType === "attack" || actionType === "technique"
? 200 + Math.random() * 150 // 200-350ms for attacks
: 150 + Math.random() * 150; // 150-300ms for movement/defense
// Update next action time using ref (prevents stale closure)
nextActionRef.current = now + actionCooldown;
// Use functional state update to avoid stale closure issues with recentTechniques
setAiState((prevState) => {
// Update recent techniques tracking with functional update
let updatedRecentTechniques = [...prevState.recentTechniques];
if (selectedTechnique) {
updatedRecentTechniques.push(selectedTechnique.id);
// Keep only last 5 techniques
Iif (updatedRecentTechniques.length > 5) {
updatedRecentTechniques = updatedRecentTechniques.slice(-5);
}
}
return {
nextAction: nextActionRef.current,
targetPosition: newTargetPosition,
lastActionType: actionType,
consecutiveAttacks: newConsecutiveAttacks,
actionCooldown,
aggressionLevel: adjustedPersonality.aggressionLevel,
selectedTechnique,
targetVitalPoint,
recentTechniques: updatedRecentTechniques,
};
});
// Execute action - pass technique and vital point directly to avoid async state issues
executeAIAction(actionType, newTargetPosition, selectedTechnique, targetVitalPoint);
}, 50); // 50ms loop for responsive AI
return () => clearInterval(aiInterval);
}, [
isPaused,
roundStarted,
roundEnded,
buildCombatContext,
decisionTree,
adjustedPersonality,
comboSystem,
executeAIAction,
onStanceChange,
onLateralityChange,
player,
opponent,
aiState,
playerLaterality,
opponentLaterality,
adaptiveDifficulty,
archetypeTechniqueIds,
]);
return {
aiState,
comboSystem,
decisionTree,
adjustedPersonality,
executeAIAction,
currentDifficultyParams: currentParams,
updateDifficultyTarget,
};
}
|