All files / js allmain.js

90.32% Statements 1923/2129
72.91% Branches 428/587
90.69% Functions 39/43
90.32% Lines 1923/2129

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 213073x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 5132x 5132x 71x 71x 71x 71x 5132x 5132x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 33x 33x 33x 2x 2x 2x 2x 33x 73x 73x 73x 73x 73x 73x                 73x 73x 73x 73x 73x 73x 73x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 27193x 27193x 27193x 27193x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 68x 68x 68x 68x 68x 68x 71x 71x 71x 71x 71x 71x 71x 71x 71x 73x 73x 73x 73x 73x 73x                             73x 73x 73x 73x 73x 73x 71x 71x 71x 71x 71x 3x 3x 71x 3x 3x 71x 71x 1x 1x 1x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x       71x 71x 71x 71x 71x 71x 71x 71x 73x 73x 73x 73x 73x 6097x 6097x 6097x 26108x 26079x 26079x 26108x 26108x 6097x 73x 8350x 8350x 8350x 8350x 49687x 49687x 90x 22x 90x 49687x 49597x 49597x 49687x 49687x 8350x 8350x 8350x 8350x 73x 73x 73x 73x 73x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 8284x 6080x 6080x 6080x 6080x 6732x 6732x 6732x 6732x 6732x 6732x 6732x 6732x 6732x 6732x 6732x 6732x 6732x 6732x 6732x 6732x 6732x 8643x 8643x 8635x 8643x 6732x 6732x 6732x 6732x 6732x 6726x 6726x 6726x 6726x 6726x 6726x 6726x 6726x 6732x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 81x 81x 6031x 6031x 6031x 6031x 6031x 6031x 6031x         6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 12x 6031x 6019x 6019x 6019x 6031x 6031x 192x 192x 192x 6031x 6031x 6031x 6031x 6019x                 6019x 6019x 6019x 6019x 6019x 6019x 6019x 6019x 6019x 6019x                   6019x 6019x 6031x 6031x 6031x 6031x 6031x 6031x 287x 287x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 78x 78x 6031x 6031x             6031x 6031x 6031x 6031x 6031x 6031x 6031x 6031x 372x 372x 80x 80x 80x 80x 372x 6031x 6031x 6031x 6031x 6080x 6074x 6074x 6074x 6074x 6074x 6074x 6074x 6080x 210x 210x 6080x 6080x 6080x 6080x 8278x 8278x 8278x 8278x 8278x 8284x 2x 2x 2x 2x 2x 2x 8278x 8278x 8278x 8278x 8278x 8278x 8284x 6056x 6056x 6056x 8278x 8278x 8278x 8278x 8278x 8278x 8278x 8278x 8278x 8284x 1454x 1454x 1454x 1454x 1454x 1454x 8277x 296x 296x 296x 296x 296x 296x 296x 8278x 8278x 8278x 8284x                                                       8278x 8278x 8278x 8278x 8278x 8278x 8278x 8278x 8284x 584x 584x 584x 584x 1x 1x 1x 584x 584x 584x 7694x 7694x 7694x 7694x 7694x 7694x 7694x 8284x 8284x 8284x 8284x 2232x 2232x 2232x 22x 22x 22x 22x 2210x 2204x 2204x 2204x 2204x 2204x 2204x 2204x 2204x 2204x 2204x     2232x 6x 6x 6x 8284x 5132x 5132x 5132x 5132x 5132x 5132x 5132x 5132x 5132x 5068x 8284x 7694x 7694x 7694x 7694x 7694x 7694x 7608x 7608x 8284x 7607x 7607x 7607x 7607x 8284x 7607x 7607x 7607x 7607x 8283x 92x 92x 92x 92x 92x 92x 90x 1890x 149310x 149310x 1890x 92x 2x 2x 2x 2x 42x 3318x 3318x 8x     42x 2x 92x 7607x 7607x 7607x 8283x 603x 603x 8284x 73x 73x 73x 73x 73x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 73x 73x 73x 73x 94x 91x 94x 73x 70x 70x 70x 70x 70x 70x 73x 70x 70x 73x 66x 66x 66x 66x 66x 66x 66x     66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x       66x 66x 66x 66x 66x 66x 13x 13x 66x 66x 66x 66x 66x 66x 66x 66x 66x 1x 1x 66x             66x 66x 66x 66x 66x               66x 66x 66x 66x 66x 66x 66x 73x 73x 73x 73x 73x 6097x 6097x 6097x 6097x 6097x 12x 6097x 6085x 6085x 6085x 115x 115x 6085x 1973x 1973x 1973x 6085x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 73x 73x 73x 73x 73x 73x 73x 73x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 73x 73x 73x 73x 73x 71x 71x 71x 73x 71x 71x 71x 6x 71x 5x 71x 6x 71x 6x 71x 48x 71x 71x 73x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 59x 59x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 68x 68x 68x 68x 68x 68x 68x 73x 68x 68x 68x 68x 68x 12x 12x 68x 41x 41x 68x 15x 15x 68x     68x 68x 68x 73x 68x 68x 68x 68x 68x 56x 15x 68x 68x 68x 73x 68x 68x 68x 68x 68x 68x 68x 68x 68x 73x 73x 73x 73x 68x 68x 68x 68x 68x 68x 68x 68x 68x     68x           68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 1224x 1224x 74124x 74124x 68x 68x 1156x 1156x 1156x 952x 952x 952x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x     68x 68x 71x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 16x 16x 16x 189x 189x 189x 205x 189x 189x 205x 69x   69x 1x 1x 69x 69x 69x 69x 189x 205x 205x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 205x 205x 205x 205x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 189x 189x 189x 174x 174x 189x 10x 10x 189x 205x 189x 189x 189x 189x 189x 205x 37x 37x 37x 37x 37x 37x 37x 37x 69x 69x 69x 69x 69x 37x 37x 37x 37x 37x 37x 37x 37x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 37x 37x 37x 37x 27x 27x 37x 37x 37x 37x 37x 37x 37x 37x 1274x 1274x 1274x 1274x 37x 37x 37x 37x 37x 37x 37x 29x 586x 586x 586x 586x 442x 442x 586x 29x 205x 152x 152x 152x 152x 152x 152x 152x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 205x 189x 189x 205x 2x 2x 2x 2x           2x 2x 2x       205x   187x 23x 23x 23x 23x 22x 22x 22x 22x 22x 22x 1x 1x     1x 1x   1x 1x               23x 23x 23x 14x 1x 14x 5x 5x 5x 4x 4x 4x 4x 4x 5x   5x 5x 5x 5x 5x 5x 14x 187x 164x 164x 164x 205x 189x 189x 189x 189x 189x 189x 189x 205x 205x 205x 189x 15120x 15120x 189x 205x 5548x 5548x 5548x 5548x 5548x 5544x 5544x 5548x 189x 189x 189x 205x 17x 8x 15x 8x 8x 17x 189x 189x 189x 189x 189x 189x 189x 189x 205x 205x 189x 189x 189x 189x 205x 36x 36x 36x 36x 189x 189x 189x 189x 189x 205x 205x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 134x 134x 189x 189x 189x 189x 189x 189x 205x 205x 205x 205x 205x 205x 9x 7x 7x 7x 7x 9x 9x 205x 25x 25x 25x 205x 189x 189x 205x 4x 4x 4x 4x 1x 1x 1x 4x 2x 2x 205x 38x 38x 38x 189x 189x 205x 3x 3x 189x 189x 203x 6x 6x 6x 189x 189x 189x 205x 205x 205x 3x 205x 3x 3x 3x 3x 3x     3x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 205x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 205x 2x 2x 2x 2x 189x 189x 189x 205x 73x 73x 73x 73x 73x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 189x 182x 1x 1x 182x 182x 182x 182x 182x 182x 182x 182x 182x     182x 189x 189x 189x 189x 189x 189x 73x 73x 73x 73x 73x 12982x 12982x 12982x 12982x 12982x 12982x 12982x 12982x 6097x 6097x   7815x 7815x 7815x 154x 154x 154x 154x 154x 1069x 1069x 1069x 151x 154x 73x 6097x 73x 73x 73x 73x 73x 73x 2x 2x 2x 2x 2x 2x 2x 2x                           2x 2x 161x 161x           161x 2x 73x 1x 1x 1x 1x 1x 91x 91x 1x 1x 1x 1x 1x 1x 1x 73x 73x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 73x                                                         73x 73x 3188x 3188x 3188x 3188x 2750x 393x 393x 393x 393x           393x 2750x 3188x 3188x 73x 6097x 6097x 6097x 6097x 73x 73x 7x 7x 7x 7x 7x 7x 7x 7x         7x 73x 73x 73x 73x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 1053x 64x     64x 64x 64x 64x             64x 64x 3x 3x 3x 64x 64x 64x 64x 64x 1053x 870x 870x 870x 870x 870x 870x 160x 160x 160x 160x 160x 870x 1044x 31x 31x 1053x 73x 6097x 6097x 6097x 6097x 412x 6097x 6097x 6097x 6097x 6097x 28x 28x 28x 28x 28x 28x 28x 28x 2x 2x 28x 6097x 73x 73x 73x 73x 73x 71x 71x 71x 71x 17x 17x 54x 54x 54x 54x 68x 68x 68x 68x 68x 68x 68x 14x 14x 68x 68x 68x 68x 54x 54x 54x 54x 54x     71x 73x 73x 73x 73x 71x 71x 71x 71x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 6x 6x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 71x  
// allmain.js — Game loop skeleton (port of allmain.c)
// Critical: phase ordering must match C exactly (see DECISIONS.md #15).
//
// moveloop_core() structure:
//   1. Bookkeeping (flags, bypasses, sanity)
//   2. if (context.move) { monster movement, turn-end, moves++ }
//   3. Display update
//   4. Get player input
//   5. Execute player command (rhack)
//   6. Cleanup (deferred_goto, vision)
//
// Monster turns from the PREVIOUS command execute at the TOP of the
// NEXT iteration, gated by context.move. On the first iteration,
// context.move is false — the player acts first.
 
import { beginCommandExec, endCommandExec, game } from './gstate.js';
 
