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 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 | 1x 60x 60x 60x 60x 30x 30x 60x 60x 30x 30x 30x 30x 30x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 30x 30x 60x 30x 60x 30x 30x 30x 30x 30x 60x 30x 30x 30x 30x 30x 60x 30x 30x 30x 60x 30x 30x 30x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 30x 60x 60x 60x 30x 30x 30x 30x 30x 30x 60x 30x 30x 30x 30x 60x 60x 30x 60x 60x 60x 60x 60x 60x 30x 30x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 30x 30x 30x 30x 30x 30x 30x 60x 60x 30x 30x 30x 29x 30x 30x 30x 30x 60x 30x 60x 60x 60x 60x 60x 60x 60x 60x 60x 30x 30x 30x 60x 60x 60x 30x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 58x 60x 60x 60x 30x 60x 30x 30x 60x 60x 60x 60x 30x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x 60x | /**
* CombatScreen3D - Three.js-based combat screen
*
* Maintains all existing combat logic and state management
* Uses Html overlays for UI and 3D meshes for game objects
*/
import { Html } from "@react-three/drei";
import { Canvas } from "@react-three/fiber";
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import * as THREE from "three";
import { useAudio } from "../../audio/AudioProvider";
import { useKeyboardControls } from "../../hooks/useKeyboardControls";
import { usePlayerAnimation } from "../../hooks/usePlayerAnimation";
import { useRoundTransition } from "../../hooks/useRoundTransition";
import { useWebGLContextLossHandler } from "../../hooks/useWebGLContextLossHandler";
import { HitEffect, PlayerState } from "../../systems";
import { CombatSystem } from "../../systems/CombatSystem";
import {
AdaptiveDifficulty,
getPersonalityByArchetype,
} from "../../systems/ai";
import {
AnimationEvents,
getAnimationForTechnique,
} from "../../systems/animation";
import { HitEffectType } from "../../systems/effects";
import { TRIGRAM_STANCES_ORDER } from "../../systems/trigram/types";
import {
GameMode,
PlayerArchetype,
Position,
TrigramStance,
} from "../../types";
import {
FONT_FAMILY,
KOREAN_COLORS,
ROUND_ANNOUNCEMENT_TIMINGS,
} from "../../types/constants";
import { hexToRgbaString } from "../../utils/colorUtils";
import { usePlayerMovement } from "../../utils/inputSystem";
import { PerformanceOverlay3D } from "../../utils/performance";
import { createPlayerFromArchetype } from "../../utils/playerUtils";
import { VolumeControl } from "../ui/VolumeControl";
import { InputBufferDisplay } from "./components/InputBufferDisplay";
import { KeyboardHints } from "./components/KeyboardHints";
import { MatchCountdown } from "./components/MatchCountdown";
import { RoundAnnouncement } from "./components/RoundAnnouncement";
import { RoundStartAnnouncement } from "./components/RoundStartAnnouncement";
import { StanceChangeIndicator } from "./components/StanceChangeIndicator";
// TODO: Create HTML versions of these UI components for Three.js
// import { CombatControls } from "./components/CombatControls";
// import { CombatFooter } from "./components/CombatFooter";
// import { CombatHUD } from "./components/CombatHUD";
// import { CombatStatsPanel } from "./components/CombatStatsPanel";
import { useActionFeedback } from "../../hooks/useActionFeedback";
import { useCombatTimer } from "../../hooks/useCombatTimer";
import { useTechniqueSelection } from "../../hooks/useTechniqueSelection";
import { GestureEvent } from "../../hooks/useTouchControls";
import { Technique } from "../../types";
import {
animationStateToPlayerAnimation,
convertPlayerStateToProps,
getBalanceState,
} from "../../utils/player3DHelpers";
import { ButtonEventType } from "../mobile/ActionButtons";
import { Direction, DPadEventType } from "../mobile/VirtualDPad";
import { SkeletalPlayer3D } from "../three/SkeletalPlayer3D";
import { VitalPointMarkers3D, VitalPointOverlayControls } from "./components";
import { ActionFeedback, TechniqueName } from "./components/ActionFeedback";
import { BodyPartHealthDisplay } from "./components/BodyPartHealthDisplay";
import CombatArena3D from "./components/CombatArena3D";
import { CombatControlsPanel } from "./components/CombatControlsPanel";
import { CombatTimer } from "./components/CombatTimer";
import { ComboCounter } from "./components/ComboCounter";
import { DamageNumbers } from "./components/DamageNumbers";
import { DifficultyIndicator } from "./components/DifficultyIndicator";
import { FPSMonitor } from "./components/FPSMonitor";
import HitEffects3D from "./components/HitEffects3D";
import { MobileControlsWrapper } from "./components/MobileControlsWrapper";
import { PauseMenu } from "./components/PauseMenu";
import { PlayerHUD } from "./components/PlayerHUD";
import { PlayerStateOverlay } from "./components/PlayerStateOverlay";
import { TechniqueBar } from "./components/TechniqueBar";
import {
AnimationUpdater,
ANNOUNCEMENT_FADE_OUT_DELAY,
calculateAccuracy,
STANCE_INDEX_MAP,
} from "./helpers";
import { useAICombat } from "./hooks/useAICombat";
import { useCombatActions } from "./hooks/useCombatActions";
import { useCombatAudio } from "./hooks/useCombatAudio";
import { useCombatLayout } from "./hooks/useCombatLayout";
import { useCombatState } from "./hooks/useCombatState";
/**
* Props for the CombatScreen3D component.
* Provides all state and callbacks required for the 3D combat screen.
*/
export interface CombatScreen3DProps {
/**
* Array of player states (expects exactly 2 players).
* Each PlayerState contains all combat and status information for a player.
*/
readonly players: readonly PlayerState[];
/**
* Callback to update a player's state by index.
* @param playerIndex - Index of the player to update (0 or 1).
* @param updates - Partial PlayerState with updated fields.
*/
readonly onPlayerUpdate: (
playerIndex: number,
updates: Partial<PlayerState>
) => void;
/**
* Current round number (1-based).
*/
readonly currentRound: number;
/**
* Remaining time in seconds for the current round.
*/
readonly timeRemaining: number;
/**
* Whether combat is currently paused.
*/
readonly isPaused: boolean;
/**
* Callback when the user exits to the menu.
*/
readonly onReturnToMenu: () => void;
/**
* Callback when the match ends, with the winner's index (0 or 1).
* @param winner - Index of the winning player.
*/
readonly onGameEnd: (winner: number) => void;
/**
* Optional game mode (affects rules/behavior).
*/
readonly gameMode?: GameMode;
/**
* Canvas width in pixels. Defaults to 1200.
*/
readonly width?: number;
/**
* Canvas height in pixels. Defaults to 800.
*/
readonly height?: number;
}
/**
* CombatScreen3D Component
* Three.js-based combat screen with 3D characters and effects
*/
export const CombatScreen3D: React.FC<CombatScreen3DProps> = ({
players,
onPlayerUpdate,
currentRound,
timeRemaining,
isPaused,
onReturnToMenu,
onGameEnd,
width = 1200,
height = 800,
}) => {
// Track when content is ready to render (prevents flash of empty content)
const [contentReady, setContentReady] = useState(false);
// Track context loss count for debugging
const contextLossCountRef = useRef(0);
// Handle WebGL context loss and restoration
useWebGLContextLossHandler({
onContextLost: () => {
console.warn("⚠️ WebGL context lost in CombatScreen");
contextLossCountRef.current += 1;
setContentReady(false);
},
onContextRestored: () => {
// Context restored - re-enable content after short delay
setTimeout(() => setContentReady(true), 100);
},
autoRestore: true,
});
// Ensure content renders after component is mounted and stable
useEffect(() => {
const timer = setTimeout(() => setContentReady(true), 50);
return () => clearTimeout(timer);
}, []);
// Audio context for button interactions
const audio = useAudio();
// Performance marks - only in dev mode and memoized
useEffect(() => {
Eif (import.meta.env.DEV) {
performance.mark("combat-3d-render-start");
return () => {
performance.mark("combat-3d-render-end");
performance.measure(
"combat-3d-render",
"combat-3d-render-start",
"combat-3d-render-end"
);
};
}
}, []);
// Layout calculations
const { arenaBounds, isMobile } = useCombatLayout(width, height);
// Combat state management
const { state: combatState, actions: combatActions } = useCombatState();
// ═══════════════════════════════════════════════════════════════════════════
// Vital Point Overlay Controls State
// ═══════════════════════════════════════════════════════════════════════════
// Vital point overlay state (for both players)
const [overlayVisible, setOverlayVisible] = useState(false);
const [severityFilters, setSeverityFilters] = useState<
import("../../types/common").VitalPointSeverity[]
>([]);
const [regionFilter, setRegionFilter] =
useState<import("./components").BodyRegionFilter>("all");
const [searchQuery, setSearchQuery] = useState("");
const [showLabels, setShowLabels] = useState(true);
const [animated, setAnimated] = useState(true);
const [scale, setScale] = useState(1.2); // Larger scale for better visibility in combat
// Keyboard shortcut for toggling overlay (V key)
useEffect(() => {
const handleKeyPress = (e: KeyboardEvent) => {
if (e.key === "v" || e.key === "V") {
setOverlayVisible((prev) => !prev);
audio.playSFX("menu_select");
}
};
window.addEventListener("keydown", handleKeyPress);
return () => window.removeEventListener("keydown", handleKeyPress);
}, [audio]);
// Action feedback system for damage numbers, combo counter, and technique names
const { state: feedbackState, actions: feedbackActions } = useActionFeedback({
damageNumberDuration: 1500,
actionFeedbackDuration: 1200,
techniqueDuration: 2000,
comboResetTime: 2000,
});
// Combat audio
const combatAudio = useCombatAudio();
// Match score tracking - use ref for internal updates, state for rendering
const [matchScore, setMatchScore] = useState({ player1: 0, player2: 0 });
const matchScoreRef = useRef(matchScore);
// Helper to update match score without triggering setState in effects
const updateMatchScore = useCallback((winner: 0 | 1) => {
const newScore = {
player1:
winner === 0
? matchScoreRef.current.player1 + 1
: matchScoreRef.current.player1,
player2:
winner === 1
? matchScoreRef.current.player2 + 1
: matchScoreRef.current.player2,
};
matchScoreRef.current = newScore;
// Use setTimeout to defer the setState call outside the effect
setTimeout(() => setMatchScore(newScore), 0);
}, []);
// Internal round tracking (since parent may always pass currentRound=1)
const [internalRound, setInternalRound] = useState(currentRound);
// Match countdown state - DISABLED: skip countdown and start combat immediately
// Using state for hasShownMatchCountdown to avoid ref access during render
const [hasShownMatchCountdown, setHasShownMatchCountdown] = useState(true); // Already shown (skipped)
const [showMatchCountdown, setShowMatchCountdown] = useState(false); // Don't show
const [showRoundStart, setShowRoundStart] = useState(false);
const [matchCountdownComplete, setMatchCountdownComplete] = useState(true); // Already complete (skipped)
// Player 1 position (controlled by player movement)
// Player 1 starts closer to center (35%) for better combat engagement
const [player1Position, setPlayer1Position] = useState<Position>({
x: arenaBounds.x + arenaBounds.width * 0.35,
y: arenaBounds.y + arenaBounds.height * 0.5,
});
// Pause menu state - local state for pause menu visibility
// Local state for pause menu UI visibility
// Note: isPaused (prop) controls game pause from parent, showPauseMenu (state) controls menu UI
// Both need to be checked because:
// - isPaused: External pause state (e.g., from parent component or global game state)
// - showPauseMenu: Local UI state for pause menu overlay
// They can be out of sync intentionally (e.g., parent pauses game but menu not shown)
const [showPauseMenu, setShowPauseMenu] = useState(false);
// Pause menu handlers
const handlePause = useCallback(() => {
setShowPauseMenu(true);
audio.playSFX("menu_select");
}, [audio]);
const handleResume = useCallback(() => {
setShowPauseMenu(false);
audio.playSFX("menu_select");
}, [audio]);
const handleRestart = useCallback(() => {
// Note: React 19 automatically batches all these state updates into a single render
// This ensures atomic state transitions without race conditions
// Reset to first round
setInternalRound(1);
setMatchScore({ player1: 0, player2: 0 });
matchScoreRef.current = { player1: 0, player2: 0 };
// Reset combat state
combatActions.setRoundEnded(false);
combatActions.setRoundStarted(false);
combatActions.setRoundDisplayStatus(null);
// Reset player health, resources, and visual state
// Includes consciousness, pain, balance to clear any blur/vignette effects
onPlayerUpdate(0, {
health: 100,
stamina: 100,
ki: 100,
consciousness: 100,
pain: 0,
balance: 100,
});
onPlayerUpdate(1, {
health: 100,
stamina: 100,
ki: 100,
consciousness: 100,
pain: 0,
balance: 100,
});
// Reset player positions to starting positions for rematch
setPlayer1Position({
x: arenaBounds.x + arenaBounds.width * 0.35,
y: arenaBounds.y + arenaBounds.height * 0.5,
});
onPlayerUpdate(1, {
position: {
x: arenaBounds.x + arenaBounds.width * 0.65,
y: arenaBounds.y + arenaBounds.height * 0.5,
},
});
// Close pause menu and start first round
// The timer will reset automatically via the initialTime prop when round starts
setShowPauseMenu(false);
setShowRoundStart(true);
audio.playSFX("menu_select");
}, [audio, combatActions, onPlayerUpdate, arenaBounds, setPlayer1Position]);
// Round transition complete handler - checks for match end or starts next round
const handleRoundTransitionComplete = useCallback(() => {
if (import.meta.env.DEV) {
console.log("[DEV] Round transition complete, checking match status");
}
// Check if match is over (best of 3 - first to 2 wins)
const currentScore = matchScoreRef.current;
if (currentScore.player1 >= 2 || currentScore.player2 >= 2) {
// Match is over - call onGameEnd instead of starting next round
const matchWinner = currentScore.player1 >= 2 ? 0 : 1;
if (import.meta.env.DEV) {
console.log("[DEV] Match over, winner:", matchWinner);
}
onGameEnd(matchWinner);
return; // Don't start next round
}
// Reset all combat state for next round (combos, hit effects, messages cleared)
combatActions.resetRoundState();
// Increment internal round counter for next round
// Use the updater function to get the new value and trigger announcement
setInternalRound((prev) => {
const nextRound = prev + 1;
if (import.meta.env.DEV) {
console.log("[DEV] Incrementing round from", prev, "to", nextRound);
}
// Wait for transition duration plus fade-out to complete before showing next round announcement
setTimeout(() => {
if (import.meta.env.DEV) {
console.log(
"[DEV] Showing round start announcement for round",
nextRound
);
}
setShowRoundStart(true);
}, ANNOUNCEMENT_FADE_OUT_DELAY);
return nextRound;
});
// Reset player health, resources, and visual state for next round
// Includes consciousness, pain, balance to clear any blur/vignette effects
onPlayerUpdate(0, {
health: 100,
stamina: 100,
ki: 100,
consciousness: 100,
pain: 0,
balance: 100,
});
onPlayerUpdate(1, {
health: 100,
stamina: 100,
ki: 100,
consciousness: 100,
pain: 0,
balance: 100,
});
// Reset player positions to starting positions for new round
setPlayer1Position({
x: arenaBounds.x + arenaBounds.width * 0.35,
y: arenaBounds.y + arenaBounds.height * 0.5,
});
// Player 2 position is reset via onPlayerUpdate
onPlayerUpdate(1, {
position: {
x: arenaBounds.x + arenaBounds.width * 0.65,
y: arenaBounds.y + arenaBounds.height * 0.5,
},
});
}, [
combatActions,
onGameEnd,
onPlayerUpdate,
arenaBounds,
// Note: setPlayer1Position is a stable React setState function and won't cause unnecessary re-renders
setPlayer1Position,
]);
// Round transition management
const {
showAnnouncement,
roundWinner,
currentRoundNumber: transitionRoundNumber,
skipCountdown,
startTransition,
} = useRoundTransition(
{
announcementDuration: ROUND_ANNOUNCEMENT_TIMINGS.ANNOUNCEMENT_DURATION,
countdownDuration: ROUND_ANNOUNCEMENT_TIMINGS.COUNTDOWN_DURATION,
transitionDuration: ROUND_ANNOUNCEMENT_TIMINGS.TRANSITION_DURATION,
},
handleRoundTransitionComplete
);
// Player 2 position - derived from players prop (AI-controlled)
// Default position is used when players prop is empty or player2 has no position
// Player 2 (AI) starts at right side of arena (65%), closer to center for faster engagement
const player2Position = useMemo<Position>(() => {
Eif (players.length >= 2 && players[1].position) {
return players[1].position;
}
return {
x: arenaBounds.x + arenaBounds.width * 0.65,
y: arenaBounds.y + arenaBounds.height * 0.5,
};
}, [players, arenaBounds]);
// Combined positions for backward compatibility with existing code
const playerPositions = useMemo<Position[]>(() => {
return [player1Position, player2Position];
}, [player1Position, player2Position]);
// Convert 2D positions to 3D world coordinates
const player1Position3D: [number, number, number] = useMemo(() => {
const relX = (playerPositions[0].x - arenaBounds.x) / arenaBounds.width;
const relZ = (playerPositions[0].y - arenaBounds.y) / arenaBounds.height;
const x = relX * 16 - 8; // Map 0-1 to -8 to 8
const z = relZ * 8 - 4; // Map 0-1 to -4 to 4
return [x, 0, z];
}, [playerPositions, arenaBounds]);
const player2Position3D: [number, number, number] = useMemo(() => {
const relX = (playerPositions[1].x - arenaBounds.x) / arenaBounds.width;
const relZ = (playerPositions[1].y - arenaBounds.y) / arenaBounds.height;
const x = relX * 16 - 8; // Map 0-1 to -8 to 8
const z = relZ * 8 - 4; // Map 0-1 to -4 to 4
return [x, 0, z];
}, [playerPositions, arenaBounds]);
// Calculate dynamic rotations so players always face each other
// atan2(dx, dz) gives the Y-axis rotation needed to face direction (dx, dz)
// This is the standard formula for rotating around Y to point at a target
const player1Rotation = useMemo(() => {
const dx = player2Position3D[0] - player1Position3D[0];
const dz = player2Position3D[2] - player1Position3D[2];
return Math.atan2(dx, dz);
}, [player1Position3D, player2Position3D]);
const player2Rotation = useMemo(() => {
const dx = player1Position3D[0] - player2Position3D[0];
const dz = player1Position3D[2] - player2Position3D[2];
return Math.atan2(dx, dz);
}, [player1Position3D, player2Position3D]);
// Combat system
const combatSystem = useMemo(() => new CombatSystem(), []);
// Track current attack animation for each player
// Used to determine which skeletal animation to play during attacks
// 각 플레이어의 현재 공격 애니메이션 추적
const [player1AttackAnimation, setPlayer1AttackAnimation] = useState<
string | undefined
>(undefined);
const [player2AttackAnimation, setPlayer2AttackAnimation] = useState<
string | undefined
>(undefined);
// Player movement
const { isMoving: player1IsMoving } = usePlayerMovement({
enabled:
!isPaused &&
combatState.roundStarted &&
!combatState.roundEnded &&
matchCountdownComplete &&
!showRoundStart,
bounds: arenaBounds,
onPositionChange: (newPosition: Position) => {
setPlayer1Position(newPosition);
onPlayerUpdate(0, { position: newPosition });
},
initialPosition: player1Position,
moveSpeed: 300,
});
// Use ref to store attack handler to avoid circular dependencies
const handleAttackRef = useRef<(() => void) | null>(null);
// Refs to clear attack animations after completion
const clearPlayer1AttackAnimation = useRef<() => void>(() => {
setPlayer1AttackAnimation(undefined);
});
const clearPlayer2AttackAnimation = useRef<() => void>(() => {
setPlayer2AttackAnimation(undefined);
});
// Player animation state machines - manages animation transitions at 60fps
// Memoize events object to maintain stability (required by usePlayerAnimation)
const player1AnimationEvents = useMemo<AnimationEvents>(
() => ({
onFrame: (frame, state) => {
// Execute attack at midpoint of animation (frame 6 of 12)
if (state === "attack" && frame === 6) {
// Attack connects at the midpoint - execute combat logic here
handleAttackRef.current?.();
}
},
onAnimationComplete: (state) => {
// Handle animation completion
if (state === "attack" || state === "defend") {
combatActions.setExecutingTechnique(false);
// Clear attack animation when attack completes
// 공격 완료 시 공격 애니메이션 초기화
if (state === "attack") {
clearPlayer1AttackAnimation.current();
}
} else if (state === "stance_change") {
// Stance change animation completed
audio.playSFX("menu_select");
}
},
}),
[combatActions, audio]
);
const player1Animation = usePlayerAnimation({
events: player1AnimationEvents,
});
const player2Animation = usePlayerAnimation({
events: {
onFrame: (frame, state) => {
if (state === "attack" && frame === 6) {
// AI attack hit detection
}
},
onAnimationComplete: (state) => {
// Clear AI attack animation when attack completes
// AI 공격 완료 시 공격 애니메이션 초기화
if (state === "attack") {
clearPlayer2AttackAnimation.current();
}
},
},
});
// Sync movement with player 1 animation (avoid circular dependency)
const prevPlayer1IsMovingRef = useRef<boolean>(player1IsMoving);
useEffect(() => {
// Only trigger transition when isMoving changes
Iif (prevPlayer1IsMovingRef.current !== player1IsMoving) {
if (player1IsMoving) {
player1Animation.transitionTo("walk");
} else if (player1Animation.currentState === "walk") {
player1Animation.transitionTo("idle");
}
prevPlayer1IsMovingRef.current = player1IsMoving;
}
}, [player1IsMoving, player1Animation]);
// Movement detection threshold for AI animation sync (in pixels)
// Lower values = more sensitive to small movements, higher values = smoother transitions
const MOVEMENT_DETECTION_THRESHOLD = 0.5;
// Sync movement with player 2 animation (AI movement detection)
const prevPlayer2PositionRef = useRef(player2Position);
useEffect(() => {
const currentPos = playerPositions[1];
const prevPos = prevPlayer2PositionRef.current;
// Detect if Player2 (AI) is moving by comparing positions
const isMoving =
Math.abs(currentPos.x - prevPos.x) > MOVEMENT_DETECTION_THRESHOLD ||
Math.abs(currentPos.y - prevPos.y) > MOVEMENT_DETECTION_THRESHOLD;
Iif (isMoving) {
// AI is moving - transition to walk animation
if (
player2Animation.currentState !== "walk" &&
player2Animation.currentState !== "attack"
) {
player2Animation.transitionTo("walk");
}
} else {
// AI stopped - transition back to idle if currently walking
Iif (player2Animation.currentState === "walk") {
player2Animation.transitionTo("idle");
}
}
prevPlayer2PositionRef.current = currentPos;
}, [playerPositions, player2Animation]);
// Valid players with complete state
const validPlayers = useMemo((): [PlayerState, PlayerState] => {
Iif (players.length === 0) {
const player1 = createPlayerFromArchetype(PlayerArchetype.MUSA, 0);
const player2 = createPlayerFromArchetype(PlayerArchetype.AMSALJA, 1);
return [
{ ...player1, position: playerPositions[0] },
{ ...player2, position: playerPositions[1] },
];
}
const player1 = players[0];
const player2 =
players[1] ?? createPlayerFromArchetype(PlayerArchetype.AMSALJA, 1);
return [
{ ...player1, position: playerPositions[0] },
{ ...player2, position: playerPositions[1] },
];
}, [players, playerPositions]);
// Use ref to access latest player health without causing re-renders
const validPlayersRef = useRef<[PlayerState, PlayerState]>(validPlayers);
useEffect(() => {
validPlayersRef.current = validPlayers;
}, [validPlayers]);
// Use refs for stable access to startTransition and internalRound
const startTransitionRef = useRef(startTransition);
const internalRoundRef = useRef(internalRound);
useEffect(() => {
startTransitionRef.current = startTransition;
internalRoundRef.current = internalRound;
}, [startTransition, internalRound]);
// Combat messages
const addCombatMessage = useCallback(
(korean: string, english: string) => {
const message = `${korean} | ${english}`;
combatActions.addCombatMessage(message);
},
[combatActions]
);
// Combat timer with warnings and time up handler
const handleTimeUp = useCallback(() => {
// End round when time runs out
if (!combatState.roundEnded) {
combatActions.setRoundEnded(true);
addCombatMessage("시간 종료!", "Time's Up!");
// Use refs to get latest values without dependency issues
const currentPlayers = validPlayersRef.current;
const player1Health = currentPlayers[0].health;
const player2Health = currentPlayers[1].health;
if (player1Health > player2Health) {
// Player 1 wins - update match score
updateMatchScore(0);
startTransitionRef.current(currentPlayers[0], internalRoundRef.current); // Player 1 wins round
} else if (player2Health > player1Health) {
// Player 2 wins - update match score
updateMatchScore(1);
startTransitionRef.current(currentPlayers[1], internalRoundRef.current); // Player 2 wins round
} else {
// Tie - no winner for this round, no score update
startTransitionRef.current(null, internalRoundRef.current);
}
}
}, [
combatState.roundEnded,
combatActions,
addCombatMessage,
updateMatchScore,
]);
// Ref pattern to stabilize onTimeUp callback for timer
const handleTimeUpRef = useRef(handleTimeUp);
useEffect(() => {
handleTimeUpRef.current = handleTimeUp;
}, [handleTimeUp]);
// Create a unique key for timer reset based on round number
// This forces the timer to reset when a new round starts
const timerResetKey = `round-${internalRound}`;
const timerState = useCombatTimer({
initialTime: Math.max(0, timeRemaining),
isPaused:
isPaused ||
!combatState.roundStarted ||
combatState.roundEnded ||
!matchCountdownComplete ||
showRoundStart,
onTimeUp: useCallback(() => handleTimeUpRef.current(), []),
warningThreshold: 10,
urgentThreshold: 5,
// Pass round number to force timer reset on new rounds
resetKey: timerResetKey,
});
// Shared round start logic - forces round to start regardless of current state
// This is called after state has been reset, so we trust the caller
// Note: Using useCallback with complete dependencies to ensure closure has latest state
const startRound = useCallback(() => {
// Always start the round when this is called - the caller is responsible
// for ensuring this is the right time to start
if (import.meta.env.DEV) {
console.log("[DEV] Starting round, setting roundStarted=true");
}
combatActions.setRoundStarted(true);
combatActions.setRoundEnded(false); // Ensure roundEnded is false
addCombatMessage("라운드 시작!", "Round Start!");
const player = validPlayers[0];
if (player?.archetype) {
const playerArchetype = player.archetype.toLowerCase();
combatAudio.playArchetypeMusic(playerArchetype, 2000);
} else {
combatAudio.playCombatMusic(2000);
}
}, [combatActions, addCombatMessage, validPlayers, combatAudio]);
// Auto-start first round since countdown is disabled
// Use a separate ref for the timer to avoid cleanup canceling the start
const hasAutoStartedRef = useRef(false);
useEffect(() => {
if (matchCountdownComplete && !hasAutoStartedRef.current) {
hasAutoStartedRef.current = true;
// Directly set roundStarted=true without going through startRound callback
// This avoids dependency issues with the callback reference
combatActions.setRoundStarted(true);
addCombatMessage("라운드 시작!", "Round Start!");
// Start music
const player = validPlayers[0];
if (player?.archetype) {
const playerArchetype = player.archetype.toLowerCase();
combatAudio.playArchetypeMusic(playerArchetype, 2000);
} else E{
combatAudio.playCombatMusic(2000);
}
}
}, [
matchCountdownComplete,
combatActions,
addCombatMessage,
validPlayers,
combatAudio,
]);
// AI systems
const adaptiveDifficulty = useMemo(() => new AdaptiveDifficulty(), []);
// Persist AI difficulty metrics
useEffect(() => {
try {
const savedMetrics = localStorage.getItem("ai_difficulty_metrics");
if (savedMetrics) {
adaptiveDifficulty.importMetrics(savedMetrics);
}
} catch (err) {
console.warn("Failed to load AI difficulty metrics:", err);
}
return () => {
try {
const metrics = adaptiveDifficulty.exportMetrics();
localStorage.setItem("ai_difficulty_metrics", metrics);
} catch (err) {
console.warn("Failed to save AI difficulty metrics:", err);
}
};
}, [adaptiveDifficulty]);
const aiPersonality = useMemo(
() => getPersonalityByArchetype(validPlayers[1].archetype),
[validPlayers]
);
// AI stance change handler
const handleAIStanceChange = useCallback(
(stance: TrigramStance) => {
onPlayerUpdate(1, { currentStance: stance });
addCombatMessage(
`AI 자세 변경: ${stance}`,
`AI Stance Change: ${stance}`
);
},
[onPlayerUpdate, addCombatMessage]
);
// Hit effect handlers
const handleEffectComplete = useCallback(
(effectId: string) => {
combatActions.removeHitEffect(effectId);
},
[combatActions]
);
const createHitEffect = useCallback(
(
id: string,
type: HitEffectType,
position: Position,
intensity: number
): HitEffect => ({
id,
type,
attackerId: "player1",
defenderId: "player2",
timestamp: Date.now(),
duration: 1000,
position,
intensity,
startTime: Date.now(),
}),
[]
);
const addHitEffect = useCallback(
(type: HitEffectType, position: Position, intensity: number = 1) => {
const effect = createHitEffect(
`effect_${Date.now()}`,
type,
position,
intensity
);
combatActions.addHitEffect(effect);
},
[createHitEffect, combatActions]
);
// Combat action handlers
const {
handleAttack,
handleDefend,
handleStanceSwitch,
handleAIAttack,
handleAIDefend,
handleAITechnique,
moveAIPlayer,
} = useCombatActions({
validPlayers,
playerPositions: [playerPositions[0], playerPositions[1]],
combatState,
combatActions,
combatSystem,
onPlayerUpdate,
addCombatMessage,
addHitEffect,
arenaBounds,
combatAudio,
});
// Store handleAttack in ref for animation callback (avoid circular dependency)
useEffect(() => {
handleAttackRef.current = handleAttack;
}, [handleAttack]);
// Technique selection and execution
const techniqueSelection = useTechniqueSelection({
player: validPlayers[0],
enabled:
!isPaused &&
combatState.roundStarted &&
!combatState.roundEnded &&
matchCountdownComplete &&
!showRoundStart,
onTechniqueExecute: useCallback(
(technique: Technique) => {
// Show technique name in action feedback
feedbackActions.showTechnique(
technique.name.korean,
technique.name.english
);
// Set attack animation based on technique
// 기술에 따른 공격 애니메이션 설정
const animationName = getAnimationForTechnique(
technique.name.english || technique.id
);
setPlayer1AttackAnimation(animationName);
// Trigger attack animation transition
// 공격 애니메이션 전환 트리거
player1Animation.transitionTo("attack");
combatActions.setExecutingTechnique(true);
// Deduct resources
onPlayerUpdate(0, {
stamina: Math.max(0, validPlayers[0].stamina - technique.staminaCost),
ki: Math.max(0, validPlayers[0].ki - technique.kiCost),
});
// Execute attack WITH the selected technique (not basic attack)
handleAttack(technique);
// Add combat message
addCombatMessage(
`${technique.name.korean} 사용!`,
`Used ${technique.name.english}!`
);
},
[
validPlayers,
onPlayerUpdate,
feedbackActions,
handleAttack,
addCombatMessage,
player1Animation,
combatActions,
]
),
});
// Convert cooldowns to Map for TechniqueBar
const cooldownsMap = useMemo(() => {
const map = new Map<string, number>();
techniqueSelection.activeCooldowns.forEach((cd) => {
map.set(cd.techniqueId, cd.remaining);
});
return map;
}, [techniqueSelection.activeCooldowns]);
// Track previous stance for visual feedback
const [previousStance, setPreviousStance] = useState<number>(0);
// Get current stance index for visual feedback using optimized lookup
const currentPlayerStance = validPlayers[0].currentStance;
const currentStanceIndex = useMemo(() => {
return STANCE_INDEX_MAP.get(currentPlayerStance) ?? 0;
}, [currentPlayerStance]);
// Extract player health values for dependency arrays
const player1Health = validPlayers[0].health;
const player2Health = validPlayers[1].health;
// Watch for player 2 health decrease to trigger damage feedback
const lastPlayer2HealthRef = useRef(player2Health);
useEffect(() => {
const currentHealth = player2Health;
const previousHealth = lastPlayer2HealthRef.current;
const damageDone = previousHealth - currentHealth;
Iif (damageDone > 0 && combatState.roundStarted && !combatState.roundEnded) {
// Determine damage type based on amount
const getDamageType = (): "critical" | "vital" | "normal" => {
if (damageDone >= 25) return "critical";
if (damageDone >= 20) return "vital";
return "normal";
};
const damageType = getDamageType();
// Add damage number at opponent position
feedbackActions.addDamageNumber(
Math.round(damageDone),
playerPositions[1],
damageType
);
// Increment combo
feedbackActions.incrementCombo();
// Add action feedback for critical hits
if (damageType === "critical") {
feedbackActions.addActionFeedback(
"critical",
"Critical!",
"치명타!",
playerPositions[0]
);
}
}
lastPlayer2HealthRef.current = currentHealth;
}, [
player2Health,
validPlayers,
playerPositions,
feedbackActions,
combatState.roundStarted,
combatState.roundEnded,
]);
// Watch for player 1 health decrease (AI attacks player)
const lastPlayer1HealthRef = useRef(player1Health);
useEffect(() => {
const currentHealth = player1Health;
const previousHealth = lastPlayer1HealthRef.current;
const damageDone = previousHealth - currentHealth;
Iif (damageDone > 0 && combatState.roundStarted && !combatState.roundEnded) {
// Add damage number at player position for AI hits
const damageType =
damageDone >= 20 ? ("critical" as const) : ("normal" as const);
feedbackActions.addDamageNumber(
Math.round(damageDone),
playerPositions[0],
damageType
);
}
lastPlayer1HealthRef.current = currentHealth;
}, [
player1Health,
validPlayers,
playerPositions,
feedbackActions,
combatState.roundStarted,
combatState.roundEnded,
]);
// Create enhanced attack handler with action feedback and animation
const handleAttackWithFeedback = useCallback(() => {
// Set default attack animation for basic attacks (without specific technique)
// 기본 공격 애니메이션 설정 (잽)
setPlayer1AttackAnimation("jab");
// Try to transition to attack animation
const success = player1Animation.transitionTo("attack");
if (success) {
// Attack execution will happen at frame 6 in onFrame callback
combatActions.setExecutingTechnique(true);
} else {
// Fallback: animation transition failed, execute attack logic immediately
console.warn(
"Attack animation transition failed; executing attack logic directly."
);
handleAttack();
}
}, [player1Animation, combatActions, handleAttack]);
// Create enhanced defend handler with action feedback and animation
const handleDefendWithFeedback = useCallback(() => {
const defenderPos = playerPositions[0];
// Try to transition to defend animation
const success = player1Animation.transitionTo("defend");
if (success) {
handleDefend();
feedbackActions.addActionFeedback(
"blocked",
"Blocked",
"방어!",
defenderPos
);
} else {
// Fallback: animation transition failed, execute defend logic immediately
console.warn(
"Defend animation transition failed; executing defend logic directly."
);
handleDefend();
feedbackActions.addActionFeedback(
"blocked",
"Blocked",
"방어!",
defenderPos
);
}
}, [handleDefend, playerPositions, feedbackActions, player1Animation]);
// Use keyboard controls hook for enhanced input handling with visual feedback
const { queuedInputs, showHints } = useKeyboardControls({
onStanceChange: useCallback(
(stanceIndex: number) => {
const stance = TRIGRAM_STANCES_ORDER[stanceIndex];
if (stance) {
// Capture previous stance BEFORE changing
const prevStance = STANCE_INDEX_MAP.get(currentPlayerStance) ?? 0;
setPreviousStance(prevStance);
// Trigger stance change animation
player1Animation.transitionTo("stance_change");
handleStanceSwitch(stance);
}
},
[handleStanceSwitch, currentPlayerStance, player1Animation]
),
onAction: useCallback(
(action: string) => {
switch (action) {
case "attack":
// Execute currently selected technique via technique selection system
techniqueSelection.executeTechnique();
break;
case "block":
handleDefendWithFeedback();
break;
// Movement and other actions handled by existing system
}
},
[techniqueSelection, handleDefendWithFeedback]
),
enabled:
!isPaused &&
!showPauseMenu &&
combatState.roundStarted &&
!combatState.roundEnded &&
matchCountdownComplete &&
!showRoundStart &&
!combatState.isExecutingTechnique,
currentStance: currentStanceIndex,
playSFX: audio.playSFX,
});
// Mobile touch control state
const [stanceWheelExpanded, setStanceWheelExpanded] = useState(false);
const activeMobileKeyRef = useRef<string | null>(null);
/**
* Mobile touch control handler - Converts VirtualDPad touch inputs to keyboard events
*
* Dispatches synthetic KeyboardEvents with proper properties to ensure compatibility
* with usePlayerMovement hook. The synthetic events include:
* - key: The character key (w/a/s/d)
* - code: The physical key code (KeyW/KeyA/KeyS/KeyD)
* - bubbles: true - Allows event to propagate through DOM
* - cancelable: true - Allows event to be prevented
*
* These properties are essential for the keyboard event listeners in inputSystem.ts
* to properly recognize and process the movement commands.
*
* @param direction - The D-pad direction or null
* @param eventType - 'start' for press, 'end' for release
*/
const handleMobileMove = useCallback(
(direction: Direction | null, eventType: DPadEventType) => {
// Map D-pad directions to movement keys (WASD)
const directionMap: Record<Direction, string> = {
up: "w",
"up-right": "w", // Diagonal simplified to primary direction
right: "d",
"down-right": "s",
down: "s",
"down-left": "s",
left: "a",
"up-left": "w",
};
if (eventType === "start" && direction) {
// Release previous key if different (prevents stuck keys)
if (
activeMobileKeyRef.current &&
activeMobileKeyRef.current !== directionMap[direction]
) {
const prevKey = activeMobileKeyRef.current;
window.dispatchEvent(
new KeyboardEvent("keyup", {
key: prevKey,
code: `Key${prevKey.toUpperCase()}`,
bubbles: true,
cancelable: true,
})
);
}
// Press new key with proper keyboard event properties
// These properties ensure usePlayerMovement recognizes the synthetic event
const key = directionMap[direction];
activeMobileKeyRef.current = key;
window.dispatchEvent(
new KeyboardEvent("keydown", {
key,
code: `Key${key.toUpperCase()}`,
bubbles: true,
cancelable: true,
})
);
} else if (eventType === "end") {
// Release active key when D-pad released
if (activeMobileKeyRef.current) {
const key = activeMobileKeyRef.current;
window.dispatchEvent(
new KeyboardEvent("keyup", {
key,
code: `Key${key.toUpperCase()}`,
bubbles: true,
cancelable: true,
})
);
activeMobileKeyRef.current = null;
}
}
},
[]
);
const handleMobileAttack = useCallback(() => {
// Execute currently selected technique via technique selection system
techniqueSelection.executeTechnique();
}, [techniqueSelection]);
const handleMobileBlock = useCallback(
(eventType: ButtonEventType) => {
if (eventType === "start") {
handleDefendWithFeedback();
}
},
[handleDefendWithFeedback]
);
const handleMobileStanceChange = useCallback(
(stanceIndex: number) => {
const stance = TRIGRAM_STANCES_ORDER[stanceIndex];
if (stance) {
const prevStance = STANCE_INDEX_MAP.get(currentPlayerStance) ?? 0;
setPreviousStance(prevStance);
handleStanceSwitch(stance);
}
},
[handleStanceSwitch, currentPlayerStance]
);
const handleMobileGesture = useCallback(
(gesture: GestureEvent) => {
switch (gesture.type) {
case "swipe-right":
// Advance toward opponent
window.dispatchEvent(new KeyboardEvent("keydown", { key: "d" }));
break;
case "swipe-left":
// Retreat from opponent
window.dispatchEvent(new KeyboardEvent("keydown", { key: "a" }));
break;
case "swipe-up":
// High attack mode - execute selected technique
techniqueSelection.executeTechnique();
break;
case "swipe-down":
// Low attack mode - execute selected technique
techniqueSelection.executeTechnique();
break;
case "two-finger-tap":
// Activate vital point targeting mode
// TODO: Implement vital point mode toggle
audio.playSFX("menu_select");
break;
}
},
[techniqueSelection, audio]
);
// Check if mobile controls should be enabled
const mobileControlsEnabled =
isMobile &&
!isPaused &&
!showPauseMenu &&
combatState.roundStarted &&
!combatState.roundEnded &&
matchCountdownComplete &&
!showRoundStart &&
!combatState.isExecutingTechnique;
// Note: Player 1 position is updated via the onPositionChange callback
// in usePlayerMovement config above, not via useEffect
// Round management
useEffect(() => {
if (isPaused) return;
Iif (timeRemaining <= 0 && !combatState.roundEnded) {
combatActions.setRoundEnded(true);
combatActions.setRoundStarted(false);
combatActions.setRoundDisplayStatus("end");
combatAudio.stopCombatMusic(1000);
const winner = validPlayers[0].health > validPlayers[1].health ? 0 : 1;
const roundWinner = validPlayers[winner];
// Update match score using deferred callback
updateMatchScore(winner);
addCombatMessage("라운드 종료!", "Round Over!");
// Start round transition instead of immediately ending game
setTimeout(() => {
startTransition(roundWinner, internalRound);
}, 1500);
}
// Note: Round start is now triggered by MatchCountdown and RoundStartAnnouncement components
// via their onComplete callbacks to ensure proper sequencing with countdown animations
}, [
timeRemaining,
combatState.roundEnded,
combatState.roundStarted,
validPlayers,
onGameEnd,
addCombatMessage,
internalRound,
isPaused,
combatActions,
combatAudio,
startTransition,
updateMatchScore,
]);
// Create a ref for the callback to avoid circular dependency
const executeAIActionCallbackRef = useRef<
((action: string, targetPos?: Position) => void) | undefined
>(undefined);
// AI Combat System - must be before executeAIActionCallback to provide aiState
const { aiState, updateDifficultyTarget } = useAICombat({
player: validPlayers[1],
opponent: validPlayers[0],
personality: aiPersonality,
adaptiveDifficulty,
isPaused,
roundStarted: combatState.roundStarted,
roundEnded: combatState.roundEnded,
arenaBounds,
onExecuteAction: (action, targetPos) =>
executeAIActionCallbackRef.current?.(action, targetPos),
onStanceChange: handleAIStanceChange,
});
// Calculate current difficulty tier for display
// Force recalculation when the adaptive difficulty system changes
const currentDifficultyTier = useMemo(
() => adaptiveDifficulty.getDifficultyTier(),
[adaptiveDifficulty]
);
// Adaptive difficulty adjustment every 2-3 rounds after round ends
useEffect(() => {
// Only adjust after round ends (not during round or at start)
Eif (!combatState.roundEnded || internalRound < 1) {
return;
}
// Adjust every 2 rounds (after rounds 2, 4, 6, etc.)
// This ensures at least 2 rounds between adjustments for smooth progression
const roundsCompleted = internalRound;
if (roundsCompleted % 2 === 0) {
// Update AI skill metrics based on player performance.
// NOTE (Phase 1 adaptive difficulty):
// - Only hits/attacks/damage metrics are currently sourced from PlayerState.
// - Combo, block, reaction-time, vital-point, and stance-change metrics are
// intentionally stubbed here (0 or constant) until PlayerState and telemetry
// are extended in a follow-up phase.
// This keeps the system functional while we iterate on richer skill tracking.
const player1 = validPlayersRef.current[0];
adaptiveDifficulty.updateSkillMetrics({
hitsLanded: player1.hitsLanded ?? 0,
totalAttacks: (player1.hitsLanded ?? 0) + (player1.misses ?? 0),
combosExecuted: 0, // TODO (Phase 2): Track combo count in PlayerState
perfectBlockCount: 0, // TODO (Phase 2): Track perfect blocks in PlayerState
avgReactionTimeMs: 600, // TODO (Phase 2): Track player reaction time
vitalPointsHit: 0, // TODO (Phase 2): Track vital point hits
effectiveStanceChanges: 0, // TODO (Phase 2): Track stance changes
damageDealt: player1.totalDamageDealt ?? 0,
damageTaken: player1.totalDamageReceived ?? 0,
});
// Get new difficulty parameters and update AI
const newParams = adaptiveDifficulty.getDifficultyParameters();
updateDifficultyTarget(newParams);
if (import.meta.env.DEV) {
const tier = adaptiveDifficulty.getDifficultyTier();
console.log(
`[DEV] Difficulty adjusted after round ${roundsCompleted}, new tier: ${tier}`
);
}
}
}, [
combatState.roundEnded,
internalRound,
adaptiveDifficulty,
updateDifficultyTarget,
]);
// AI action execution - uses aiState from useAICombat
const executeAIActionCallback = useCallback(
(action: string, targetPos?: Position) => {
switch (action) {
case "attack":
// Set AI attack animation based on technique
// AI 공격 애니메이션 설정
if (
aiState.selectedTechnique?.name?.english ||
aiState.selectedTechnique?.englishName
) {
const techName =
aiState.selectedTechnique.name?.english ||
aiState.selectedTechnique.englishName ||
"jab";
setPlayer2AttackAnimation(getAnimationForTechnique(techName));
} else {
setPlayer2AttackAnimation("jab");
}
player2Animation.transitionTo("attack");
handleAIAttack(aiState.selectedTechnique, aiState.targetVitalPoint);
break;
case "defend":
player2Animation.transitionTo("defend");
handleAIDefend();
break;
case "technique":
case "combo":
// Set AI attack animation based on technique
// AI 기술 애니메이션 설정
if (
aiState.selectedTechnique?.name?.english ||
aiState.selectedTechnique?.englishName
) {
const techName =
aiState.selectedTechnique.name?.english ||
aiState.selectedTechnique.englishName ||
"cross";
setPlayer2AttackAnimation(getAnimationForTechnique(techName));
} else {
setPlayer2AttackAnimation("cross");
}
player2Animation.transitionTo("attack");
handleAITechnique(
aiState.selectedTechnique,
aiState.targetVitalPoint
);
break;
case "approach":
case "retreat":
case "circle":
if (targetPos) {
moveAIPlayer(targetPos);
}
break;
case "feint":
{
const playerPos = validPlayers[0].position;
const feintOffset = 50;
const feintPos = {
x: playerPos.x + (Math.random() - 0.5) * feintOffset,
y: playerPos.y + (Math.random() - 0.5) * feintOffset,
};
moveAIPlayer(feintPos);
addCombatMessage("AI 페인트", "AI Feint");
setTimeout(() => {
if (
!combatState.roundEnded &&
combatState.roundStarted &&
validPlayers.length >= 2
) {
const currentPlayerPos = validPlayers[0].position;
const currentAiPos = validPlayers[1].position;
const dx = currentAiPos.x - currentPlayerPos.x;
const dy = currentAiPos.y - currentPlayerPos.y;
const dist = Math.sqrt(dx * dx + dy * dy) || 1;
const retreatDistance = 80;
const retreatPos = {
x: Math.max(
arenaBounds.x,
Math.min(
arenaBounds.x + arenaBounds.width - 60,
currentPlayerPos.x + (dx / dist) * retreatDistance
)
),
y: Math.max(
arenaBounds.y,
Math.min(
arenaBounds.y + arenaBounds.height - 180,
currentPlayerPos.y + (dy / dist) * retreatDistance
)
),
};
moveAIPlayer(retreatPos);
}
}, 200);
}
break;
case "counter":
// Set AI attack animation for counter attack
// AI 반격 애니메이션 설정
if (
aiState.selectedTechnique?.name?.english ||
aiState.selectedTechnique?.englishName
) {
const techName =
aiState.selectedTechnique.name?.english ||
aiState.selectedTechnique.englishName ||
"cross";
setPlayer2AttackAnimation(getAnimationForTechnique(techName));
} else {
setPlayer2AttackAnimation("cross");
}
player2Animation.transitionTo("attack");
handleAIAttack(aiState.selectedTechnique, aiState.targetVitalPoint);
addCombatMessage("AI 반격!", "AI Counter!");
break;
}
},
[
handleAIAttack,
handleAIDefend,
handleAITechnique,
moveAIPlayer,
addCombatMessage,
validPlayers,
arenaBounds,
combatState.roundEnded,
combatState.roundStarted,
aiState.selectedTechnique,
aiState.targetVitalPoint,
player2Animation,
]
);
// Update the ref
useEffect(() => {
executeAIActionCallbackRef.current = executeAIActionCallback;
}, [executeAIActionCallback]);
// Update adaptive difficulty metrics
useEffect(() => {
Iif (combatState.roundEnded && validPlayers.length === 2) {
const player = validPlayers[0];
const totalAttacks = (player.hitsLanded ?? 0) + (player.hitsTaken ?? 0);
if (totalAttacks === 0) return;
adaptiveDifficulty.updateSkillMetrics({
hitsLanded: player.hitsLanded ?? 0,
totalAttacks,
combosExecuted: player.comboCount ?? 0,
perfectBlockCount: 0,
avgReactionTimeMs: 500,
vitalPointsHit: player.vitalPointHits ?? 0,
effectiveStanceChanges: 0,
damageDealt: player.totalDamageDealt ?? 0,
damageTaken: player.totalDamageReceived ?? 0,
});
}
}, [combatState.roundEnded, adaptiveDifficulty, validPlayers]);
// Check game end conditions
const checkGameEnd = useCallback(() => {
Iif (combatState.roundEnded) return;
const p1Defeated = validPlayers[0].health <= 0;
const p2Defeated = validPlayers[1].health <= 0;
Iif (p1Defeated || p2Defeated) {
combatActions.setRoundEnded(true);
combatActions.setRoundStarted(false);
combatActions.setRoundDisplayStatus("ko");
const winner = p1Defeated ? 1 : 0;
const roundWinner = validPlayers[winner];
// Update match score using deferred callback
updateMatchScore(winner);
addCombatMessage(
p1Defeated ? "플레이어 1 패배" : "플레이어 1 승리!",
p1Defeated ? "Player 1 Defeated" : "Player 1 Victory!"
);
// Start round transition
setTimeout(() => {
startTransition(roundWinner, internalRound);
}, 1500);
}
}, [
validPlayers,
addCombatMessage,
combatState.roundEnded,
combatActions,
internalRound,
startTransition,
updateMatchScore,
]);
useEffect(() => {
checkGameEnd();
}, [player1Health, player2Health, checkGameEnd]);
// Keyboard input handling
useEffect(() => {
const handleCombatInput = (event: KeyboardEvent) => {
// ESC key toggles pause menu (unless pause menu is already open)
if (event.key === "Escape") {
event.preventDefault();
if (showPauseMenu) {
handleResume();
} else {
handlePause();
}
return;
}
// Block all other combat inputs when paused or during pause menu
// isPaused: External pause state from parent component
// showPauseMenu: Local pause menu UI is visible
// Both conditions block input to prevent combat actions while game is paused
if (isPaused || showPauseMenu) {
return;
}
// Block all combat inputs during countdown or round start announcement
if (!matchCountdownComplete || showRoundStart) {
return;
}
if (
!combatState.roundStarted ||
combatState.roundEnded ||
combatState.isExecutingTechnique
) {
return;
}
const key = event.key.toLowerCase();
if (key >= "1" && key <= "8") {
const stanceIndex = parseInt(key) - 1;
const stances: TrigramStance[] = [
TrigramStance.GEON,
TrigramStance.TAE,
TrigramStance.LI,
TrigramStance.JIN,
TrigramStance.SON,
TrigramStance.GAM,
TrigramStance.GAN,
TrigramStance.GON,
];
handleStanceSwitch(stances[stanceIndex]);
event.preventDefault();
}
if (key === " ") {
handleAttackWithFeedback();
event.preventDefault();
}
if (event.key === "Shift") {
handleDefendWithFeedback();
event.preventDefault();
}
};
window.addEventListener("keydown", handleCombatInput);
return () => window.removeEventListener("keydown", handleCombatInput);
}, [
combatState.roundStarted,
combatState.roundEnded,
combatState.isExecutingTechnique,
matchCountdownComplete,
showRoundStart,
isPaused,
showPauseMenu,
handleStanceSwitch,
handleAttackWithFeedback,
handleDefendWithFeedback,
handlePause,
handleResume,
]);
return (
<div
style={{
width: `${width}px`,
height: `${height}px`,
position: "relative",
backgroundColor: "#0a0a0a",
}}
data-testid="combat-screen"
>
{/* Three.js Canvas for 3D rendering */}
<Canvas
camera={{ position: [0, 8, 12], fov: 60 }}
gl={{
antialias: true,
alpha: false,
powerPreference: "high-performance",
}}
dpr={[1, 2]}
shadows={false}
onCreated={({ gl, scene }) => {
gl.setClearColor(KOREAN_COLORS.UI_BACKGROUND_DARK, 1);
scene.fog = new THREE.Fog(KOREAN_COLORS.UI_BACKGROUND_DARK, 15, 35);
}}
>
{/* Animation updater - updates both player animations at 60fps */}
<AnimationUpdater
player1Animation={player1Animation}
player2Animation={player2Animation}
/>
{/* 3D Combat Arena */}
<CombatArena3D lighting="cyberpunk" />
{/* Player 1 */}
<SkeletalPlayer3D
{...convertPlayerStateToProps(
validPlayers[0],
player1Position3D,
player1Rotation, // Dynamic rotation - always faces opponent
{
isMobile,
facing: "right", // No flip - rotation handles facing direction
// Enable facial expressions and eye tracking - 얼굴 표정 및 눈 추적 활성화
enableFacialExpressions: true,
enableEyeTracking: true,
opponentPosition: player2Position3D,
}
)}
currentAnimation={animationStateToPlayerAnimation(
player1Animation.currentState
)}
attackAnimation={player1AttackAnimation}
/>
{/* Player 2 (AI) */}
<SkeletalPlayer3D
{...convertPlayerStateToProps(
validPlayers[1],
player2Position3D,
player2Rotation, // Dynamic rotation - always faces opponent
{
isMobile,
facing: "right", // No flip - rotation handles facing direction
// Enable facial expressions and eye tracking - 얼굴 표정 및 눈 추적 활성화
enableFacialExpressions: true,
enableEyeTracking: true,
opponentPosition: player1Position3D,
}
)}
currentAnimation={animationStateToPlayerAnimation(
player2Animation.currentState
)}
attackAnimation={player2AttackAnimation}
/>
{/* Hit Effects */}
<HitEffects3D
effects={combatState.hitEffects}
onEffectComplete={handleEffectComplete}
arenaBounds={arenaBounds}
/>
{/* Vital Point Overlay - Show on both players */}
{overlayVisible && (
<>
{/* Player 1 Vital Points */}
<VitalPointMarkers3D
position={player1Position3D}
visible={overlayVisible}
severityFilter={severityFilters}
regionFilter={regionFilter}
searchQuery={searchQuery}
showLabels={showLabels}
scale={scale}
animated={animated}
onPointClick={() => {
// Optional: Add point targeting in combat
}}
/>
{/* Player 2 Vital Points */}
<VitalPointMarkers3D
position={player2Position3D}
visible={overlayVisible}
severityFilter={severityFilters}
regionFilter={regionFilter}
searchQuery={searchQuery}
showLabels={showLabels}
scale={scale}
animated={animated}
onPointClick={() => {
// Optional: Add point targeting in combat
}}
/>
</>
)}
{/* Vital Point Overlay Controls - fixed screen position, left side below player status */}
<VitalPointOverlayControls
screenPosition={{ top: "200px", left: "20px" }}
visible={overlayVisible}
onVisibleChange={setOverlayVisible}
severityFilters={severityFilters}
onSeverityFiltersChange={setSeverityFilters}
regionFilter={regionFilter}
onRegionFilterChange={setRegionFilter}
searchQuery={searchQuery}
onSearchQueryChange={setSearchQuery}
showLabels={showLabels}
onShowLabelsChange={setShowLabels}
animated={animated}
onAnimatedChange={setAnimated}
scale={scale}
onScaleChange={setScale}
isMobile={isMobile}
/>
{/* Action Feedback - Damage Numbers */}
<DamageNumbers
damages={feedbackState.damageNumbers}
isMobile={isMobile}
arenaBounds={arenaBounds}
/>
{/* Action Feedback - Action Indicators */}
<ActionFeedback
feedbacks={feedbackState.actionFeedbacks}
isMobile={isMobile}
arenaBounds={arenaBounds}
/>
{/* Combo Counter */}
<ComboCounter combo={feedbackState.comboCount} isMobile={isMobile} />
{/* Technique Name Display */}
{feedbackState.currentTechnique && (
<TechniqueName
korean={feedbackState.currentTechnique.korean}
english={feedbackState.currentTechnique.english}
isMobile={isMobile}
onComplete={() => feedbackActions.hideTechnique()}
/>
)}
{/* Performance Overlay (Development Only) - positioned in bottom-left of 3D scene */}
{import.meta.env.DEV && (
<PerformanceOverlay3D position={[-9, -2, 5]} visible={true} />
)}
{/* Round display status overlay - only show when content is ready */}
{contentReady &&
combatState.roundDisplayStatus &&
combatState.roundDisplayStatus !== null && (
<Html fullscreen>
<div
style={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
fontSize: "72px",
fontWeight: "bold",
fontFamily: FONT_FAMILY.KOREAN,
color: `#${KOREAN_COLORS.ACCENT_GOLD.toString(16).padStart(
6,
"0"
)}`,
textShadow: "0 0 20px rgba(255, 215, 0, 0.8)",
pointerEvents: "none",
zIndex: 1000,
}}
>
{combatState.roundDisplayStatus === "start" && "라운드 시작!"}
{combatState.roundDisplayStatus === "fight" && "전투!"}
{combatState.roundDisplayStatus === "end" && "라운드 종료"}
{combatState.roundDisplayStatus === "ko" && "K.O.!"}
</div>
</Html>
)}
{/* Visual Feedback Components for Keyboard Controls */}
<StanceChangeIndicator
currentStance={currentStanceIndex}
previousStance={previousStance}
isMobile={isMobile}
/>
<KeyboardHints
visible={showHints}
currentStance={currentStanceIndex}
isMobile={isMobile}
/>
<InputBufferDisplay queuedInputs={queuedInputs} isMobile={isMobile} />
{/* Mobile Touch Controls - Only shown on mobile devices */}
{isMobile && (
<MobileControlsWrapper
enabled={mobileControlsEnabled}
currentStanceIndex={currentStanceIndex}
stanceWheelExpanded={stanceWheelExpanded}
onMove={handleMobileMove}
onAttack={handleMobileAttack}
onBlock={handleMobileBlock}
onStanceChange={handleMobileStanceChange}
onStanceWheelToggle={() =>
setStanceWheelExpanded(!stanceWheelExpanded)
}
onGesture={handleMobileGesture}
/>
)}
{/* Performance Monitoring - FPS display (dev mode only) */}
{process.env.NODE_ENV === "development" && (
<FPSMonitor
enabled={true}
warningThreshold={50}
criticalThreshold={30}
/>
)}
</Canvas>
{/* Html UI Overlays (positioned absolutely over Canvas) */}
<div
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
pointerEvents: "none",
}}
>
{/* Combat Title - Top Center */}
<div
style={{
position: "absolute",
top: "10px",
left: "50%",
transform: "translateX(-50%)",
fontSize: isMobile ? "18px" : "24px",
fontWeight: "bold",
fontFamily: FONT_FAMILY.KOREAN,
color: `#${KOREAN_COLORS.ACCENT_GOLD.toString(16).padStart(
6,
"0"
)}`,
textShadow: "0 0 4px rgba(0,0,0,0.8)",
zIndex: 200,
}}
>
전투 | Combat
</div>
{/* Combat Timer - Below Title */}
{combatState.roundStarted &&
!combatState.roundEnded &&
matchCountdownComplete &&
!showRoundStart && (
<CombatTimer
formattedTime={timerState.formattedTime}
warningLevel={timerState.warningLevel}
isTimeUp={timerState.isTimeUp}
isMobile={isMobile}
style={{ top: isMobile ? "45px" : "50px" }}
/>
)}
{/* Volume Control - consistent with other screens */}
<VolumeControl position="bottom-right" compact={isMobile} />
{/* Player 1 HUD - Top Left */}
<PlayerHUD
player={validPlayers[0]}
position="left"
isMobile={isMobile}
/>
{/* Player 2 HUD - Top Right */}
<PlayerHUD
player={validPlayers[1]}
position="right"
isMobile={isMobile}
/>
{/* Body Part Health Displays - show individual body part health bars */}
{validPlayers[0].bodyPartHealth && (
<BodyPartHealthDisplay
bodyPartHealth={validPlayers[0].bodyPartHealth}
playerId={validPlayers[0].id}
position="left"
isMobile={isMobile}
/>
)}
{validPlayers[1].bodyPartHealth && (
<BodyPartHealthDisplay
bodyPartHealth={validPlayers[1].bodyPartHealth}
playerId={validPlayers[1].id}
position="right"
isMobile={isMobile}
/>
)}
{/* AI Difficulty Indicator - Shows current adaptive difficulty tier */}
<DifficultyIndicator tier={currentDifficultyTier} isMobile={isMobile} />
{/* Player State Visual Indicators */}
{/* Player 1 State Overlay - includes consciousness blur, pain vignette, etc. */}
<PlayerStateOverlay
pain={validPlayers[0].pain}
balanceState={getBalanceState(validPlayers[0].balance)}
position="left"
consciousness={validPlayers[0].consciousness}
bloodLoss={0} // FIXME: bloodLoss property not yet added to PlayerState interface - overlay will not display until implemented
stamina={validPlayers[0].stamina}
isMobile={isMobile}
/>
{/* Note: Player 2 (AI) does not get fullscreen state overlays like consciousness blur */}
{/* as those effects would incorrectly affect the player's view */}
{/* Technique Bar - Bottom Center */}
{combatState.roundStarted &&
!combatState.roundEnded &&
matchCountdownComplete &&
!showRoundStart && (
<TechniqueBar
techniques={techniqueSelection.availableTechniques}
player={validPlayers[0]}
selectedIndex={techniqueSelection.selectedIndex}
cooldowns={cooldownsMap}
onTechniqueSelect={techniqueSelection.selectTechnique}
onTechniqueHover={(_tech) => {
// Could add additional hover effects here
}}
isMobile={isMobile}
screenWidth={width}
screenHeight={height}
/>
)}
{/* Combat Controls and Stats */}
<CombatControlsPanel
combatMessages={combatState.combatMessages}
isMobile={isMobile}
/>
{/* Combat Footer - Back Button */}
<div
style={{
position: "absolute",
bottom: isMobile ? "20px" : "30px",
left: "50%",
transform: "translateX(-50%)",
minHeight: "50px",
pointerEvents: "auto",
zIndex: 100,
}}
>
{/* Back button container */}
<div
style={{
textAlign: "center",
background: "rgba(10, 10, 15, 0.85)",
border: `2px solid ${hexToRgbaString(
KOREAN_COLORS.PRIMARY_CYAN,
0.8
)}`,
borderRadius: "8px",
padding: isMobile ? "8px 12px" : "10px 16px",
}}
>
<style>
{`
.combat-return-menu-btn {
background: ${hexToRgbaString(
KOREAN_COLORS.PRIMARY_CYAN,
0.9
)};
color: ${hexToRgbaString(
KOREAN_COLORS.UI_BACKGROUND_DARK,
1
)};
border: none;
border-radius: 8px;
padding: ${isMobile ? "10px 16px" : "12px 24px"};
font-size: ${isMobile ? "14px" : "16px"};
font-family: ${FONT_FAMILY.KOREAN};
font-weight: bold;
cursor: pointer;
transition: all 0.2s ease;
min-height: 40px;
}
.combat-return-menu-btn:hover {
transform: scale(1.05);
box-shadow: 0 0 20px ${hexToRgbaString(
KOREAN_COLORS.PRIMARY_CYAN,
0.8
)};
}
`}
</style>
<button
onClick={onReturnToMenu}
onMouseEnter={() => audio.playSFX("menu_hover")}
className="combat-return-menu-btn"
data-testid="return-to-menu-button"
aria-label="Return to main menu"
>
메뉴로 | Return to Menu
</button>
</div>
</div>
{/* Pause Menu Overlay */}
{(isPaused || showPauseMenu) && (
<PauseMenu
onResume={handleResume}
onRestart={handleRestart}
onReturnToMenu={onReturnToMenu}
isMobile={isMobile}
/>
)}
</div>
{/* Round Announcement Overlay */}
{showAnnouncement && roundWinner && (
<RoundAnnouncement
roundNumber={transitionRoundNumber}
roundWinner={roundWinner}
currentScore={matchScore}
roundStats={{
damageDealt: roundWinner.totalDamageDealt ?? 0,
hitsLanded: roundWinner.hitsLanded ?? 0,
vitalPointsHit: roundWinner.vitalPointHits ?? 0,
accuracy: calculateAccuracy(roundWinner),
}}
onCountdownComplete={() => {
// Check if match is over (best of 3)
if (matchScore.player1 >= 2 || matchScore.player2 >= 2) {
const winner = matchScore.player1 >= 2 ? 0 : 1;
onGameEnd(winner);
} else {
// Match continues - trigger transition to next round
skipCountdown();
}
}}
onSkip={() => {
// Check if match is over (best of 3) before skipping
if (matchScore.player1 >= 2 || matchScore.player2 >= 2) {
const winner = matchScore.player1 >= 2 ? 0 : 1;
onGameEnd(winner);
} else {
skipCountdown();
}
}}
isMobile={isMobile}
totalRounds={3}
/>
)}
{/* Match Start Countdown Overlay - only shows once at match start */}
{showMatchCountdown && !hasShownMatchCountdown && (
<MatchCountdown
onComplete={() => {
setHasShownMatchCountdown(true);
setShowMatchCountdown(false);
setMatchCountdownComplete(true);
// Start the first round after countdown
startRound();
}}
isMobile={isMobile}
showSkip={false}
/>
)}
{/* Round Start Announcement for subsequent rounds */}
{/* Note: showRoundStart is only set to true after round 1 ends, so no need for internalRound > 1 check */}
{showRoundStart && (
<RoundStartAnnouncement
roundNumber={internalRound}
duration={2}
onComplete={() => {
if (import.meta.env.DEV) {
console.log(
"[DEV] Round start announcement complete for round",
internalRound
);
}
setShowRoundStart(false);
// Start combat for this round
startRound();
}}
isMobile={isMobile}
/>
)}
</div>
);
};
export default CombatScreen3D;
|