// Mail daemon — lazy import on first call to avoid breaking if missives_data.js absent.
let _ckmailstatus = undefined; // undefined = not yet loaded, null = unavailable
async function ckmailstatus_wrapper() {
    if (_ckmailstatus === undefined) {
        _ckmailstatus = null; // mark as attempted
        import('./missives.js').then(m => { _ckmailstatus = m.ckmailstatus; }).catch(() => {});
        return; // skip this turn, available next turn
    }
    if (_ckmailstatus) await _ckmailstatus();
}
import { A_CON, A_DEX, A_INT, A_STR, A_WIS, ACH_ASTR, ACH_ENDG, ACH_HELL, COLNO, DISMOUNT_FELL, ENERGY_REGENERATION, EXT_ENCUMBER, FAINTED, FAINTING, FAST, FULL_MOON, INTRINSIC, isok, KILLED_BY, LOW_PM, LR_DOWNTELE, LR_UPTELE, MAGIC_PORTAL, MM_NOWAIT, MOD_ENCUMBER, NEW_MOON, NON_PM, NORMAL_SPEED, NOT_HUNGRY, ROLE_FEMALE, ROLE_GENDMASK, ROLE_MALE, ROOM, ROWNO, RUN_CRAWL, RUN_LEAP, RUN_TPORT, SATIATED, UNENCUMBERED, UTOTYPE_ATSTAIRS, UTOTYPE_FALLING, UTOTYPE_PORTAL, WEAK } from './const.js';
import { rn2, rnd, rn1, c_d, pushRngLogEntry, pushCtxMoveLog, setRnlPlayerAccessor } from './rng.js';
import { isStartupPromptPhase, more, nhgetch, ynFunction } from './input.js';
import { find_level, qstart_level } from './dungeon.js';
import { assertNotInModal, enterModal, exitModal, setMonMovingGetter } from './modal_guard.js';
import {
    create_nhwindow_menu, start_menu, add_menu, add_menu_str,
    end_menu, select_menu, destroy_nhwindow_menu,
} from './menu.js';
import { decl_globals_init } from './decl.js';
import { stairway_add, stairway_at, stairway_find_from, u_on_dnstairs, u_on_newpos, u_on_sstairs, u_on_upstairs } from './stairs.js';
import { near_capacity, encumber_msg, pickup, reset_justpicked } from './pickup.js';
import { init_objects } from './o_init.js';
import { role_init } from './role.js';
import { init_dungeons } from './dungeon.js';
import { init_artifacts } from './artifact.js';
import { u_init, u_init_inventory_attrs, u_init_skills_discoveries } from './u_init.js';
import { mklev, l_nhcore_init, level_finalize_topology, mineralize_kelp } from './mklev.js';
import { tutorial_turn } from './sp_lev.js';
import { movebubbles, place_lregion } from './mkmaze.js';
import { change_luck, check_special_room, end_running, lookaround, losehp, monster_nearby, unmul } from './hack.js';
import { u_wipe_engr } from './engrave.js';
import { tutorial } from './nhlua.js';
import { cansee, vision_reset, vision_recalc } from './vision.js';
import { any_light_source } from './light.js';
import { level_difficulty, makedog, makemon } from './makemon.js';
import { domove, dosearch0, nomul, rhack } from './cmd.js';
import { clear_bypasses } from './worn.js';
import { Norep, maybe_lvltport_feedback, temperature_change_msg, u_collide_m } from './do.js';
import {
    keepdogs as keepdogs_impl,
    losedogs as losedogs_impl,
    mon_catchup_elapsed_time,
    set_malign,
} from './dog.js';
import { m_at } from './map_access.js';
import { ok_to_quest, onquest } from './quest.js';
import { com_pager as quest_com_pager, deliver_splev_message } from './questpgr.js';
import { emitTurnMapstate } from './mapstate.js';
import { gethungry as gethungry_impl, reset_eat } from './eat.js';
import { seetrap, selftouch } from './trap.js';
import { ballrelease, drag_down } from './ball.js';
import { welded } from './wield.js';
import { dismount_steed } from './steed.js';
import {
    movemon,
    mcalcmove,
    mcalcdistress,
    hide_monst,
    initrack,
    m_next2u,
    settrack,
    stop_occupation,
} from './mon.js';
import { m_everyturn_effect } from './monmove.js';
import { bot, cls, curs_on_u, delay_output, display_nhwindow, docrt, docrt_cls, find_ac, flush_glyph_buf, flush_screen, newsym, render_screen_output_to_display, setBotl, setBotlx, setTimeBotl, status_initialize, timebot, tty_clear_nhwindow, tty_display_nhwindow, tty_dismiss_nhwindow, tty_destroy_nhwindow, tty_create_nhwindow, erase_menu_or_text, docorner, NHW_MENU } from './display.js';
import { reglyph_darkroom } from './drawing.js';
import { phase_of_the_moon, friday_13th, time_from_yyyymmddhhmmss } from './calendar.js';
import { ACURR, exerchk, exercise } from './attrib.js';
import { NO_COLOR } from './terminal.js';
import {
    mons, NUMMONS, G_NOCORPSE,
    PM_KNIGHT, PM_ROGUE, PM_SAMURAI, PM_TOURIST, PM_VALKYRIE, PM_WIZARD, PM_WIZARD_OF_YENDOR,
} from './monsters.js';
import { S_room } from './symbols.js';
import { cmap_to_glyph as _cmap_to_glyph_am } from './glyph.js';
import { pline, putmsghistory, urgent_pline, verbalize, You, You_feel, You_hear } from './pline.js';
import { align_gname } from './pray.js';
import { Blind, Breathless, Deaf, Fumbling, Half_physical_damage, Maybe_Half_Phys, Polymorph, Punished, Role_if, Teleportation, Upolyd, Unchanging, In_endgame, Is_waterlevel, Is_airlevel, Very_fast, Fast } from './macros.js';
import { nh_timeout, do_storms, fall_asleep, run_timers } from './timeout.js';
import { dosounds } from './sounds.js';
import { tele } from './teleport.js';
import { next_to_u, check_leash } from './apply.js';
import { polyself } from './polyself.js';
import { you_were } from './were.js';
import { night } from './calendar.js';
import { run_regions } from './region.js';
import { set_wear } from './do_wear.js';
import { GameMap } from './game.js';
import { invault } from './vault.js';
import { on_level } from './hacklib.js';
import { more_experienced, newexplevel } from './exper.js';
import { makewish } from './zap.js';
import { record_achievement } from './insight.js';
import { age_spells } from './spell.js';
import { place_object } from './mkobj.js';
import { initObjectData } from './objects.js';
 
const TOPLINE_NEED_MORE = 1;
 
// C ref: allmain.c:1025 interrupt_multi(msg)
async function interrupt_multi(msg) {
    const g = game;
    if ((g.multi || 0) > 0 && !g.context?.travel && !g.context?.run) {
        nomul(0);
        if (g.flags?.verbose && msg)
            await Norep('%s', msg);
    }
}
 
// ---------------------------------------------------------------------------
// early_init — C ref: allmain.c early_init()
// Called once at program startup, before anything else.
// ---------------------------------------------------------------------------
export async function early_init() {
    // decl_globals_init() — initialize global declaration state
    await decl_globals_init();
    // C ref: objects.c objects_globals_init() — compute bases[], oclass_prob_totals[]
    initObjectData();
    // monst_globals_init() — monster class globals
    // sys_early_init() — system-specific early init
    // runtime_info_init() — runtime info
}
 
// ---------------------------------------------------------------------------
// newgame — C ref: allmain.c newgame()
// Full new game initialization: objects, role, dungeons, artifacts,
// character, level generation, initial placement, welcome message.
// ---------------------------------------------------------------------------
export async function newgame() {
    const g = game;
 
    // notice_mon_off() — suppress monster notices during setup
    setBotlx('newgame');
    g.context.ident = 2;       // id 1 reserved for youmonst
    g.context.warnlevel = 1;
    g.context.next_attrib_check = 600;
    g.context.tribute = { enabled: true };
 
    // Initialize mvitals for all monsters.
    if (!Array.isArray(g.mvitals))
        g.mvitals = [];
    for (let i = LOW_PM; i < NUMMONS; i++) {
        if (!g.mvitals[i])
            g.mvitals[i] = { mvflags: 0 };
        g.mvitals[i].mvflags = mons[i]?.geno & G_NOCORPSE;
    }
 
    // C ref: allmain.c newgame() — exact call order matching C
    await init_objects();      // must be before u_init()
 
    g.flags.pantheon = -1;
    await role_init();         // must be before init_dungeons(), u_init()
 
    await init_dungeons();     // must be before u_init()
    await init_artifacts();    // before u_init()
    await u_init();            // u_init_misc: handedness, HP, energy
 
    l_nhcore_init();           // create Lua state (nhlib.lua shuffle)
    // reset_glyphmap(gm_newgame)
 
    // C ref: newgame → cls() → clear_nhwindow(WIN_MAP)
    // MAP falls through to term_clear_screen → erase_tty_screen
    // which clears STATUS and MAP again (3 total ^botlx[tty_clear_nhwindow])
    await tty_clear_nhwindow('map');
    // C ref: float_vs_flight() — check flight/levitation state (before mklev)
    setBotl('float_vs_flight');
    // C ref: status_initialize() — 2nd call from new_status_window
    status_initialize();
 
    await mklev();             // generate first level
    await u_on_upstairs();     // place player on stairs
    vision_reset();            // C: newgame() resets vision internals here
    // C newgame() does not call vision_recalc() before makedog(); keep the
    // recalc deferred to moveloop/docrt-driven paths via this flag.
    g.vision_full_recalc = 1;
    // check_special_room — now called inside goto_level (line ~1514)
 
    // if (MON_AT(u.ux, u.uy)) mnexto(...)
    await makedog();           // create starting pet
 
    await u_init_inventory_attrs(); // starting inventory — AFTER mklev
 
    // C ref: docrt_flags → cls → clear_nhwindow(WIN_MAP)
    // cls() internally calls tty_display_nhwindow('message', false) matching
    // C's cls() → display_nhwindow(WIN_MESSAGE, FALSE) at display.c:2238.
    await cls();
 
    // C ref: newgame() does docrt(); flush_screen(1); bot();
    // docrt() internally calls cls() which clears all windows.
    await docrt();
    await flush_screen();
    await bot();
    // while (u.uroleplay.reroll && reroll_menu()) { ... }
 
    await u_init_skills_discoveries();
 
    if (g.flags.legacy) {
        await com_pager(g.u.uroleplay.pauper ? 'pauper_legacy' : 'legacy');
        // C ref: questpgr.c:607-608 — synopsis goes into message history
        // for ^P recall. C: putmsghistory("[deity has chosen you...]", FALSE)
        const deityName = align_gname(g.u.ualignbase?.[0] ?? g.u.ualign?.type ?? 0);
        putmsghistory(`[${deityName} has chosen you to recover the Amulet of Yendor for Him.]`);
    }
 
    g.urealtime.realtime = 0;
    g.urealtime.start_timing = g.getnow();
 
    g.program_state.something_worth_saving++;
 
    await welcome(true);
    notice_mon_on();
}
 
// ---------------------------------------------------------------------------
// moveloop — C ref: allmain.c moveloop()
// Entry point: runs preamble, then loops moveloop_core() forever.
// ---------------------------------------------------------------------------
export async function moveloop(resuming) {
    await moveloop_preamble(resuming);

    if (!resuming) {
        await maybe_do_tutorial();
    }

    for (;;) {
        await moveloop_core();
        // C ref: C's done() calls exit() which terminates immediately.
        // JS's done() sets gameover=1 and returns; check here to stop.
        if (game.program_state?.gameover || game.program_state?.exiting)
            break;
    }
}
 
// ---------------------------------------------------------------------------
// moveloop_preamble — C ref: allmain.c moveloop_preamble()
// Side-effects from the real world, initial setup before loop starts.
// ---------------------------------------------------------------------------
export async function moveloop_preamble(resuming) {
    const g = game;
 
    // Moon phase and Friday 13th affect luck
    g.flags.moonphase = phase_of_the_moon();
    if (g.flags.moonphase === FULL_MOON) {
        await You("are lucky!  Full moon tonight.");
        change_luck(1);
    } else if (g.flags.moonphase === NEW_MOON) {
        await pline("Be careful!  New moon tonight.");
    }
    g.flags.friday13 = friday_13th();
    if (g.flags.friday13) {
        await pline("Watch out!  Bad things can happen on Friday the 13th.");
        change_luck(-1);
    }
 
    if (!resuming) {
        g.program_state.beyond_savefile_load = 1;
        // Wire rnl() to read Luck from game state (uluck + moreluck)
        setRnlPlayerAccessor(() => g.u);
        g.context.rndencode = rnd(9000);
        // C ref: allmain.c:76 — apply side-effects of starting gear
        await set_wear(null);
        reset_justpicked(game.invent);
        // pickup(1) — autopickup at initial location — TODO
        g.context.seer_turn = rnd(30);
        g.u.umovement = NORMAL_SPEED;
        initrack();
    }
 
    setBotlx('moveloop_preamble');
 
    if (resuming) {
        // read_engr_at(u.ux, u.uy)
        // fix_shop_damage()
    }
 
    // encumber_msg()
    g.u.uz0 = { ...g.u.uz };
    pushCtxMoveLog('moveloop_preamble', g.context.move);
    g.context.move = 0;
 
    g.program_state.in_moveloop = 1;
}
 
// ---------------------------------------------------------------------------
// moveloop_core — C ref: allmain.c moveloop_core()
// C ref: allmain.c — reallocate movement to all monsters on the level.
// Single site for ^mcalcmove event (one-event-one-place).
function reallocate_monster_movement() {
    const g = game;
    for (let mtmp = g.fmon; mtmp; mtmp = mtmp.nmon) {
        if (mtmp.dead) continue;
        const oldMv = mtmp.movement;
        mtmp.movement += mcalcmove(mtmp, true);
        pushRngLogEntry(`^mcalcmove[${mtmp.mnum}@${mtmp.mx},${mtmp.my} speed=${mtmp.data?.mmove ?? 0} mv=${oldMv}->${mtmp.movement}]`);
    }
}
 
function dmonsfree() {
    const g = game;
    let prev = null;
    for (let m = g.fmon; m; ) {
        const next = m.nmon || null;
        if (m.dead && !m.isgd) {
            if (prev) prev.nmon = next;
            else g.fmon = next;
            m.nmon = null;
        } else {
            prev = m;
        }
        m = next;
    }
    if (Array.isArray(g.level?.monsters)) {
        g.level.monsters = g.level.monsters.filter(m => m && (!m.dead || m.isgd));
    }
}
 
// One tick of the game loop. THIS IS THE CRITICAL FUNCTION.
// Phase ordering must match C exactly.
// ---------------------------------------------------------------------------
export async function moveloop_core() {
    const g = game;
    setMonMovingGetter(() => g.context?.mon_moving);
    let monscanmove = false;
    const display = game?.nhDisplay || null;
    let commandToken = null;
 
    g.displayEpoch = (g.displayEpoch ?? 0) + 1;
 
    assertNotInModal('moveloop_core');
 
    // --- Bookkeeping ---
    // get_nh_event()
    // dobjsfree() — includes dmonsfree()
    dmonsfree();
    if (g.context.bypasses)
        clear_bypasses();
 
    // --- Monster movement (gated by context.move) ---
    if (g.context.move) {
        // actual time passed
        g.u.umovement -= NORMAL_SPEED;
 
        do {
            // C ref: allmain.c:261 — encumber_msg at top of hero-can't-move loop
            await encumber_msg();
 
            g.context.mon_moving = true;
            // C ref: allmain.c:251 — record hero HP before monsters act.
            // saving_grace() uses this to prevent one-shot death when HP
            // was >= 90% of max at the start of the monster turn.
            g.uhp_at_start_of_monster_turn = g.u.uhp;
            g._monmove_since_capture = true;
            // Monster turns may need input (e.g. shopkeeper zaps wand →
            // pline → more → nhgetch). Wrap in command exec context so
            // nhgetch's assertLegalInputOwner sees a valid token.
            // In C, wgetch blocks with no special context needed.
            {
                const monToken = beginCommandExec(g, { site: 'movemon' });
                try {
                    do {
                        monscanmove = await movemon();
                        if (g.program_state?.gameover) break;
                        if (g.u.umovement >= NORMAL_SPEED)
                            break; // it's now your turn
                    } while (monscanmove);
                } finally {
                    endCommandExec(g, monToken);
                }
            }
            // C ref: allmain.c:257 — mon_moving is cleared here, before
            // near_capacity and mcalcdistress.  Leaving it true through
            // mcalcdistress causes set_apparxy inside newcham to fire
            // on shapeshifters where C's control flow excludes it (see
            // seed0800 vampire-bat mux/muy regression, issue #400).
            g.context.mon_moving = false;
 
            let wtcap = near_capacity();
            if (!monscanmove && g.u.umovement < NORMAL_SPEED) {
                // Both hero and monsters are out of steam
                // mcalcdistress() — adjust monster trap/blind/etc
                await mcalcdistress();
 
                // Reallocate movement to monsters — use fmon chain (newest first)
                reallocate_monster_movement();
 
                // Random monster spawn
                const spawn_threshold = g.u.uevent.udemigod ? 25
                    : (depth_uz() > depth_stronghold()) ? 50 : 70;
                if (!rn2(spawn_threshold)) {
                    await makemon(null, 0, 0, 0);
                }
 
                // Hero movement recalculation
                u_calc_moveamt(wtcap);
                settrack();
 
                g.moves++;
                if (g.moves >= 1000000000) {
                    // display_nhwindow(WIN_MESSAGE, true)
                    // urgent_pline("The dungeon capitulates.")
                    // done(ESCAPED)
                }
                g.hero_seq = g.moves << 3;
 
                if (g.flags.time && !g.context.run)
                    setTimeBotl('moveloop_core');
 
                // --- Once-per-turn effects ---
                // Order must match C allmain.c exactly:
                // 1. timed effects + regions
                await nh_timeout();
                await run_regions();
                // 2. bless countdown
                if (g.u.ublesscnt) g.u.ublesscnt--;
                // C ref: allmain.c:330 — reset saving_grace flag each turn.
                g.saving_grace_turn = false;
                // 3. HP/PW regeneration (BEFORE dosounds/gethungry!)
                // C ref: allmain.c:340-347
                if (g.u.uinvulnerable) {
                    wtcap = UNENCUMBERED;
                } else if (!Upolyd() ? (g.u.uhp < g.u.uhpmax)
                              : (g.u.mh < g.u.mhmax
                                 || g.youmonst?.data?.mlet === 57 /*S_EEL*/))
                    await regen_hp(wtcap);
                // C ref: allmain.c:297-301 — moving while encumbered is hard work.
                if (wtcap > MOD_ENCUMBER && g.u.umoved) {
                    if (!((wtcap < EXT_ENCUMBER) ? (g.moves % 30) : (g.moves % 10)))
                        await overexert_hp();
                }
                await regen_pw(wtcap);
                // 4. Teleportation, polymorph checks
                // C ref: allmain.c:360-392
                if (!g.u.uinvulnerable) {
                    if (Teleportation() && !rn2(85)) {
                        const old_ux = g.u.ux, old_uy = g.u.uy;
                        await tele();
                        if (g.u.ux !== old_ux || g.u.uy !== old_uy) {
                            if (!(await next_to_u())) {
                                await check_leash(old_ux, old_uy);
                            }
                        }
                    }
                    let mvl_change = g._mvl_change || 0;
                    if ((mvl_change === 1 && !Polymorph())
                        || (mvl_change === 2 && (g.u.ulycn ?? NON_PM) === NON_PM))
                        mvl_change = 0;
                    if (Polymorph() && !rn2(100))
                        mvl_change = 1;
                    else if ((g.u.ulycn ?? NON_PM) !== NON_PM && !Upolyd()
                             && !rn2(80 - (20 * night())))
                        mvl_change = 2;
                    if (mvl_change && !Unchanging()) {
                        if (g.multi >= 0) {
                            await stop_occupation();
                            if (mvl_change === 1)
                                await polyself(0);
                            else
                                await you_were();
                            mvl_change = 0;
                        }
                    }
                    g._mvl_change = mvl_change;
                }
                // 5. auto-search (C: allmain.c:342, between regen and dosounds)
                {
                    const SEARCHING = 34;
                    if (g.u.uprops?.[SEARCHING]?.intrinsic
                        && !g.level?.flags?.noautosearch
                        && g.multi >= 0) {
                        await dosearch0(1, true);
                    }
                }
                // 6. dosounds, do_storms, gethungry
                await dosounds();
                await do_storms();
                await gethungry();
                // 7. spell aging, exercise, vault, amulet
                age_spells();
                await exerchk();
                await invault();
                if (g.u.uhave?.amulet) await amulet();
                // 8. engrave wiping
                if (!rn2(40 + current_dex() * 3)) {
                    u_wipe_engr(rnd(3));
                }
                // C ref: allmain.c:362-367 — Wizard interventions after amulet.
                if (g.u.uevent?.udemigod && !g.u.uinvulnerable) {
                    if (g.u.udg_cnt) g.u.udg_cnt--;
                    if (!g.u.udg_cnt) {
                        await intervene();
                        g.u.udg_cnt = rn1(200, 50);
                    }
                }
 
                // C ref: allmain.c:417-420 — bubble/fumarole processing
                if (Is_waterlevel(g.u?.uz) || Is_airlevel(g.u?.uz))
                    await movebubbles();
                // else if (g.level?.flags?.fumaroles) fumaroles(); // TODO: port fumaroles
 
                // C ref: allmain.c — immobility countdown runs during turn-end.
                if (g.multi < 0) {
                    await runmode_delay_output();
                    if (++g.multi === 0) {
                        await unmul(null);
                        if (g.u.utotype)
                            await deferred_goto();
                    }
                }
 
                // Optional per-turn compact state hash for parity diagnostics.
                emitTurnMapstate(g, pushRngLogEntry, 'turn_end');
            }
        } while (g.u.umovement < NORMAL_SPEED);
        g.context.mon_moving = false;
 
        // --- Once-per-hero-took-time ---
        g.hero_seq++;
        // C ref: allmain.c:471 — encumber_msg after hero acts
        await encumber_msg();
        // clairvoyance check
        if (g.moves >= g.context.seer_turn) {
            g.context.seer_turn = g.moves + rn1(31, 15);
        }
        // sink_into_lava, pooleffects
        // see_nearby_monsters()
        // (auto-search moved to turn-end block above to match C ordering)
    }
 
    // --- Once-per-player-input ---
    // clear_splitobjs()
 
    // C ref: allmain.c:515-521 — Amulet of Yendor grants a wish on first pickup
    if (g.u.uhave?.amulet && !g.u.uevent?.amulet_wish) {
        if (!g.u.uevent) g.u.uevent = {};
        g.u.uevent.amulet_wish = 1;
        await display_nhwindow('message', true);
        await urgent_pline('The Amulet is bestowing a wish upon you!');
        await makewish();
    }
 
    find_ac();
    // C ref: allmain.c:523-529 — while buried/underwater or otherwise not
    // in normal movement view mode, perform deferred vision recalc here.
    // This pre-command recalc is distinct from the post-rhack recalc at the
    // end of moveloop_core and is required for occupation turns.
    if (!g.context.mv || Blind()) {
        if (g.vision_full_recalc)
            vision_recalc();
    }
 
    // C ref: allmain.c:530-536 — direct conditional bot + curs_on_u.
    // bot/timebot is called directly (not via flush_screen) so midlog
    // annotations show "@ moveloop_core" not "@ flush_screen".
    // After bot/timebot, C calls curs_on_u() → flush_screen(1) which
    // paints gnew entries and positions cursor at hero. JS uses
    // flush_glyph_buf + setCursor to match without double-emitting bot.
    // When NEITHER bot nor timebot runs, C does NOT flush gnew or set
    // cursor — gnew stays pending until the next pline → flush_screen.
    if (g.disp.botl || g.disp.botlx) {
        await bot();
        flush_glyph_buf();
        if (g.u?.ux) {
            const d = game?.nhDisplay;
            if (d) d.setCursor(g.u.ux - 1, g.u.uy + 1);
        }
    } else if (g.disp.time_botl) {
        await timebot();
        flush_glyph_buf();
        if (g.u?.ux) {
            const d = game?.nhDisplay;
            if (d) d.setCursor(g.u.ux - 1, g.u.uy + 1);
        }
    }
 
    // C-shaped input ownership: while getpos/farlook is active, subsequent
    // keys belong to that prompt family, not to a fresh moveloop/parse start.
    if (g.iflags?.getloc_travelmode || g.iflags?.getloc_tip_active) {
        // C ref: getpos positions cursor at targeting location, not hero.
        // Use travelcc (or hero if no target) matching C's dotravel → getpos.
        {
            const tc = g.iflags?.travelcc;
            const tx = (tc?.x > 0) ? tc.x : (g.u?.ux ?? 1);
            const ty = (tc?.y > 0) ? tc.y : (g.u?.uy ?? 0);
            const d = game?.nhDisplay;
            if (d) d.setCursor(tx - 1, ty + 1);
        }
        g.u.umoved = false;
        commandToken = beginCommandExec(g, {
            site: 'moveloop_core',
            multi: g.multi,
            move: g.context?.move ?? null,
        });
        try {
            await rhack(0);
        } finally {
            endCommandExec(g, commandToken, {
                site: 'moveloop_core',
                multi: g.multi,
                move: g.context?.move ?? null,
            });
        }
        vision_recalc();
        return;
    }
 
    // C ref: allmain.c:538 — hero fog cloud gas creation, etc.
    await m_everyturn_effect(g.youmonst);
 
    g.context.move = 1;
    pushCtxMoveLog('moveloop_core', g.context.move);
 
    // --- Occupation handling ---
    if (g.multi >= 0 && g.occupation) {
        if ((await g.occupation()) === 0)
            g.occupation = null;
        // C ref: allmain.c:576-579 — monster_nearby() interrupts occupation
        if (monster_nearby()) {
            await stop_occupation();
            reset_eat();
        }
        await runmode_delay_output();
        return;
    }
 
    g.u.umoved = false;
 
    // --- Multi-turn command handling ---
    commandToken = beginCommandExec(g, {
        site: 'moveloop_core',
        multi: g.multi,
        move: g.context?.move ?? null,
    });
    try {
        if (g.multi > 0) {
            await lookaround();
            await runmode_delay_output();
            if (!g.multi) {
                g.context.move = 0;
                pushCtxMoveLog('moveloop_core', g.context.move);
                return;
            }
            if (g.context.mv) {
                if (g.multi < 80 && !--g.multi)
                    end_running(true);
                await domove();
                // C: flush_screen(1) after domove updates the terminal so
                // the player sees the hero moving step by step during runs.
                // In JS, show_glyph_cell → setCell already updated the DOM,
                // but the browser won't repaint until we yield. A setTimeout(0)
                // yields one event loop turn for the browser to paint.
                // Only in browser mode — headless tests don't need this.
                if (display?.container) {
                    await new Promise(r => setTimeout(r, 0));
                }
            } else {
                --g.multi;
                await rhack(g.cmd_key);
            }
        } else if (g.multi === 0) {
            // C ref: allmain.c:535-537 — check for mail delivery
            await ckmailstatus_wrapper();
            // C ref: flush_screen(1) before rhack positions cursor at hero.
            // Mail delivery above may have moved cursor to message end.
            if (g.u?.ux) {
                const d = game?.nhDisplay;
                if (d) d.setCursor(g.u.ux - 1, g.u.uy + 1);
            }
            await rhack(0);
        }
    } finally {
        endCommandExec(g, commandToken, {
            site: 'moveloop_core',
            multi: g.multi,
            move: g.context?.move ?? null,
        });
    }
 
    // C ref: done() → exit() in C halts immediately. In JS, check here.
    if (g.program_state?.gameover) return;
 
    // C ref: allmain.c moveloop_core() — deferred_goto() is called
    // after rhack()/domove command handling, before vision_recalc().
    if (g.u.utotype)
        await deferred_goto();
 
    // C ref: allmain.c:543 — recompute vision only when flagged.
    // C sets vision_full_recalc in domove (hero movement), light sources,
    // polyself, goto_level, etc. JS may be missing some of these.
    if (g.vision_full_recalc) {
        vision_recalc();
        // C vision_recalc(0) drives visibility redraws itself. JS keeps
        // vision_recalc lighter, so refresh map cells here for non-move
        // turns (for example, pit escape) where finishHeroMove() did not run.
        const forceDarkroomRefresh = !!(g.flags?.dark_room && g.iflags?.wc_color !== false);
        if (!g.u.umoved) {
            for (let y = 0; y < ROWNO; y++) {
                for (let x = 1; x < COLNO; x++) {
                    newsym(x, y);
                }
            }
        } else if (forceDarkroomRefresh) {
            // Keep non-visible room memory in sync with C's dark-room rendering.
            // Some cells can stay stale S_room until touched by a later redraw;
            // refresh only those unseen room cells that are still lit-room glyphs.
            for (let y = 0; y < ROWNO; y++) {
                for (let x = 1; x < COLNO; x++) {
                    const loc = g.level?.at(x, y);
                    if (!loc || loc.typ !== ROOM || loc.glyph !== _cmap_to_glyph_am(S_room)) continue;
                    if (cansee(x, y)) continue;
                    newsym(x, y);
                }
            }
        }
    }
 
    // C ref: allmain.c:560-565 — NHCB_END_TURN callback runner.
    // Tutorial uses this to inject guidance/events (for example, hunger help).
    if (in_tutorial(g.u.uz)) {
        await tutorial_turn();
    }
}
 
// C's NOMUX recorder captures the monster turn AFTER the last hero action.
// This function runs just the monster movement + turn-end effects without
// attempting to read hero input. Used by playTurns after all keys.
export async function moveloop_core_monsters_only() {
    const g = game;
 
    if (g.u.utotype)
        await deferred_goto();
 
    dmonsfree();
 
    if (g.context.move) {
        g.u.umovement -= NORMAL_SPEED;
 
        do {
            g.context.mon_moving = true;
            g.uhp_at_start_of_monster_turn = g.u.uhp;
            let monscanmove;
            do {
                monscanmove = await movemon();
                if (g.u.umovement >= NORMAL_SPEED)
                    break;
            } while (monscanmove);
            g.context.mon_moving = false;
 
            // C ref: mon.c:1314 — after all monsters move, if any light
            // source exists, schedule vision recalc (a monster carrying a
            // lamp may have moved, changing what the hero can see).
            if (any_light_source())
                g.vision_full_recalc = 1;
 
            let wtcap = near_capacity();
            if (!monscanmove && g.u.umovement < NORMAL_SPEED) {
                await mcalcdistress();
 
                reallocate_monster_movement();
 
                const spawn_threshold = g.u.uevent.udemigod ? 25
                    : (depth_uz() > depth_stronghold()) ? 50 : 70;
                if (!rn2(spawn_threshold)) {
                    await makemon(null, 0, 0, 0);
                }
 
                u_calc_moveamt(wtcap);
                settrack();
 
                g.moves++;
                g.hero_seq = g.moves << 3;
 
                if (g.flags.time && !g.context.run)
                    setTimeBotl('moveloop_core');
 
                await nh_timeout();
                await run_regions();
                if (g.u.ublesscnt) g.u.ublesscnt--;
                g.saving_grace_turn = false;
                // C ref: allmain.c:356 — outer gate: skip regen if HP full
                if (!Upolyd() ? (g.u.uhp < g.u.uhpmax)
                              : (g.u.mh < g.u.mhmax))
                    await regen_hp(wtcap);
                // C ref: allmain.c:297-301 — moving while encumbered is hard work.
                if (wtcap > MOD_ENCUMBER && g.u.umoved) {
                    if (!((wtcap < EXT_ENCUMBER) ? (g.moves % 30) : (g.moves % 10)))
                        await overexert_hp();
                }
                await regen_pw(wtcap);
                {
                    const SEARCHING = 34;
                    if (g.u.uprops?.[SEARCHING]?.intrinsic
                        && !g.level?.flags?.noautosearch
                        && g.multi >= 0) {
                        await dosearch0(1, true);
                    }
                }
                await dosounds();
                await do_storms();
                await gethungry();
                age_spells();
                await exerchk();
                await invault();
                if (g.u.uhave?.amulet) await amulet();
                if (!rn2(40 + current_dex() * 3)) {
                    u_wipe_engr(rnd(3));
                }
                if (g.u.uevent?.udemigod && !g.u.uinvulnerable) {
                    if (g.u.udg_cnt) g.u.udg_cnt--;
                    if (!g.u.udg_cnt) {
                        await intervene();
                        g.u.udg_cnt = rn1(200, 50);
                    }
                }
                // C ref: allmain.c:417-420 — bubble/fumarole processing
                if (Is_waterlevel(g.u?.uz) || Is_airlevel(g.u?.uz))
                    await movebubbles();
 
                if (g.multi < 0) {
                    await runmode_delay_output();
                    if (++g.multi === 0) {
                        await unmul(null);
                        if (g.u.utotype)
                            await deferred_goto();
                    }
                }
 
                // Optional per-turn compact state hash for parity diagnostics.
                emitTurnMapstate(g, pushRngLogEntry, 'turn_end');
            }
        } while (g.u.umovement < NORMAL_SPEED);
    }
}
 
// ---------------------------------------------------------------------------
// u_calc_moveamt — C ref: allmain.c u_calc_moveamt()
// Calculate hero movement amount based on speed and encumbrance.
// ---------------------------------------------------------------------------
function u_calc_moveamt(wtcap) {
    const g = game;
    let moveamt = 0;
 
    if (g.u.usteed && g.u.umoved) {
        moveamt = mcalcmove(g.u.usteed, true);
    } else {
        moveamt = g.youmonst?.data?.mmove ?? NORMAL_SPEED;
 
        if (Very_fast()) {
            if (rn2(3) !== 0)
                moveamt += NORMAL_SPEED;
        } else if (Fast()) {
            if (rn2(3) === 0)
                moveamt += NORMAL_SPEED;
        }
    }
 
    switch (wtcap) {
    case 0: /* UNENCUMBERED */ break;
    case 1: /* SLT_ENCUMBER */ moveamt -= Math.trunc(moveamt / 4); break;
    case 2: /* MOD_ENCUMBER */ moveamt -= Math.trunc(moveamt / 2); break;
    case 3: /* HVY_ENCUMBER */ moveamt -= Math.trunc(moveamt * 3 / 4); break;
    case 4: /* EXT_ENCUMBER */ moveamt -= Math.trunc(moveamt * 7 / 8); break;
    }
 
    g.u.umovement += moveamt;
    if (g.u.umovement < 0) g.u.umovement = 0;
    // Per-step umov tracing so cross-engine divergences are visible in the
    // event stream.  Emits base (mmove), fast-roll bump, encumbrance drop,
    // final delta.  Parity with C's u_calc_moveamt instrumentation.
    pushRngLogEntry(`^u_calc_moveamt[base=${(g.youmonst?.data?.mmove ?? NORMAL_SPEED)} wtcap=${wtcap} moveamt=${moveamt} umv=${g.u.umovement}]`);
}
 
// Initialization functions imported from decl.js, o_init.js, role.js,
// dungeon.js, artifact.js, u_init.js
 
// u_on_upstairs imported from stairs.js (uses stairway_find_dir)
 
// NOTE: differs from canonical stairs.js — uses isok() guard instead of !game.u,
// and optional-chaining for uz/uz0 level-change check vs explicit null checks.
async function u_on_rndspot(upflag) {
    const g = game;
    const up = (upflag & 1) !== 0;
    const area = up ? (g.updest || {}) : (g.dndest || {});
    // C ref: dungeon.c await u_on_rndspot()
    // Uses place_lregion() so default-zero regions still consume RNG and
    // resolve through bad_location/exclusion checks like C.
    await place_lregion(
        area.lx || 0, area.ly || 0, area.hx || 0, area.hy || 0,
        area.nlx || 0, area.nly || 0, area.nhx || 0, area.nhy || 0,
        up ? LR_UPTELE : LR_DOWNTELE,
        null
    );
}
// makedog imported from makemon.js
 
// keepdogs and losedogs imported from dog.js (keepdogs_impl, losedogs_impl)
 
// docrt, bot, timebot imported from display.js
function alignAdj(alignVal) {
    return alignVal < 0 ? 'chaotic' : alignVal > 0 ? 'lawful' : 'neutral';
}
 
function Hello() {
    switch (game.urole?.mnum) {
    case PM_KNIGHT:
        return 'Salutations';
    case PM_SAMURAI:
        return 'Konnichi wa';
    case PM_TOURIST:
        return 'Aloha';
    case PM_VALKYRIE:
        return 'Velkommen';
    default:
        return 'Hello';
    }
}
 
async function welcome(newGame) {
    const display = game?.nhDisplay || null;
    const g = game;
    if (!display || (!g.promptedStartup && !isStartupPromptPhase())) return;
    const currentgend = g.flags.female ? 1 : 0;
    let desc = '';
    if (newGame) {
        desc += ` ${alignAdj(g.u.ualignbase?.[0] ?? 0)}`;
    }
    const roleHasDistinctFemale = !!g.urole?.name?.f;
    const roleAllowsBothGenders =
        ((g.urole?.allow || 0) & ROLE_GENDMASK) === (ROLE_MALE | ROLE_FEMALE);
    if (!roleHasDistinctFemale && newGame && roleAllowsBothGenders) {
        desc += currentgend ? ' female' : ' male';
    }
    const roleName = (currentgend && g.urole?.name?.f) ? g.urole.name.f : g.urole?.name?.m;
    desc += ` ${g.urace?.adj || 'human'} ${roleName || 'Adventurer'}`;
    // C ref: allmain.c welcome() just calls pline — no docrt. The screen
    // is already rendered by newgame's docrt() + flush_screen() + bot().
    await pline(`${Hello()} ${g.plname}, welcome to NetHack!  You are a${desc}.`);
 
    // C ref: allmain.c:898 — livelog_printf(LL_ACHIEVE, "%s entered the dungeon")
    // Populates gg.gamelog for the chronicle (v command / show_gamelog).
    if (!g.gamelog) g.gamelog = [];
    {
        const aAdj = g.flags?.initalign === 0 ? 'lawful'
            : g.flags?.initalign === 1 ? 'neutral' : 'chaotic';
        const gAdj = g.flags?.female ? 'female' : 'male';
        const rAdj = g.urace?.adj || 'human';
        const rName = roleName || 'Adventurer';
        g.gamelog.push({
            turn: g.moves || 1,
            text: `${g.plname} the ${aAdj} ${gAdj} ${rAdj} ${rName} entered the dungeon`,
        });
    }
}
 
const STARTUP_PAGER_TEXT = {
    legacy: `It is written in the Book of %d:
 
    After the Creation, the cruel god Moloch rebelled
    against the authority of Marduk the Creator.
    Moloch stole from Marduk the most powerful of all
    the artifacts of the gods, the Amulet of Yendor,
    and he hid it in the dark cavities of Gehennom, the
    Under World, where he now lurks, and bides his time.
 
Your %G %d seeks to possess the Amulet, and with it
to gain deserved ascendance over the other gods.
 
You, a newly trained %r, have been heralded
from birth as the instrument of %d.  You are destined
to recover the Amulet for your deity, or die in the
attempt.  Your hour of destiny has come.  For the sake
of us all:  Go bravely with %d!`,
    pauper_legacy: `It is written in the Book of %d:
 
    After the Creation, the cruel god Moloch rebelled
    against the authority of Marduk the Creator.
    Moloch stole from Marduk the most powerful of all
    the artifacts of the gods, the Amulet of Yendor,
    and he hid it in the dark cavities of Gehennom, the
    Under World, where he now lurks, and bides his time.
 
Your %G %d seeks to possess the Amulet, and with it
to gain deserved ascendance over the other gods.
 
You, an untrained %r, have been unable to adequately
prepare to be the instrument of %d.  Nevertheless, you
are destined to recover the Amulet for your deity, or die
in the attempt.  Your hour of destiny has come.  For the
sake of us all:  Go bravely with %d!`,
};
 
function questRankTitle() {
    const g = game;
    const role = g.urole;
    if (!role?.rank?.length) return 'Adventurer';
    const firstRank = role.rank[0];
    return (g.flags.female && firstRank.f) ? firstRank.f : (firstRank.m || 'Adventurer');
}
 
function questDeityName() {
    const g = game;
    let name = '';
    switch (g.flags.initalign) {
    case 2:
        name = g.urole?.lgod || '';
        break;
    case 1:
        name = g.urole?.ngod || '';
        break;
    case 0:
        name = g.urole?.cgod || '';
        break;
    default:
        name = 'someone';
        break;
    }
    return name.startsWith('_') ? name.slice(1) : name;
}
 
function questDeityTitle() {
    const g = game;
    const deity = (
        g.flags.initalign === 2 ? g.urole?.lgod
            : g.flags.initalign === 1 ? g.urole?.ngod
                : g.flags.initalign === 0 ? g.urole?.cgod
                    : null
    ) || '';
    return deity.startsWith('_') ? 'goddess' : 'god';
}
 
function startupPagerLines(msgid) {
    const template = STARTUP_PAGER_TEXT[msgid];
    if (!template) return null;
    return template
        .replaceAll('%d', questDeityName())
        .replaceAll('%G', questDeityTitle())
        .replaceAll('%r', questRankTitle())
        .split('\n');
}
 
// NOTE: differs from canonical questpgr.js — startup-specific pager with RNG
// consumption, display overlay, and --More-- handling (not com_pager_core).
// Also NEW import edge (questpgr.js does not import allmain.js).
async function com_pager(msgid) {
    // C ref: questpgr.c — com_pager() creates a fresh Lua state via nhl_init(),
    // which loads nhlib.lua and consumes the align[] shuffle RNG.
    rn2(3);
    rn2(2);
    const display = game?.nhDisplay || null;
    const lines = startupPagerLines(msgid);
    const showStartupText = game.promptedStartup || isStartupPromptPhase();
    if (!display) {
        return;
    }
    if (!lines || !showStartupText) {
        // C ref: questpgr.c com_pager_core can still present text (or at least
        // xwaitforspace) outside startup; keep the --More-- boundary.
        await more(display);
        return;
    }
    // C ref: com_pager_core → deliver_by_window creates NHW_MENU window.
    // C's tty_display_nhwindow sets cw->active=1; destroy calls dismiss if active.
    const datawin = tty_create_nhwindow(NHW_MENU);
    if (game.wins[datawin]) game.wins[datawin].active = true;
 
    // C renders the game map first (via display_gamewindows/docrt), then
    // overlays the pager text on rows 0-17. Map content below the pager
    // (rows 18+) and status lines (22-23) remain visible.
    // Use existing _screen_output (from prior docrt) to preserve correct
    // game state (especially AC in status lines). Don't call docrt()
    // here as it may recalculate with stale worn-armor state.
    if (game._screen_output) {
        render_screen_output_to_display(display);
    }
 
    const cols = display.cols || 80;
    const maxWidth = lines.reduce((m, line) => Math.max(m, line.length), 0);
    const promptRow = 17;
    // C ref: wintty.c — pager right-aligns text against column 79
    const titleCol = cols - maxWidth - 1;
    // C's tty_putstr stores maxcol = strlen(str) + 1 (attribute byte),
    // then offx = cols - maxcol - 1 = cols - strlen - 2. The dismiss
    // events use this offset to match C's erase_menu_or_text parameters.
    const dismissOffx = cols - maxWidth - 2;
    const clearRowFrom = (row, col) => {
        const start = Math.max(0, Math.min(col, cols));
        for (let c = start; c < cols; c++) {
            display.setCell(c, row, ' ');
        }
    };
    for (let row = 0; row < lines.length && row < promptRow; row++) {
        const line = lines[row];
        clearRowFrom(row, titleCol - 1);
        if (!line) continue;
        const leadingSpaces = line.length - line.trimStart().length;
        display.putstr(titleCol + leadingSpaces, row, line.trimStart());
    }
    clearRowFrom(promptRow, titleCol - 1);
    display.putstr(titleCol, promptRow, '--More--');
    if (typeof display.setCursor === 'function') {
        display.setCursor(titleCol + '--More--'.length, promptRow);
    }
 
    // Tell docrt() to serialize from grid instead of rebuilding from game
    // state. The pager text is rendered directly to the grid; docrt() would
    // overwrite it because g.level already exists at this point.
    game._menuActive = true;
    // C's pager uses xwaitforspace which doesn't touch toplin.
    // Don't set toplin to NEED_MORE here — that would trigger
    // ^toplin[tty_nhgetch=2] events that C doesn't produce.
    enterModal('more');
    try {
        let ch;
        do {
            ch = await nhgetch();
        } while (ch !== 32 && ch !== 27 && ch !== 13);
    } finally {
        exitModal('more');
        game._menuActive = false;
        // C ref: com_pager_core → deliver_by_window → destroy_nhwindow
        // C's destroy_nhwindow calls tty_dismiss_nhwindow for active windows,
        // which runs erase_menu_or_text → docorner to clean up the overlay.
        if (game.level) {
            tty_destroy_nhwindow(datawin);
            erase_menu_or_text(datawin, dismissOffx, promptRow);
            await docorner(dismissOffx, promptRow + 1);
            // Repaint the terminal grid after overlay cleanup.
            // erase_menu_or_text cleared grid rows, and docorner
            // updated the glyph buffer via newsym. Now generate
            // a fresh screen and paint it to the grid so subsequent
            // grid-based captures (during More prompts) are correct.
            const display = game?.nhDisplay || null;
            if (display) {
                // Generate ANSI output from current glyph state
                await docrt(false, true); // captureOnly — no setBotlx
                if (game._screen_output) {
                    render_screen_output_to_display(display);
                }
            }
        } else {
            tty_destroy_nhwindow(datawin);
        }
    }
}
function notice_mon_on() { /* allmain.c */ }
 
// movemon, mcalcdistress, mcalcmove, initrack, settrack imported from mon.js
// makemon imported from makemon.js
 
// NOTE: differs from canonical cmd.js — wraps rhack with _inRhack flag.
// _rhackScreenIdx records the screen index before command execution.
// Menu captures during rhack replace this screen rather than pushing
// a new one (C captures at the menu's getch, not moveloop's getch).
// domove is in cmd.js
// C ref: do.c:1479 goto_level()
// Core level transition logic. Called inline from command handlers
// (dodown, doup, teleport) matching C's non-deferred call pattern.
// C ref: do.c goto_level(newlevel, at_stairs, falling, portal)
export async function goto_level(newlev, atStairs = true, falling = false, portal = false) {
    const g = game;
    let u = g.u;
    if (!newlev) return;
    const levelKey = (lev) => `${lev?.dnum ?? -1}:${lev?.dlevel ?? -1}`;
    const oldUz = { ...(u.uz || {}) };
    const dist = depth_of_level(newlev) - depth_of_level(oldUz);
    const prev_temperature = g.level?.flags?.temperature || 0;
    const newdungeon = newlev.dnum !== oldUz.dnum;
    const leavingTutorial = newdungeon && in_tutorial(oldUz) && !in_tutorial(newlev);
    const atLadder = !!stairway_at(u?.ux, u?.uy)?.isladder;
 
    // C ref: do.c:1578-1581 — prevent descending past quest start
    // unless the quest leader has given permission.
    if (on_level(u.uz, qstart_level()) && !newdungeon && !ok_to_quest()) {
        await pline('A mysterious force prevents you from descending.');
        return;
    }
 
    // C ref: do.c:1583-1584 — same level → do nothing
    if (on_level(newlev, u.uz))
        return;
 
    // C ref: do.c:1509-1513 — tutorial state transition hooks.
    if (newdungeon) {
        if (in_tutorial(newlev)) {
            await tutorial(true);
        } else if (in_tutorial(oldUz)) {
            await tutorial(false);
        }
        // C ref: nhlua.c nhl_gamestate(reststate) can replace player state.
        // Refresh local alias so subsequent writes hit current game.u.
        u = g.u;
    }
 
    if (!g.savedLevels) g.savedLevels = new Map();
    if (g.level && Number.isInteger(oldUz.dnum) && Number.isInteger(oldUz.dlevel)) {
        g.savedLevels.set(levelKey(oldUz), {
            level: g.level,
            stairs: g.stairs ?? null,
            moves: g.moves ?? 0,
            // C ref: save.c save_track — utrack is written into the
            // level save file, then cleared from memory.  On re-entry
            // getlev()/rest_track() reads it back from the level file.
            utrack: g.utrack ? g.utrack.map(t => ({ x: t?.x ?? 0, y: t?.y ?? 0 })) : null,
            utpnt: g.utpnt ?? 0,
            utcnt: g.utcnt ?? 0,
        });
    }
    // C ref: do.c:1649 — at level leave, savelev() runs with mode
    // (WRITING|FREEING); release_data(nhfp) is true so save_track()
    // follows the write with initrack().  Clearing in-memory utrack
    // here matches that behavior — the saved copy is restored later
    // when getlev() is called for the destination level (if it has
    // a save file).
    initrack();
    const savedDest = g.savedLevels.get(levelKey(newlev)) || null;
    const isNewLevel = !savedDest;
    // C ref: do.c:1718-1720 — suppress flush_screen during level transition
    await flush_screen(-1); // toggle delay ON
 
    // C ref: do.c:1618-1621 — pre-departure state cleanup
    // reset_utrap(FALSE) → set_utrap(0,0) → float_vs_flight() → SET_BOTL
    setBotl('float_vs_flight');
    // C: fill_pit(u.ux, u.uy) — not yet ported
    // C: set_ustuck(NULL) → SET_BOTL
    setBotl('set_ustuck');
 
    // C ref: do.c:1623-1624 — keepdogs before leaving
    await keepdogs_impl(false);
    // C ref: do.c:1626-1631 — clear vision before saving/leaving old level.
    // This avoids stale previous-level visibility influencing next-level redraw.
    vision_recalc(2);
 
    // Emit mapdump for leaving level
    const oldDnum = u.uz.dnum;
    const oldDlevel = u.uz.dlevel;
    pushRngLogEntry(`^mapdump[leave_d${oldDnum}l${oldDlevel}_m${g.moves ?? 0}]`);
 
    // Update hero level
    u.uz0 = { ...u.uz };
    u.uz = { dnum: newlev.dnum, dlevel: newlev.dlevel };
    // C ref: do.c:1692-1699 goto_level() — track per-dungeon deepest
    // (or highest, for builds-up branches) level reached.
    {
        const dng = g.dungeons?.[u.uz.dnum];
        if (dng) {
            const entryLev = dng.entry_lev ?? 1;
            const buildsUp = entryLev > 1;
            if (!buildsUp) {
                if ((u.uz.dlevel ?? 0) > (dng.dunlev_ureached ?? 0))
                    dng.dunlev_ureached = u.uz.dlevel;
            } else if (!dng.dunlev_ureached || (u.uz.dlevel ?? 0) < dng.dunlev_ureached) {
                dng.dunlev_ureached = u.uz.dlevel;
            }
        }
    }
    g.updest = { lx: 0, ly: 0, hx: 0, hy: 0, nlx: 0, nly: 0, nhx: 0, nhy: 0 };
    g.dndest = { lx: 0, ly: 0, hx: 0, hy: 0, nlx: 0, nly: 0, nhx: 0, nhy: 0 };
 
    // Create new level — clear per-level display state
    g._terrain_memory = {};
    if (savedDest) {
        g.level = savedDest.level;
        g.stairs = savedDest.stairs ?? null;
        // C ref: restore.c:947-972 rest_stairs() reads stairs in chain order
        // and rebuilds with stairway_add(), which prepends and reverses chain.
        {
            let prev = null;
            let cur = g.stairs;
            while (cur) {
                const nxt = cur.next || null;
                cur.next = prev;
                prev = cur;
                cur = nxt;
            }
            g.stairs = prev;
        }
        // Saved-levels are stored as live JS objects instead of serialized
        // C savefiles; if the stairway chain gets out-of-sync with map fields,
        // reinsert missing canonical downstairs link so restored mapstate
        // matches C's rest_stairs/in-map stair topology.
        if (g.level?.dnstair
            && !stairway_at(g.level.dnstair.x, g.level.dnstair.y)) {
            const dnum = u?.uz?.dnum ?? newlev?.dnum ?? 0;
            const dlevel = (u?.uz?.dlevel ?? newlev?.dlevel ?? 1) + 1;
            stairway_add(
                g.level.dnstair.x,
                g.level.dnstair.y,
                false,
                false,
                { dnum, dlevel }
            );
        }
        // C ref: restore.c getlev() rebuilds ftrap by prepending each restored
        // trap, reversing serialized order. Normalize saved-level trap array to
        // that restored-chain orientation.
        if (Array.isArray(g.level?.traps) && g.level.traps.length > 1) {
            g.level.traps = [...g.level.traps].reverse();
        }
        // C ref: restore.c getlev() restores floor object chains by
        // rebuilding fobj and calling place_object() for floor objects.
        // JS keeps saved levels as live objects; replay placement here to
        // preserve C-ordered ^place ownership on level restore.
        if (Array.isArray(g.level?.objects) && g.level.objects.length > 0) {
            const restoredFloor = [...g.level.objects];
            g.level.objects = [];
            for (const otmp of restoredFloor) {
                otmp.nobj = null;
                otmp.nexthere = null;
                place_object(otmp, otmp.ox, otmp.oy);
            }
        }
        // C ref: restore.c:1204-1212 getlev — process monsters on restored level.
        // Monsters that can hide get rnd(10) consumed for re-hiding check.
        // mon_catchup_elapsed_time and restore_cham are not yet ported;
        // the rnd(10) consumption is the RNG-critical part.
        const elapsed = (g.moves || 0) - (savedDest.moves || 0);
        if (elapsed > 0) {
            for (const mtmp of (g.level.monsters || [])) {
                if (mtmp.dead) continue;
                await mon_catchup_elapsed_time(mtmp, elapsed);
                // C ref: restore.c:1212 — hide_monst for elapsed time
                if (elapsed > rnd(10)) {
                    hide_monst(mtmp);
                }
            }
        }
    } else {
        g.level = new GameMap();
        g.level.nroom = 0;
        g.level.rooms = [];
 
        // mklev() — generate level (includes getbones rn2(3))
        await mklev();
    }
 
    // C ref: do.c:1729 goto_level() — normalize room/corridor glyph state
    // for dark-room display semantics immediately after level load/gen.
    reglyph_darkroom();
 
    // C ref: do.c:1746-1773 — place hero at arrival location
    // C uses stairway_find_from to find the stair connecting to the
    // previous level, then places hero there. For new dungeons without
    // a direct stair connection, uses u_on_sstairs or u_on_rndspot.
    // C ref: do.c goto_level() transit direction is depth-based, not dlevel-based.
    // Cross-dungeon transitions can have lower dlevel but still be deeper overall.
    // C ref: do.c:1489 — up is determined by total depth, not dlevel.
    // depth() accounts for the dungeon's depth_start offset.
    let goingUp = depth_of_level(newlev) < depth_of_level({ dnum: oldDnum, dlevel: oldDlevel });
    if (leavingTutorial) goingUp = false;
    let stairTransitMsgDone = false;
    {
        if (portal && !In_endgame(g.u?.uz)) {
            // C ref: do.c:1736-1759 — portal arrivals place hero onto the
            // corresponding MAGIC_PORTAL trap on destination level.
            let ttrap = null;
            for (let t = g.ftrap; t; t = t.ntrap) {
                if (t.ttyp === MAGIC_PORTAL) {
                    ttrap = t;
                    break;
                }
            }
            if (!ttrap) {
                await u_on_rndspot(0);
            } else {
                seetrap(ttrap);
                u_on_newpos(ttrap.tx, ttrap.ty);
            }
        } else if (portal) {
            await u_on_rndspot(0);
        } else if (atStairs && !falling) {
            const stway = stairway_find_from
                ? stairway_find_from({ dnum: oldDnum, dlevel: oldDlevel }, atLadder)
                : null;
            if (stway) {
                // Found stair connecting to previous level
                g.u.ux = stway.sx;
                g.u.uy = stway.sy;
                // C ref: do.c:1765,1783 — mark stair as traversed
                stway.u_traversed = true;
            } else if (newdungeon) {
                // New dungeon, no direct stair — use special stairs
                if (goingUp) {
                    if (u_on_sstairs) await u_on_sstairs(1);
                    else await u_on_rndspot(0);
                } else {
                    if (u_on_sstairs) await u_on_sstairs(0);
                    else await u_on_rndspot(0);
                }
            } else if (goingUp) {
                // C ref: going up arrives on the destination level's downstairs.
                if (u_on_dnstairs) await u_on_dnstairs();
                else await u_on_upstairs();
            } else {
                // C ref: going down arrives on the destination level's upstairs.
                await u_on_upstairs();
            }
 
            // C ref: do.c:1794-1810 — overloaded/fumbling descent fall branch.
            if (!goingUp) {
                if (!(g.u?.dz)) {
                    // stayed on same level: no transit effects
                } else if ((near_capacity() > UNENCUMBERED) || Punished() || Fumbling()) {
                    await You('fall down the stairs.');
                    stairTransitMsgDone = true;
                    if (Punished()) {
                        await drag_down();
                        if (!welded(g.u?.uball)) {
                            await ballrelease(false);
                        }
                    }
                    if (g.u?.usteed) {
                        await dismount_steed(DISMOUNT_FELL);
                    } else {
                        await losehp(Maybe_Half_Phys(rnd(3)),
                            'tumbling down a flight of stairs', KILLED_BY);
                    }
                    await selftouch('Falling, you');
                }
            }
        } else {
            // C ref: do.c trap door / level_tele / endgame transit path.
            await u_on_rndspot(goingUp ? 1 : 0);
        }
    }
 
    // Rebuild fmon linked list and monMap from level's monsters.
    // C ref: restore.c getlev() rebuilds level.monsters[x][y] spatial
    // table during level restore. JS must do the same — the saved monMap
    // may have stale entries from monsters that were removed by keepdogs
    // or that moved positions. Rebuild it fresh from the monster array.
    g.fmon = null;
    const newMonsters = g.level?.monsters || [];
    // Clear the monMap before rebuilding
    if (g.level?.monMap) {
        for (let x = 0; x < COLNO; x++) {
            if (g.level.monMap[x]) g.level.monMap[x].fill(null);
        }
    }
    for (let i = newMonsters.length - 1; i >= 0; i--) {
        const m = newMonsters[i];
        m.nmon = g.fmon;
        g.fmon = m;
        // Rebuild monMap entry for live, on-map monsters
        if (!m.dead && (m.mstate ?? 0) === 0 && isok(m.mx, m.my)) {
            g.level.setMonAt(m.mx, m.my, m);
        }
    }
 
    // C ref: do.c:1760-1816 — transit messaging is part of the
    // at_stairs branch only (not portal/in-endgame arrivals).
    if (!stairTransitMsgDone && atStairs && !portal && !In_endgame(g.u?.uz) && g.flags?.verbose) {
        if (goingUp) {
            await You('climb up the stairs.');
        } else if (g.u?.dz) {
            await pline('You descend the stairs.');
        }
    }
 
    // C ref: do.c:1816 — losedogs() restores migrated pets
    await losedogs_impl();
    // C ref: do.c:1823 — run level-specific timers on arrival
    await run_timers();
    // C ref: do.c:1827-1828 — resolve hero/monster collision after pet arrival
    {
        const mtmp = m_at(g.u.ux, g.u.uy);
        if (mtmp) await u_collide_m(mtmp);
    }
    // C ref: do.c:1711 — getlev() on re-entry calls rest_track() which
    // reads the destination level's previously-saved utrack.  For a
    // fresh level (mklev path at do.c:1699), rest_track is not called
    // so the track stays empty (cleared at leave above).
    if (savedDest && savedDest.utrack) {
        g.utrack = savedDest.utrack.map(t => ({ x: t.x, y: t.y }));
        g.utpnt = savedDest.utpnt;
        g.utcnt = savedDest.utcnt;
    }
    // else: utrack is already empty from initrack() at leave-old-level.
 
    // C ref: do.c — initial movement of bubbles just before vision_recalc.
    // This runs inside goto_level, NOT in the moveloop per-turn block, because
    // the level teleport command has context.move=0 (no ECMD_TIME).
    if (Is_waterlevel(g.u?.uz) || Is_airlevel(g.u?.uz))
        await movebubbles();
 
    // C ref: do.c:1718-1719 — suppress moveloop auto-recalc after level transition
    g.vision_full_recalc = 0;
    // C ref: do.c:1837-1841 — vision_reset, docrt (which calls cls), flush_screen
    vision_reset();
    // C ref: docrt → cls() → clear_nhwindow(MAP) → term_clear_screen
    // Uses docrt_cls which includes the MAP→BASE fallthrough to term_clear_screen
    await docrt_cls();
    // C ref: docrt_flags line 1758 — sets botlx after cls
    setBotlx('docrt_flags');
    // Redraw map cells after cls() so the immediate post-transition frame
    // includes the new level map behind arrival messages.
    // Clear _menuActive so docrt takes the full path (no menu is active
    // at this point — we're in goto_level's screen reset).
    g._menuActive = false;
    await docrt(false, true);
    await flush_screen(-1);
 
    // C ref: do.c:1854-1855 — deliver deferred level-teleport arrival text
    // immediately after the screen reset, before later arrival messages.
    if (g.dfr_post_msg) {
        await maybe_lvltport_feedback();
    }
 
    // C ref: do.c:1871 — special-level custom arrival message.
    await deliver_splev_message();
 
    // C ref: do.c:1874-1890 — Gehennom/Valley arrival messaging and state.
    {
        const prevDun = g.dungeons?.[oldUz?.dnum];
        const curDun = g.dungeons?.[g.u?.uz?.dnum];
        const wasHell = !!prevDun?.flags?.hellish;
        const isHell = !!curDun?.flags?.hellish;
        const isValley = on_level(g.u?.uz, g.valley_level);
        if (!wasHell && isHell) {
            if (isValley) {
                await You('arrive at the Valley of the Dead...');
                await pline('The odor of burnt flesh and decay pervades the air.');
                if (!Deaf()) await You_hear('groans and moans everywhere.');
            }
            record_achievement(ACH_HELL);
        }
        if (isHell && !isValley) {
            if (!g.u.uevent) g.u.uevent = {};
            g.u.uevent.gehennom_entered = 1;
        }
    }
 
    // C ref: do.c:1882-1893 — endgame arrival events.
    if (In_endgame(g.u?.uz)) {
        if (newdungeon)
            record_achievement(ACH_ENDG);
        const isAstralNew = isNewLevel && on_level(g.u?.uz, g.astral_level);
        if (isAstralNew) {
            // C ref: do.c:1886 — final_level(): guardian angel + player monsters
            await final_level();
            record_achievement(ACH_ASTR);
        } else if (newdungeon && g.u?.uhave?.amulet) {
            await resurrect();
        }
    } else if (g.u?.uz?.dnum === g.quest_dnum) {
        // C ref: do.c:1905-1906 — quest level entry messages.
        await onquest();
    }
 
    // C ref: do.c:1926-1928 goto_level() — new rogue-level entry message.
    if (isNewLevel && on_level(g.u?.uz, g.rogue_level)) {
        await You('enter what seems to be an older, more primitive world.');
    }
 
    // C ref: do.c:1975-1981 — tourist XP for reaching a new level
    if (Role_if(PM_TOURIST)) {
        more_experienced(level_difficulty(), 0);
        await newexplevel();
    }
 
    // C ref: do.c:1931-1945 — quest-leader "quest portal" message
    // when entering the quest branch level in the main dungeon.
    if ((oldUz?.dnum !== g.quest_dnum)
        && at_dgn_entrance(g.quest_dnum)
        && !(g.u?.uevent?.qcompleted
            || g.u?.uevent?.qexpelled
            || g.quest_status?.leader_is_dead)) {
        if (!g.u.uevent) g.u.uevent = {};
        if (!g.u.uevent.qcalled) {
            g.u.uevent.qcalled = 1;
            await quest_com_pager('quest_portal');
        } else {
            await quest_com_pager(Role_if(PM_ROGUE) ? 'quest_portal_demand' : 'quest_portal_again');
        }
    }
 
    // C ref: do.c:1984+ and do.c:2015+ — level arrival temperature/smoke feedback.
    await temperature_change_msg(prev_temperature);
 
    // C ref: do.c:2011 — assign_level(&u.uz0, &u.uz); reset "previous level"
    // marker after a completed transition so portal re-entry checks behave
    // like C on subsequent turns.
    g.u.uz0 = { ...g.u.uz };
 
    // C harness patch ref: do.c emits mapstate dump immediately after
    // assign_level(&u.uz0, &u.uz) in goto_level(), not later from cmd tail.
    // C's hero_seq reflects the current turn at dump time. Ensure JS matches
    // by syncing hero_seq to moves before emitting (C sets hero_seq in the
    // moveloop's context.move block which may have already run this turn).
    if (g.hero_seq < (g.moves << 3)) g.hero_seq = g.moves << 3;
    emitTurnMapstate(g, pushRngLogEntry, 'after_goto_level');
 
    // C ref: do.c:1995 — give room entrance message, if any.
    // This handles quest leader dialogue, temple greetings, etc.
    // Messages and --More-- keys are consumed here, inside goto_level,
    // matching C's behavior where check_special_room fires before
    // the moveloop's next iteration.
    await check_special_room(false);
 
    // C ref: do.c:2007-2013 — falling damage after assign_level/mapstate.
    if (falling) {
        let dmg = c_d(Math.max(dist, 1), 6);
        dmg = Maybe_Half_Phys(dmg);
        await losehp(dmg, 'falling down a mine shaft', KILLED_BY);
    }
 
    // C ref: do.c:2015 — arrival autopickup/decor pass.
    await pickup(1);
}
 
// C ref: do.c:2075 deferred_goto()
// For level transitions that were scheduled (traps, portals) rather
// than called inline. Delegates to goto_level.
export async function deferred_goto() {
    const g = game;
    const u = g.u;
    if (!u || !u.utotype) return;
 
    const newlev = u.utolev;
    const oldlev = { ...(u.uz || {}) };
    const typmask = u.utotype; // C saves this because goto_level clears u.utotype
    const sameLevel = !!newlev
        && newlev.dnum === oldlev.dnum
        && newlev.dlevel === oldlev.dlevel;
 
    if (newlev && !sameLevel) {
        if (g.dfr_pre_msg) {
            await pline(g.dfr_pre_msg);
        }
        await goto_level(
            newlev,
            !!(typmask & UTOTYPE_ATSTAIRS),
            !!(typmask & UTOTYPE_FALLING),
            !!(typmask & UTOTYPE_PORTAL)
        );
        // UTOTYPE_RMPORTAL trap removal not yet ported.
        if (g.dfr_post_msg
            && (u.uz?.dnum !== oldlev.dnum || u.uz?.dlevel !== oldlev.dlevel)) {
            await pline(g.dfr_post_msg);
        }
    }
 
    void typmask; // keep C shape while UTOTYPE_* consumers are ported
    u.utotype = 0; // caller keys off this
    g.dfr_pre_msg = null;
    g.dfr_post_msg = null;
}
 
// Calendar functions imported from calendar.js above.
 
// near_capacity imported from pickup.js
// C ref: attrib.c:410-418 change_luck()
function depth_of_level(lev) {
    if (!lev) return 0;
    const dnum = lev.dnum;
    const dlevel = lev.dlevel;
    const dungeon = game?.dungeons?.[dnum];
    if (!dungeon || !dlevel) return 0;
    return (dungeon.depth_start || 0) + dlevel - 1;
}
function depth_uz() { return depth_of_level(game?.u?.uz) || 1; }
function depth_stronghold() { return depth_of_level(game?.stronghold_level); }
function level_monsters() { return game?.level?.monsters || []; }
function in_tutorial(uz) {
    return Number.isInteger(game.tutorial_dnum) && uz?.dnum === game.tutorial_dnum;
}
function at_dgn_entrance(dnum) {
    const uz = game.u?.uz;
    if (!uz || dnum == null) return false;
    const branches = game.branches || [];
    for (const br of branches) {
        if (br?.end2?.dnum !== dnum) continue;
        if (on_level(uz, br.end1)) return true;
    }
    return false;
}
// Fast, Very_fast: imported from macros.js
function current_dex() { return ACURR(A_DEX); }
 
// pline, You imported from display.js
// nh_timeout, run_regions, do_storms imported from timeout.js
// NOTE: differs from canonical vault.js — empty stub here, NEW import edge.
// NOTE: differs from canonical wizard.js — empty stub here (canonical returns bool), NEW import edge.
// C ref: wizard.c:61 amulet() — Amulet effects each turn
async function amulet() {
    const g = game;
    const u = g.u;
    const AMULET_OF_YENDOR = 310; // from objects.js
    const MAGIC_PORTAL_TRAP = 21; // MAGIC_PORTAL trap type
    const amu = (u.uamul?.otyp === AMULET_OF_YENDOR) ? u.uamul
              : (u.uwep?.otyp === AMULET_OF_YENDOR) ? u.uwep : null;
    if (amu && !rn2(15)) {
        for (const trap of (g.level?.traps || [])) {
            if (trap.ttyp === MAGIC_PORTAL_TRAP) {
                const du = (trap.tx - u.ux) * (trap.tx - u.ux) + (trap.ty - u.uy) * (trap.ty - u.uy);
                if (du <= 9)
                    await pline(`${amu === u.uamul ? 'Your amulet' : 'The amulet'} feels hot!`);
                else if (du <= 64)
                    await pline(`${amu === u.uamul ? 'Your amulet' : 'The amulet'} feels very warm.`);
                else if (du <= 144)
                    await pline(`${amu === u.uamul ? 'Your amulet' : 'The amulet'} feels warm.`);
                break;
            }
        }
    }
    if (!g.context?.no_of_wizards) return;
    for (let mtmp = g.fmon; mtmp; mtmp = mtmp.nmon) {
        if (mtmp.dead) continue;
        if (mtmp.iswiz && mtmp.msleeping && !rn2(40)) {
            mtmp.msleeping = 0;
            if (!m_next2u(mtmp))
                await You('get the creepy feeling that somebody noticed your taking the Amulet.');
            return;
        }
    }
}
// C ref: do.c:2042 final_level — Astral Plane arrival
async function final_level() {
    const g = game;
    // C ref: iter_mons(reset_hostility) — reset monster hostility on Astral
    const { reset_hostility } = await import('./priest.js');
    for (let m = g.fmon; m; m = m.nmon) {
        if (!m.dead) reset_hostility(m);
    }
    // C ref: create_mplayers(rn1(4, 3), TRUE)
    const { create_mplayers } = await import('./mplayer.js');
    await create_mplayers(rn1(4, 3), true);
    // C ref: gain_guardian_angel()
    const { gain_guardian_angel } = await import('./minion.js');
    await gain_guardian_angel();
}
 
// C ref: wizard.c:715 resurrect
async function resurrect() {
    const g = game;
    let mtmp = null;
    let verb;
    if (!(g.context?.no_of_wizards ?? 0)) {
        // make a new Wizard
        verb = 'kill';
        mtmp = await makemon(mons[PM_WIZARD_OF_YENDOR], g.u?.ux ?? 0, g.u?.uy ?? 0, MM_NOWAIT);
        if (mtmp) {
            mtmp.mrevived = 1;
        }
    }
    // C ref: wizard.c:729-758 — migrating wizard path (not yet ported)
 
    if (mtmp) {
        mtmp.mstrategy &= ~(0x00000f00); // STRAT_WAITMASK
        mtmp.mtame = 0;
        mtmp.mpeaceful = 0;
        set_malign(mtmp);
        if (!Deaf()) {
            await pline('A voice booms out...');
            await verbalize(`So thou thought thou couldst ${verb} me, fool.`);
        }
    }
}
// C ref: wizard.c:61 intervene() — Wizard interventions when demigod
async function intervene() {
    const g = game;
    const isAstral = on_level(g.u?.uz, g.astral_level);
    const which = isAstral ? rnd(4) : rn2(6);
    // C ref: wizard.c:68-83 — cases 0 and 5 don't apply on Astral
    switch (which) {
    case 0:
    case 1:
        await You_feel('vaguely nervous.');
        break;
    case 2:
        if (!Blind()) {
            const { hcolor } = await import('./do_name.js');
            await You(`notice a ${hcolor('black')} glow surrounding you.`);
        }
        { const { rndcurse } = await import('./sit.js'); await rndcurse(); }
        break;
    case 3:
        { const { aggravate } = await import('./mon.js'); aggravate(); }
        break;
    case 4:
        { const { nasty } = await import('./wizard.js'); nasty(null); }
        break;
    case 5:
        await resurrect();
        break;
    }
}
 
// C ref: hack.c runmode_delay_output()
async function runmode_delay_output() {
    const g = game;
    pushRngLogEntry('>runmode_delay_output');
    if ((g.context?.run || g.multi) && g.flags?.runmode !== RUN_TPORT) {
        if (g.flags.runmode !== RUN_LEAP || !(g.moves % 7)) {
            g.disp.time_botl = !!g.flags.time;
            await curs_on_u();
            await delay_output();
            if (g.flags.runmode === RUN_CRAWL) {
                await delay_output();
                await delay_output();
                await delay_output();
                await delay_output();
            }
        }
    }
    pushRngLogEntry('<runmode_delay_output');
}
 
async function gethungry() {
    // C ref: eat.c gethungry() — full hunger processing
    return gethungry_impl();
}
 
// C ref: hack.c:3015 overexert_hp()
async function overexert_hp() {
    const u = game.u;
    const hpRef = Upolyd() ? 'mh' : 'uhp';
    const hp = u?.[hpRef] ?? 0;
    if (hp > 1) {
        u[hpRef] = hp - 1;
        setBotl('overexert_hp');
    } else {
        await You('pass out from exertion!');
        exercise(A_CON, false);
        await fall_asleep(-10, false);
    }
}
 
// Regeneration stubs (consume no RNG until fully ported)
// C ref: allmain.c:627 regen_hp()
// RNG: rn2(100) for HP regen check when HP < max
async function regen_hp(wtcap) {
    const g = game;
    const u = g.u;
    if (!u) return;
    const MOD_ENCUMBER = 2;
    const encumbrance_ok = (wtcap < MOD_ENCUMBER || !u.umoved);
 
    // C ref: allmain.c:749-766 — non-polymorphed HP regen
    // U_CAN_REGEN: Regeneration intrinsic, or sleeping with Sleepy
    // C ref: allmain.c:692 U_CAN_REGEN = Regeneration || (Sleepy && u.usleep)
    const REGENERATION = 22; // from const.js
    const SLEEPY = 68; // from const.js
    const canRegen = !!(u.uprops?.[REGENERATION]?.intrinsic
        || u.uprops?.[REGENERATION]?.extrinsic)
        || !!((u.uprops?.[SLEEPY]?.intrinsic || u.uprops?.[SLEEPY]?.extrinsic) && u.usleep);
    let reachedFull = false;
    // C ref: allmain.c:702-721 — polymorphed hero HP handling
    if (Upolyd()) {
        if (u.mh < 1) {
            const { rehumanize } = await import('./polyself.js');
            await rehumanize();
        } else if (g.youmonst?.data?.mlet === 57 /*S_EEL*/
                   && !([16/*POOL*/, 17/*MOAT*/, 18/*WATER*/].includes(g.level?.at(u.ux, u.uy)?.typ))
                   && !Is_waterlevel(g.u?.uz)
                   && !Breathless()) {
            // Eel out of water loses HP
            if (u.mh > 1 && !canRegen && rn2(u.mh) > rn2(8)
                && (!Half_physical_damage() || !((g.moves || 0) % 2))) {
                u.mh -= 1;
                setBotl('regen_hp_eel');
            }
        } else if (u.mh < u.mhmax) {
            if (canRegen || (encumbrance_ok && !((g.moves || 0) % 20))) {
                u.mh = Math.min(u.mh + 1, u.mhmax);
                setBotl('regen_hp_poly');
            }
        }
        reachedFull = (u.mh === u.mhmax);
        if (reachedFull) await interrupt_multi('You are in full health.');
        return;
    }
    if (u.uhp < u.uhpmax && (encumbrance_ok || canRegen)) {
        let heal = ((u.ulevel + ACURR(A_CON)) > rn2(100)) ? 1 : 0;
        if (canRegen) heal += 1;
        // C ref: allmain.c:734 — sleeping with Sleepy property heals faster
        if ((u.uprops?.[SLEEPY]?.intrinsic || u.uprops?.[SLEEPY]?.extrinsic) && u.usleep)
            heal++;
        if (heal) {
            u.uhp += heal;
            if (u.uhp > u.uhpmax) u.uhp = u.uhpmax;
            setBotl('regen_hp');
            reachedFull = (u.uhp === u.uhpmax);
        }
    }
    if (reachedFull) {
        await interrupt_multi('You are in full health.');
    }
}
// C ref: allmain.c:691 regen_pw — energy regeneration
async function regen_pw(wtcap) {
    const g = game;
    const u = g.u;
    if (!u || u.uen >= u.uenmax) return;
    const MOD_ENCUMBER = 2;
    const interval = Math.trunc((30 + 8 - u.ulevel) * (Role_if(PM_WIZARD) ? 3 : 4) / 6);
    const energyRegen = !!(u.uprops?.[ENERGY_REGENERATION]?.intrinsic
        || u.uprops?.[ENERGY_REGENERATION]?.extrinsic);
    if ((wtcap < MOD_ENCUMBER && interval > 0 && !(g.moves % interval))
        || energyRegen) {
        const wis = u.acurr?.a?.[A_WIS] ?? 10;
        const intel = u.acurr?.a?.[A_INT] ?? 10;
        let upper = Math.trunc((wis + intel) / 15) + 1;
        // C: EMagical_breathing bonus (simplified: skip)
        u.uen += rn1(upper, 1);
        if (u.uen > u.uenmax) u.uen = u.uenmax;
        setBotl('regen_pw');
        if (u.uen === u.uenmax) {
            await interrupt_multi('You feel full of energy.');
        }
    }
}
// u_wipe_engr imported from engrave.js (removed local stub)
 
// C ref: options.c ask_do_tutorial()
// Displays a menu with "Yes, do a tutorial" / "No, just start play" options.
// On re-prompt (after invalid input), adds "(Please choose 'y' or 'n'.)".
async function ask_do_tutorial() {
    // C ref: options.c ask_do_tutorial()
    // If tutorial option was set in config, obey it without asking.
    if (game.tutorial_set_in_config) {
        return game.flags?.tutorial ? 'y'.charCodeAt(0) : 'n'.charCodeAt(0);
    }
 
    let pass = 0;
    let result;
    do {
        const win = create_nhwindow_menu();
        start_menu(win);
        add_menu(win, 'y', 'y', 0, 0, NO_COLOR, 'Yes, do a tutorial', 0);
        add_menu(win, 'n', 'n', 0, 0, NO_COLOR, 'No, just start play', 0);
        add_menu_str(win, '');
        add_menu_str(win, 'Put "OPTIONS=!tutorial" in .nethackrc to skip this query.');
        if (pass > 0) {
            add_menu_str(win, "(Please choose 'y' or 'n'.)");
        }
        end_menu(win, 'Do you want a tutorial?');
        result = await select_menu(win, 1); // PICK_ONE
        destroy_nhwindow_menu(win);
        pass++;
    } while (result.count === 0);
 
    if (result.count > 0) {
        return result.items[0].identifier === 'y' ? 'y'.charCodeAt(0) : 'n'.charCodeAt(0);
    }
    // ESC (count === -1) → no tutorial
    return 'n'.charCodeAt(0);
}
 
// Tutorial prompt — C ref: options.c ask_do_tutorial()
// Uses a full NHW_MENU window, not a simple yn prompt.
export async function maybe_do_tutorial() {
    const sp = find_level('tut-1');
    if (!sp) return;
    const answer = await ask_do_tutorial();
    if (String.fromCharCode(answer).toLowerCase() === 'y') {
        const display = game?.nhDisplay || null;
        await tutorial(true);
 
        // C ref: do.c:2101 deferred_goto → goto_level → arrive()
        // C's arrive() calls pline BEFORE level generation events.
        // The pline triggers flush_screen → bot, then state management.
        await pline('Entering the tutorial.');
        // C ref: arrive() calls float_vs_flight() and set_ustuck()
        // which each SET_BOTL. No intermediate setBotl.
        setBotl('float_vs_flight');
        setBotl('set_ustuck');
 
        // C ref: do.c goto_level() → mklev() → makelevel()
        // C: getbones() — rn2(3), returns early (no bones)
        rn2(3);
 
        // C: nhl_init() → nhlib.lua → align[] shuffle
        l_nhcore_init(); // rn2(3) + rn2(2)
 
        // C: splev_initlev() rn2(2) for solidfill lit is now handled
        // inside level_init() when the level script calls des.level_init().
 
        // C: goto_level saves current level, emits mapdump event keyed by move count.
        pushRngLogEntry(`^mapdump[leave_d0l1_m${game.moves ?? 0}]`);
 
        // C ref: do.c:1608-1616 goto_level() — preserve departing level state
        // so tutorial exit can restore the exact prior level.
        if (!game.savedLevels) game.savedLevels = new Map();
        if (game.level
            && Number.isInteger(game.u?.uz?.dnum)
            && Number.isInteger(game.u?.uz?.dlevel)) {
            const key = `${game.u.uz.dnum}:${game.u.uz.dlevel}`;
            game.savedLevels.set(key, {
                level: game.level,
                stairs: game.stairs ?? null,
                moves: game.moves ?? 0,
            });
        }
 
        game.u.ucamefrom = { ...game.u.uz };
        game.u.uz0 = { ...game.u.uz };
        game.u.uz = { dnum: sp.dlevel.dnum, dlevel: sp.dlevel.dlevel };
        game.u.utolev = { ...game.u.uz };
        game.updest = { lx: 0, ly: 0, hx: 0, hy: 0, nlx: 0, nly: 0, nhx: 0, nhy: 0 };
        game.dndest = { lx: 0, ly: 0, hx: 0, hy: 0, nlx: 0, nly: 0, nhx: 0, nhy: 0 };
 
        // C: clear_level_structures creates a fresh GameMap
        // Clear per-level display memory (JS uses a global dict, C uses per-tile seenv)
        game._terrain_memory = {};
        game.level = new GameMap();
        game.level.nroom = 0;
        game.level.rooms = [];
        // C ref: mklev.c:init_level() sets svl.level.flags.hero_memory = 1.
        // Tutorial generation bypasses mklev(), so set the same invariant here.
        game.level.flags.hero_memory = true;
        game.in_mklev = true; // C: set during mklev for mkobj_erosions etc.
 
        // C: s_level flags.align is computed from dungeon flags bitmask.
        // Tutorial dungeon has flags = MAZELIKE|UNCONNECTED = 0x04|0x10.
        // C's init_level: flags.align = ((dungeon_flags & 0x70) >> 4) = 1 = AM_CHAOTIC.
        // The UNCONNECTED flag (0x10) overlaps D_ALIGN_CHAOTIC (AM_CHAOTIC<<4).
        // This is a C data format quirk we must reproduce for bit-exact parity.
        game.special_level_align = 1; // AM_CHAOTIC
 
        // Run the tut-1 level script
        try {
            const tut1 = await import('./levels/tut-1.js'); // lazy // lazy
            if (typeof tut1.generate === 'function') {
                await tut1.generate();
            }
        } catch (e) {
            // Don't silently swallow tutorial errors.
            throw e;
        }
 
        // Tutorial level generation path bypasses mklev(); run the same
        // topology finalization steps that establish rm.flags aliases
        // (bound_digging + wall_info state) without invoking mineralize RNG.
        level_finalize_topology({ skipMineralize: true });
 
        // C ref: mklev() runs water_has_kelp() checks during level-finalize
        // before arrival. Keep this explicit pass for tutorial parity.
        mineralize_kelp(-1, -1, false);
 
        // C: goto_level() arrival on tutorial entry uses await u_on_rndspot(0),
        // which in turn uses the level's teleport-region destination area.
        await u_on_rndspot(0);
        if (game?.dndest?.lx > 0 && game?.dndest?.ly >= 0
            && game?.dndest?.lx === game?.dndest?.hx
            && game?.dndest?.ly === game?.dndest?.hy) {
            u_on_newpos(game.dndest.lx, game.dndest.ly);
        }
 
        // C-shaped level transition invariant: fmon tracks only current
        // level monsters. Reset stale old-level chain before continuing.
        game.fmon = null;
        const tutorialMonsters = game.level?.monsters || [];
        for (let i = tutorialMonsters.length - 1; i >= 0; i--) {
            const m = tutorialMonsters[i];
            m.nmon = game.fmon;
            game.fmon = m;
        }
 
        // C: mapdump event for the completed tutorial level
        {
            const serial = ((game.mapdump_serial ?? 0) + 1);
            game.mapdump_serial = serial;
            pushRngLogEntry(`^mapdump[d8l1_${String(serial).padStart(3, '0')}]`);
        }
 
        // C ref: goto_level → vision_reset + vision_recalc for new level.
        // Terrain memory is populated incrementally as the player explores.
        vision_reset();
        vision_recalc();
 
        // C ref: after level gen, the "Entering" message is still pending
        // (toplin=2). C routes this through tty_display_nhwindow(WIN_MESSAGE),
        // which owns the more() -> tty_clear_nhwindow -> display lifecycle,
        // then cls() clears the screen for the new level before the engraving
        // messages.
        game._menuActive = false;
        if (display) {
            // C ref: docrt_flags → cls → display_nhwindow(WIN_MESSAGE) handles
            // more() internally when toplin=NEED_MORE. cls() then calls
            // clear_nhwindow(WIN_MAP) → term_clear_screen → erase_tty_screen
            // which iterates all active windows. No separate clear calls needed.
            // docrt() internally emits setBotlx('docrt_flags') after newsym loop.
            await cls();
            game._terrain_memory = {};
            // C ref: docrt_flags() runs newsym loop + SET_BOTLX
            await docrt(true);
            await flush_screen();
            render_screen_output_to_display(display);
            // C keeps hero_seq tied to moves (moves << 3).
            game.hero_seq = (game.moves ?? 0) << 3;
            // C tutorial goto-level path emits mapstate dump in the arrival
            // frame before the first engraving plines.
            emitTurnMapstate(game, pushRngLogEntry, 'after_goto_level');
            // C ref: read_engr_at — two plines. The second pline's
            // update_topl sees toplin=NEED_MORE from the first and
            // calls more() internally.
            await pline('Something is engraved here on the floor.');
            await pline('You read: "Move around with h j k l".');
            // C ref: allmain.c:652 — docrt() after deferred_goto.
            // C's docrt internally calls cls() which handles the pending
            // more() for the second engraving message.
            // moveloop_core handles find_ac + bot on first iteration —
            // do NOT call find_ac/flush_screen here (C doesn't).
            game._terrain_memory = {};
            await cls();
            await docrt(true);
        }
        // C ref: do.c goto_level() finalization resets uz0 to current level
        // after arrival processing is complete.
        game.u.uz0 = { ...game.u.uz };
    }
}