All files / js zap.js

51.15% Statements 1213/2371
44.32% Branches 246/555
65.38% Functions 51/78
51.15% Lines 1213/2371

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 237273x 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   12x   14x 6x 2x 6x 2x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 21x 21x 21x 21x 21x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 3x 3x 3x 3x 3x   73x 1x 1x     1x       1x 1x             1x 1x 1x 1x 1x 1x 73x                           73x 73x 73x 73x 73x 73x 73x 73x                   73x                                     73x       73x 73x 3x 3x 3x                     3x 3x 73x 1x 1x 1x 1x 1x 1x     1x 1x                 1x 73x 11x 11x 11x 11x 11x                                                       11x 73x               73x             73x                   73x         73x                                                             73x 31x 31x 31x 31x                                       31x       73x 73x 73x 24716x 24716x 24716x 24716x 24716x 24716x   24716x 24716x 24716x 24716x 24716x 24716x 73x 31x 31x 31x 31x 31x 31x 31x 31x 31x                                                                       31x 31x 31x 31x 31x                                                         31x 31x                                                                                     31x 31x 31x 73x 73x 31x 31x 31x 31x 2x 2x 2x 17x 31x 31x 31x 31x 6x 6x                       6x       6x 6x 6x 2x 31x 73x 72x 72x 72x 72x 72x 72x 72x 72x 24x 24x 24x   24x           24x 72x 17x 17x     17x 72x         72x 72x 8x 8x 72x 23x 72x 72x 72x       72x 72x                                     72x 72x 24x 24x 72x       72x 72x 73x 24x 24x 24x 24x 24x 24x 2x 2x 2x                                                             2x 2x 24x 24x 73x                                                                                   73x                     73x 73x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x               3x 3x 3x 3x 3x                 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x         3x 1x 1x 1x 3x                     3x               3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 89x 89x 3x 3x 3x 89x 89x 89x 3x 3x 3x 3x 3x                 3x 3x 3x 3x 3x 3x 3x 73x 2x 2x 2x 2x 2x       2x 2x 2x 2x             2x 2x             2x 2x 2x 73x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 73x 92x 92x 92x 92x 92x 73x 27x 27x 27x   27x 73x 73x 24x 24x 24x 24x 24x 24x 24x 73x               73x 542x 542x 426x 542x 73x 73x 20x 19x 10x 10x 18x 9x 9x 9x 9x 9x 9x 19x 19x 20x 73x 73x 45x 45x 73x 73x 4x 4x 4x 4x 4x 4x 73x 73x 6x 6x 6x 6x 6x 73x 73x 1x 1x   1x 1x     1x 1x 73x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x     1x     1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 73x 73x 12x 12x 12x 11x 12x 12x 12x 73x 32x 32x 32x 32x 32x 32x 32x 32x 73x               73x 4x 4x 4x 4x 4x 2x 2x 2x 2x 4x 2x 2x 2x 4x         4x       4x               4x       4x 4x 4x 2x 2x 2x 4x 73x 73x 8x 8x 8x 8x           8x 1x 1x 1x 1x 1x 1x 1x       1x       8x       8x                 8x               8x         8x 5x 5x 5x 5x 5x 8x     8x     8x     8x       8x 1x 1x     1x 1x   1x 1x 1x 8x   8x 1x 1x 8x           8x       8x         8x               8x             8x     8x 8x   8x           8x       8x 8x 7x 7x 8x 73x           73x 73x 7x 7x 7x 7x 7x 73x 73x 21x 21x 21x 21x 21x 21x 21x   21x 7x 7x   7x   7x 7x 7x 7x 7x 21x 4x 14x 10x 8x 8x 6x 6x 9x 9x 20x 9x 9x 9x 21x 73x 73x 30x 30x 4x 4x 4x 30x 26x 30x 24x 30x 30x   28x       24x     24x 8x 7x     24x 16x 16x 16x 16x 30x     27x 23x 23x 23x 30x 73x 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x                                 1x           1x             1x                         1x                                                       1x     1x 1x 1x 1x 1x                     1x     1x           1x                         1x                     1x     1x           1x     1x     1x     1x   1x 1x 1x 1x 1x 1x 1x 73x 73x 7x 7x               7x 7x 7x   7x             7x 7x 7x 5x       5x 5x 5x 5x 5x 5x     5x 2x 2x 2x     2x 2x 3x 3x 3x 7x         7x 1x 1x 1x             1x                   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 7x     7x     7x 1x 1x 7x   7x     7x 7x       7x 7x 7x 7x     7x     7x   7x 7x 7x 7x 7x 73x 73x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 32x 32x 32x 32x 32x 32x 53x 148x 148x 148x 148x 148x         148x 31x 31x 148x 148x 148x 148x 24x             24x 16x 16x 24x 148x                 148x 21x 21x 1x       1x 21x 1x 1x 1x 1x               1x 1x 20x 19x 19x 19x 19x 21x 148x 31x 31x 31x 128x 148x 148x 31x 31x 31x                   31x 148x 148x 128x 128x 32x 32x 32x 32x 128x 96x 103x 72x 72x 148x 53x 53x 73x 73x 73x             73x 73x 2x 2x 2x 2x 2x 2x 2x               2x                                   2x 1x       1x 1x 1x 1x 1x 1x 1x 1x 2x       2x                                                             2x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x             2x                 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 73x 8x 8x 8x 8x 8x 8x       8x 3x 3x 1x 1x 1x 3x 2x 2x 3x 3x 3x 3x 3x 3x 8x 3x 3x       3x 3x 3x 3x 3x 8x 1x     1x 1x 1x 1x 8x           8x 1x 1x       1x 1x 1x 1x 1x 1x 8x     8x           8x 8x 8x 73x                 73x 73x 9x 9x 73x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x                       10x 10x 10x 10x 10x 10x 10x 10x 10x 73x 73x 73x 1x 1x 1x                       1x 1x 1x     72x 72x 72x 73x 72x 72x 72x 72x 73x 73x 73x 72x 72x 72x 72x 73x 2x 2x 2x 2x 2x 2x 2x             2x 2x 2x 2x                   2x   2x 2x   2x 2x 2x 2x                       2x 2x 2x       73x 10x 10x 10x 10x 10x 2x 2x 2x     2x 2x 2x 2x 2x 10x 8x 7x 7x 10x     10x 9x 9x 9x 71x 73x     73x 73x 11x 11x 9x       9x 9x 11x       11x 11x 11x 11x 11x 11x 73x 9x 10x     9x 10x 73x 73x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x       4x 1x 1x 1x 1x 1x 1x 1x 4x 4x 73x 73x 73x 1x 1x 1x 1x 1x     1x 73x 73x                                     73x 73x         73x 73x       73x 73x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 73x 73x 73x                 73x 73x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x 117x           117x 117x 117x 117x 117x 117x 117x 117x 117x 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  
// zap.js -- Full port of zap.c from NetHack 3.7
// Wand/spell/breath zap effects, beam propagation, damage handling
import { game } from './gstate.js';
import { closed_door } from './monmove.js';
import { Blind, Breathless, Cold_resistance, Deaf, Fire_resistance, Hallucination, HStun, Invocation_lev, Maybe_Half_Phys, Reflecting, See_invisible, Shock_resistance, Sleep_resistance, Stunned, Unchanging } from './macros.js';
import { fall_asleep } from './timeout.js';
import { getlin, ynFunction } from './input.js';
import { bot, canseemon, canspotmon, delay_output, flush_screen, newsym, seemimic, shieldeff, tmp_at, tty_clear_nhwindow } from './display.js';
import { GLYPH_ZAP_OFF } from './glyph.js';
import { an, aobjnam, corpse_xname, doname, makeplural, readobjnam, the, The, Tobjnam, vtense, xname, yname, Yname2 } from './objnam.js';
import { rndmonnam } from './do_name.js';
import { delobj, getobj, hold_another_object, makeknown, useup, useupall } from './invent.js';
import { rn1, rn2, rnd, c_d, pushRngLogEntry } from './rng.js';
import { AMULET_OF_UNCHANGING, AMULET_OF_YENDOR, ARMOR_CLASS, BELL_OF_OPENING, BOULDER, CANDELABRUM_OF_INVOCATION, CORPSE, DWARVISH_CLOAK, EGG, GEM_CLASS, IMMEDIATE, Is_box, is_corrodeable, is_crackable, is_flammable, is_poisonable, is_rottable, is_rustprone, LOW_BOOTS, MAGIC_LAMP, MAGIC_MARKER, NODIR, OIL_LAMP, POT_GAIN_ABILITY, POT_OIL, POT_POLYMORPH, POT_WATER, POTION_CLASS, RIN_SHOCK_RESISTANCE, RING_CLASS, ROCK, SCR_FIRE, SCROLL_CLASS, SPBOOK_CLASS, SPE_BLANK_PAPER, SPE_BOOK_OF_THE_DEAD, SPE_CANCELLATION, SPE_CONE_OF_COLD, SPE_CREATE_MONSTER, SPE_DETECT_UNSEEN, SPE_DIG, SPE_DRAIN_LIFE, SPE_EXTRA_HEALING, SPE_FINGER_OF_DEATH, SPE_FIREBALL, SPE_FORCE_BOLT, SPE_HEALING, SPE_KNOCK, SPE_LIGHT, SPE_MAGIC_MISSILE, SPE_NOVEL, SPE_POLYMORPH, SPE_SLEEP, SPE_SLOW_MONSTER, SPE_STONE_TO_FLESH, SPE_TELEPORT_AWAY, SPE_TURN_UNDEAD, SPE_WIZARD_LOCK, STATUE, STRANGE_OBJECT, TOOL_CLASS, WAN_CANCELLATION, WAN_COLD, WAN_CREATE_MONSTER, WAN_DEATH, WAN_DIGGING, WAN_ENLIGHTENMENT, WAN_FIRE, WAN_LIGHT, WAN_LIGHTNING, WAN_LOCKING, WAN_MAGIC_MISSILE, WAN_MAKE_INVISIBLE, WAN_NOTHING, WAN_OPENING, WAN_POLYMORPH, WAN_PROBING, WAN_SECRET_DOOR_DETECTION, WAN_SLEEP, WAN_SLOW_MONSTER, WAN_SPEED_MONSTER, WAN_STASIS, WAN_STRIKING, WAN_TELEPORTATION, WAN_UNDEAD_TURNING, WAN_WISHING, WAND_CLASS, WEAPON_CLASS } from './objects.js';
import { A_CON, A_DEX, A_INT, A_STR, A_WIS, ACID_RES, BURIED_TOO, COLD_RES, CONTAINED_TOO, CORR, CXN_PFX_THE, DB_DIR, DB_EAST, DB_NORTH, DB_SOUTH, DB_WEST, DBWALL, DISINT_RES, DISP_BEAM, DISP_CHANGE, DISP_END, DRAWBRIDGE_DOWN, DRAWBRIDGE_UP, ECMD_CANCEL, ECMD_OK, ECMD_TIME, engulfing_u, EXPL_MAGICAL, FIRE_RES, FLASHED_LIGHT, GETOBJ_EXCLUDE, GETOBJ_NOFLAGS, GETOBJ_SUGGEST, ICE, is_magical_trap, ismnum, Is_stronghold, is_xport, isok, M_AP_TYPE, M_SEEN_REFL, MM_FEMALE, MM_MALE, MM_NOCOUNTBIRTH, MM_NOMSG, MM_NOWAIT, NC_SHOW_MSG, NC_VIA_WAND_OR_SPELL, NO_MINVENT, NON_PM, nothing_happens, OBJ_BURIED, OBJ_FLOOR, OBJ_FREE, OBJ_INVENT, OBJ_MINVENT, ONAME, P_BASIC, P_EXPERT, P_ISRESTRICTED, P_SKILLED, P_UNSKILLED, POISON_RES, POLY_NOFLAGS, RLOC_MSG, SCORR, SDOOR, SHOCK_RES, SLEEP_RES, TEMPLE, THROWN_WEAPON, TIMEOUT, TRAP_EXPLODE, VIBRATING_SQUARE, W_ACCESSORY, W_ARM, W_ARMC, W_ARMOR, W_ARMS, W_ARMU, W_ART, W_RING, W_WEP, WAND_BACKFIRE_CHANCE, WAND_WREST_CHANCE, ZAP_POS, ZAPPED_WAND } from './const.js';
import { exercise, ACURR } from './attrib.js';
import { Soundeffect } from './sounds.js';
import { more_experienced } from './exper.js';
import { addtobill, check_unpaid, costly_spot, stolen_value } from './shk.js';
import { check_capacity, killed, losehp, monkilled } from './hack.js';
import { breaks, hero_breaks } from './dothrow.js';
import { cansee } from './vision.js';
import { m_at, obj_at, t_at } from './map_access.js';
import { AD_ACID, AD_COLD, AD_DISN, AD_DRST, AD_ELEC, AD_FIRE, AD_MAGM, AD_RBRE, AD_SLEE, mons, PM_CROCODILE, PM_GREMLIN, S_EEL, S_ZOMBIE } from './monsters.js';
import { resists_magm, resists_fire, resists_cold, resists_elec,
         resists_poison, resists_acid, resists_disint, resists_blnd,
         defended, haseyes, hides_under, nonliving, is_demon, is_vampshifter, is_rider,
         is_undead, completelyburns, control_teleport, unique_corpstat, is_reviver,
         monstseesu, monstunseesu } from './mondata.js';
import { find_mac, mon_adjust_speed, mon_set_minvis, which_armor, setnotworn } from './worn.js';
import { create_particular, litroom, recharge } from './read.js';
import { zap_dig } from './dig.js';
import { acid_damage, check_gear_next_turn, DEADMONSTER, drain_item, has_oname, healmon, hideunder, is_mplayer, mon_nam, monflee, Monnam, newcham, stop_occupation, uhim, unstuck, unturn_dead, update_inventory, wakeup } from './mon.js';
import { boxlock, doorlock } from './lock.js';
import { pline, pline_The, You, You_feel, You_hear, Your } from './pline.js';
import { Ring_gone } from './do_wear.js';
import { findit } from './detect.js';
import { noteleport_level, rloc, rloc_to } from './teleport.js';
import { enexto, makemon } from './makemon.js';
import { in_rooms } from './shk.js';
import { deltrap, undestroyable_trap, trapname } from './trap.js';
import { find_drawbridge, is_db_wall, open_drawbridge, close_drawbridge, destroy_drawbridge, is_pool } from './dbridge.js';
import { engr_at, del_engr, make_engr_at, rloc_engr, wipe_engr_at, random_engraving } from './engrave.js';
import { cvt_sdoor_to_door, show_map_spot } from './detect.js';
import { recalc_block_point, unblock_point, glyph_at } from './display.js';
import { S_arrow_trap, PCHAR_TILES_ROWS } from './symbols.js';
import { explode } from './explode.js';
import { make_blinded, make_stunned, potionbreathe } from './potion.js';
import { sleep_monst, slept_monst } from './mhitm.js';
import { m_useup } from './mthrowu.js';
import { mon_reflects, ureflects } from './muse.js';
import { create_gas_cloud } from './region.js';
import { burnarmor } from './trap.js';
import { erode_armor, flash_hits_mon, xkilled } from './uhitm.js';
import { s_suffix, upstart } from './hacklib.js';
import { getdir, nomul } from './cmd.js';
import { polyself } from './polyself.js';
import { ustatusline } from './insight.js';
import { encumber_msg, force_decor } from './pickup.js';
import { dead_species, dealloc_obj, destroy_items, erosion_matters, get_obj_location, ignite_items, is_damageable, melt_ice, mkobj, mksobj, obj_extract_self, place_object, rnd_class, rloco, splitobj, weight } from './mkobj.js';
import { spell_skilltype } from './spell.js';
import { P_SKILL } from './weapon.js';
import { christen_monst } from './do_name.js';
import { cant_revive } from './read.js';
import { cant_finish_meal } from './eat.js';
import { attach_egg_hatch_timeout } from './timeout.js';
import { CLR_BLACK, CLR_GREEN, CLR_ORANGE, CLR_WHITE, CLR_YELLOW } from './terminal.js';
// ── Constants ──
const MAGIC_COOKIE = 1000;
const M1_NOHANDS = 0x2000;
const ZT_MAGIC_MISSILE = AD_MAGM - 1;
const ZT_FIRE = AD_FIRE - 1;
const ZT_COLD = AD_COLD - 1;
const ZT_SLEEP = AD_SLEE - 1;
const ZT_DEATH = AD_DISN - 1;
const ZT_LIGHTNING = AD_ELEC - 1;
const ZT_POISON_GAS = AD_DRST - 1;
const ZT_ACID = AD_ACID - 1;
function ZT_WAND(x) { return x; }
function ZT_SPELL(x) { return 10 + x; }
function ZT_BREATH(x) { return 20 + x; }
function is_hero_spell(type) { return type >= 10 && type < 20; }
function BZ_OFS_WAN(otyp) { return Math.abs(otyp - WAN_MAGIC_MISSILE) % 10; }
function BZ_OFS_SPE(otyp) { return Math.abs(otyp - SPE_MAGIC_MISSILE) % 10; }
function BZ_U_WAND(bztyp) { return 0 + bztyp; }
function BZ_U_SPELL(bztyp) { return 10 + bztyp; }
const flash_types = [
    "magic missile",
    "bolt of fire", "bolt of cold", "sleep ray", "death ray",
    "bolt of lightning", "", "", "", "",
    "magic missile",
    "fireball", "cone of cold", "sleep ray", "finger of death",
    "bolt of lightning",
    "", "", "", "",
    "blast of missiles",
    "blast of fire", "blast of frost", "blast of sleep gas",
    "blast of disintegration", "blast of lightning",
    "blast of poison gas", "blast of acid", "", "",
];
// C ref: zap.c zapdir_to_glyph — encodes (zap_type, beam_dir) into the
// canonical ZAP glyph range. map_glyphinfo's ZAP branch decodes both
// the cmap sym (S_vbeam+dir) and the color (zapcolors[zap_type]).
function zapdir_to_glyph(dx, dy, beam_type) {
    if (beam_type >= 8) beam_type = 0;
    const dir = (dx === dy) ? 2 : ((dx && dy) ? 3 : (dx ? 1 : 0));
    return ((beam_type << 2) | dir) + GLYPH_ZAP_OFF;
}
const destroy_strings = [
    ['freezes and shatters', 'freeze and shatter', 'shattered potion'],
    ['boils and explodes', 'boil and explode', 'boiling potion'],
    ['ignites and explodes', 'ignite and explode', 'exploding potion'],
    ['catches fire and burns', 'catch fire and burn', 'burning scroll'],
    ['catches fire and burns', '', 'burning book'],
    ['turns to dust and vanishes', '', ''],
    ['breaks apart and explodes', '', 'exploding wand'],
];
// ── Local helpers ──
// resists_*, defended, nonliving, is_demon, is_vampshifter, is_rider,
// is_undead all imported from mondata.js
// ── hero_shock_resistance — C ref: youprop.h Shock_resistance
export function hero_shock_resistance() {
    // C uses Shock_resistance (which includes polymorph/form bits via properties).
    // JS property propagation is still incomplete in some polymorph paths, so
    // include current-form electrical resistance for C-faithful behavior.
    return Shock_resistance() || resists_elec(game.youmonst);
}
function normal_shape(_mon) { /* stub */ }
// C ref: teleport.c:2262 u_teleport_mon
async function u_teleport_mon(mtmp, give_feedback) {
    if (mtmp.ispriest && in_rooms(mtmp.mx, mtmp.my, TEMPLE)) {
        if (give_feedback) await pline(`${Monnam(mtmp)} resists your magic!`);
        return false;
    } else if (engulfing_u(mtmp) && noteleport_level(mtmp)) {
        if (give_feedback) await You(`are no longer inside ${mon_nam(mtmp)}!`);
        unstuck(mtmp);
        await rloc(mtmp, RLOC_MSG);
    } else if ((is_rider(mtmp.data) || control_teleport(mtmp.data))
               && rn2(13)) {
        const cc = {};
        if (enexto(cc, game.u.ux, game.u.uy, mtmp.data)) {
            await rloc_to(mtmp, cc.x, cc.y);
        } else {
            await rloc(mtmp, RLOC_MSG);
        }
    } else {
        if (!await rloc(mtmp, RLOC_MSG))
            return false;
    }
    return true;
}
// ── get_mon_location — C ref: zap.c:692 ──
function get_mon_location(mon, result) {
    if (mon === game.youmonst || (game.u.usteed && mon === game.u.usteed)) {
        result.x = game.u.ux;
        result.y = game.u.uy;
        return true;
    } else if (mon.mx > 0) {
        result.x = mon.mx;
        result.y = mon.my;
        return true;
    }
    result.x = 0; result.y = 0;
    return false;
}
// adtyp_to_prop: imported from mkobj.js
// u_adtyp_resistance_obj: imported from mkobj.js
// inventory_resistance_check: imported from mkobj.js
// ── destroy_items — C ref: zap.c:5957 ──
// destroyable: imported from mkobj.js
// maybe_destroy_item: imported from mkobj.js
// destroy_items: imported from mkobj.js
// ── recharge_item — simplified for RNG parity ──
function recharge_item(obj, curse_bless) {
    if (obj.oclass === WAND_CLASS) {
        const n = rn2(7);
        obj.spe = (obj.spe || 0) + n + 1;
    } else if (obj.oclass === RING_CLASS) {
        const n = rn2(7);
        obj.spe = (obj.spe || 0) + n + 1;
    }
}
// ── cancel_item — C ref: zap.c:1239 ──
function cancel_item(obj) {
    if (!obj) return;
    const otyp = obj.otyp;
    // Simplified: cancel the magical properties
    if (game.objects[otyp]?.oc_magic
        || (obj.spe && (obj.oclass === ARMOR_CLASS
                        || obj.oclass === WEAPON_CLASS))
        || otyp === POT_OIL) {
        const cancelled_spe = (obj.oclass === WAND_CLASS) ? -1 : 0;
        if (obj.spe !== cancelled_spe
            && otyp !== WAN_CANCELLATION) {
            obj.spe = cancelled_spe;
        }
    }
    // Uncurse/unbless
    obj.cursed = false;
    obj.blessed = false;
}
// drain_item: imported from mon.js
function blank_novel(obj) {
    obj.novelidx = 0;
}
// ── lightdamage — C ref: zap.c:3021 ──
// C ref: zap.c:3021 lightdamage() — light hurts gremlins
async function lightdamage(obj, ordinary, amt) {
    let dmg = amt;
    if (dmg && game.u?.umonnum === PM_GREMLIN) {
        dmg = rnd(dmg);
        if (dmg > 10) dmg = 10 + rnd(dmg - 10);
        if (dmg > 20) dmg = 20;
        await pline(`Ow, that light hurts${(dmg > 2 || game.u.mh <= 5) ? '!' : '.'}`);
        if (obj.oclass === SCROLL_CLASS || obj.oclass === SPBOOK_CLASS)
            ordinary = false;
        const how = (obj.oclass === SPBOOK_CLASS) ? 'spell of light' : xname(obj);
        const buf = `${ordinary ? 'zapped' : 'blasted'} self with ${how}`;
        await losehp(Maybe_Half_Phys(dmg), buf, 0);
    }
    return dmg;
}
// ── flashburn — C ref: zap.c:3055 ──
async function flashburn(duration, via_lightning) {
    // C ref: zap.c:3055 flashburn()
    if (!resists_blnd(game.youmonst)) {
        await You('are blinded by the flash!');
        await make_blinded(duration, false);
        if (!Blind()) {
            await Your('vision clears.');
        }
        return true;
    }
    if (!via_lightning) {
        // C: when blindness is resisted by special equipment, show shield effect.
        // We currently lack a dedicated resist-by-artifact predicate; preserve
        // visible feedback for non-lightning flash resistance.
        shieldeff(game.u.ux, game.u.uy);
        return true;
    }
    return false;
}
// ── bounce_dir — C ref: zap.c:4657 ──
function bounce_dir(sx, sy, ddx_ref, ddy_ref, bchance) {
    if (!ddx_ref.v || !ddy_ref.v || (bchance > 0 && !rn2(bchance))) {
        ddx_ref.v = -(ddx_ref.v);
        ddy_ref.v = -(ddy_ref.v);
    } else {
        const g = game;
        const levl = g.level?.locations;
        let bounce = 0;
        const lsy = sy - ddy_ref.v;
        const lsx = sx - ddx_ref.v;
        if (isok(sx, lsy) && levl) {
            const rmn = levl[sx]?.[lsy]?.typ || 0;
            if (ZAP_POS(rmn) && !closed_door(sx, lsy)) bounce = 1;
        }
        if (isok(lsx, sy) && levl) {
            const rmn = levl[lsx]?.[sy]?.typ || 0;
            if (ZAP_POS(rmn) && !closed_door(lsx, sy)) {
                if (!bounce || rn2(2)) bounce = 2;
            }
        }
        switch (bounce) {
        case 0:
            ddx_ref.v = -(ddx_ref.v);
            /* FALLTHROUGH */
        case 1:
            ddy_ref.v = -(ddy_ref.v);
            break;
        case 2:
            ddx_ref.v = -(ddx_ref.v);
            break;
        }
    }
}
// ── release_hold — C ref: zap.c:578 ──
async function release_hold() {
    const mtmp = game.u.ustuck;
    if (!mtmp) return;
    // Simplified release
    game.u.ustuck = null;
    await You("are released.");
}
// ── probe_objchain — C ref: zap.c:612 ──
function probe_objchain(otmp) {
    for (; otmp; otmp = otmp.nobj) {
        // observe_object(otmp) -- treat as "seen"
        otmp.dknown = true;
    }
}
// ── probe_monster — C ref: zap.c:626 ──
async function probe_monster(mtmp) {
    // mstatusline(mtmp) -- stub
    if (game.notonhead) return;
    if (mtmp.minvent) {
        probe_objchain(mtmp.minvent);
    } else {
        await pline(`${Monnam(mtmp)} is not carrying anything.`);
    }
}
// ── boxlock_invent — C ref: zap.c:2682 ──
function boxlock_invent(obj) {
    // (un)lock carried boxes -- simplified
    // for (otmp = invent; otmp; otmp = otmp.nobj) { if (Is_box(otmp)) boxlock(otmp, obj); }
}
// ── zap_steed — C ref: zap.c:3082 ──
async function zap_steed(obj) {
    if (!game.u.usteed) return false;
    const steed = game.u.usteed;
    if (!game.bhitpos) game.bhitpos = { x: 0, y: 0 };
    game.bhitpos.x = steed.mx;
    game.bhitpos.y = steed.my;
    game.notonhead = false;
    switch (obj.otyp) {
    case WAN_PROBING:
        await probe_monster(steed);
        learnwand(obj);
        return true;
    case WAN_TELEPORTATION: case SPE_TELEPORT_AWAY:
        // tele() -- you go together, stub
        return true;
    case WAN_MAKE_INVISIBLE:
    case WAN_CANCELLATION: case SPE_CANCELLATION:
    case WAN_POLYMORPH: case SPE_POLYMORPH:
    case WAN_STRIKING: case SPE_FORCE_BOLT:
    case WAN_SLOW_MONSTER: case SPE_SLOW_MONSTER:
    case WAN_SPEED_MONSTER:
    case SPE_HEALING: case SPE_EXTRA_HEALING:
    case SPE_DRAIN_LIFE:
    case WAN_OPENING: case SPE_KNOCK:
        await bhitm(steed, obj);
        return true;
    default:
        return false;
    }
}
// ── maybe_explode_trap — C ref: zap.c:3589 ──
async function maybe_explode_trap(ttmp, otmp, learn_it_ref) {
    if (!ttmp || !otmp)
        return;
    if (otmp.otyp === WAN_CANCELLATION || otmp.otyp === SPE_CANCELLATION) {
        const x = ttmp.tx, y = ttmp.ty;
        if (undestroyable_trap(ttmp.ttyp)) {
            shieldeff(x, y);
            if (cansee(x, y)) {
                ttmp.tseen = true;
                newsym(x, y);
                learn_it_ref.v = true;
            }
        } else if (is_magical_trap(ttmp.ttyp)) {
            const seeit = cansee(x, y);
            /* note: this explosion mustn't destroy otmp */
            await explode(x, y, -WAN_CANCELLATION,
                    20 + c_d(3, 6), TRAP_EXPLODE, EXPL_MAGICAL);
            deltrap(ttmp);
            newsym(x, y);
            if (seeit)
                learn_it_ref.v = true;
        }
    }
}
function trap_to_defsym(ttyp) {
    return S_arrow_trap + ttyp - 1;
}
// ── zap_map — C ref: zap.c:3623 ──
// C ref: zap.c:959 obj_resists — RNG: rn2
export function obj_resists(obj, ochance, achance) {
    if (!obj) return false;
    if (obj.otyp === AMULET_OF_YENDOR
        || obj.otyp === SPE_BOOK_OF_THE_DEAD
        || obj.otyp === CANDELABRUM_OF_INVOCATION
        || obj.otyp === BELL_OF_OPENING
        || (obj.otyp === CORPSE && is_rider(mons[obj.corpsenm]))) {
        return true;
    } else {
        // C ref: zap.c obj_resists — rn2(100) only in the else branch
        const chance = rn2(100);
        return chance < (obj.oartifact ? achance : ochance);
    }
}
// ── zap_map — C ref: zap.c:3623 ──
async function zap_map(x, y, obj) {
    const g = game;
    let ttmp = t_at(x, y);
    let dbx = x, dby = y;
    const learn_it_ref = { v: false };
    /* cancellation */
    await maybe_explode_trap(ttmp, obj, learn_it_ref);
    ttmp = t_at(x, y); /* refresh in case trap was altered or is gone */
    if (g.u.dz > 0) { /* zapping down */
        const e = engr_at(x, y);
        /* subset of engraving effects */
        if (e && e.engr_type !== 1 /* HEADSTONE */) {
            switch (obj.otyp) {
            case WAN_POLYMORPH:
            case SPE_POLYMORPH:
                del_engr(e);
                const { buf: ebuf, pristinebuf } = random_engraving();
                await make_engr_at(x, y, ebuf, pristinebuf, g.moves, 0);
                break;
            case WAN_CANCELLATION:
            case SPE_CANCELLATION:
            case WAN_MAKE_INVISIBLE:
                del_engr(e);
                break;
            case WAN_TELEPORTATION:
            case SPE_TELEPORT_AWAY:
                rloc_engr(e);
                break;
            case SPE_STONE_TO_FLESH:
                if (e.engr_type === 2 /* ENGRAVE */) {
                    await pline_The(Hallucination()
                                  ? "floor runs like butter!"
                                  : "edges on the floor get smoother.");
                    wipe_engr_at(x, y, c_d(2, 4), true);
                }
                break;
            case WAN_STRIKING:
            case SPE_FORCE_BOLT:
                wipe_engr_at(x, y, c_d(2, 4), true);
                break;
            default:
                break;
            }
        }
    } else if (!g.u.dz) {
        const loc = g.level.at(x, y);
        const ltyp = loc.typ;
        const dbRes = find_drawbridge(dbx, dby);
        if (dbRes.found) {
            dbx = dbRes.x; dby = dbRes.y;
            switch (obj.otyp) {
            case WAN_OPENING:
            case SPE_KNOCK:
                /* dbwall: 'closed door' of raised drawbridge */
                if (is_db_wall(x, y)) {
                    if (cansee(dbx, dby) || cansee(x, y))
                        learn_it_ref.v = true;
                    await open_drawbridge(dbx, dby);
                }
                break;
            case WAN_LOCKING:
            case SPE_WIZARD_LOCK:
                /* drawbridge_down: span of lowered drawbridge */
                if ((cansee(dbx, dby) || cansee(x, y))
                    && g.level.at(dbx, dby).typ === DRAWBRIDGE_DOWN)
                    learn_it_ref.v = true;
                await close_drawbridge(dbx, dby);
                break;
            case WAN_STRIKING:
            case SPE_FORCE_BOLT:
                if (ltyp !== DRAWBRIDGE_UP) {
                    learn_it_ref.v = true;
                    await destroy_drawbridge(dbx, dby);
                }
                break;
            }
        }
    }
    if (obj.otyp === WAN_PROBING) {
        const loc = g.level.at(x, y);
        let ltyp = loc.typ;
        show_map_spot(x, y, false);
        ltyp = loc.typ;
        /* secret door gets revealed, converted into regular door */
        if (ltyp === SDOOR) {
            cvt_sdoor_to_door(loc);
            recalc_block_point(x, y);
            newsym(x, y);
            if (cansee(x, y)) {
                await pline("Probing reveals a secret door.");
                learn_it_ref.v = true;
            }
        } else if (ltyp === SCORR) {
            loc.typ = CORR;
            unblock_point(x, y);
            newsym(x, y);
            await pline("Probing exposes a secret corridor.");
            learn_it_ref.v = true;
        } else if (ltyp === ICE || (ltyp >= 33 && ltyp <= 37) /* furniture */) {
            if (g.u.dz > 0) {
                await force_decor(true);
                learn_it_ref.v = true;
            }
        }
        if (ttmp) {
            const t_already_seen = ttmp.tseen;
            const hallu = Hallucination();
            ttmp.tseen = true;
            newsym(x, y);
            if (!t_already_seen || hallu) {
                const ttmpname = trapname(ttmp.ttyp, false);
                const use_the = !hallu ? (ttmp.ttyp === VIBRATING_SQUARE
                                    && Invocation_lev())
                                 : !rn2(4);
                await You("find %s%c",
                    use_the ? the(ttmpname) : an(ttmpname),
                    use_the ? '!' : '.');
                learn_it_ref.v = !hallu;
            }
        }
    }
    if (learn_it_ref.v)
        learnwand(obj);
}
// ── bhitpile — C ref: zap.c:2428 ──
// C ref: zap.c:2428 bhitpile — iterate floor objects at (tx,ty) for wand/spell hit
async function bhitpile(obj, fhito, tx, ty, zz) {
    if (!fhito) return 0;
    const firstObj = obj_at(tx, ty);
    if (!firstObj) return 0;
    // C ref: zap.c:2465 — reset material accumulator before per-pile zaps.
    game.poly_zapped = -1;
    const hidingunder = (zz !== 0
                         && !!game.u?.uundetected
                         && hides_under(game.youmonst?.data));
    let first = true;
    let hitanything = 0;
    for (let otmp = firstObj; otmp; ) {
        const next_obj = otmp.nexthere;
        if (hidingunder) {
            if (first) {
                first = false;
                if (zz > 0) {
                    otmp = next_obj;
                    continue;
                }
            } else if (zz < 0) {
                otmp = next_obj;
                continue;
            }
        }
        if (otmp.where !== OBJ_FLOOR || otmp.ox !== tx || otmp.oy !== ty) {
            otmp = next_obj;
            continue;
        }
        hitanything += await fhito(otmp, obj);
        otmp = next_obj;
    }
    return hitanything;
}
// ── zap_over_floor — C ref: zap.c:5134 ──
async function zap_over_floor(x, y, type, shopdamage_ref, ignoremon, exploding_wand_typ) {
    const damgtype = zaptype(type) % 10;
    let rangemod = 0;
    const levl = game.level?.locations;
    const loc = levl?.[x]?.[y];
    if (!loc) return 0;
    switch (damgtype) {
    case ZT_FIRE:
        // Ice melting, pool evaporation, fountain steam, web burning
        // Simplified for RNG parity -- the key RNG calls are:
        if (loc.typ === 6 /* ICE */) {
            // melt_ice(x, y, null) -- stub
        } else if (loc.typ === 10 /* POOL */) {
            // create_gas_cloud(x, y, rnd(5), 0)
            // For RNG parity, consume the rnd(5) even though we stub
            rnd(5);
            rangemod -= 3;
        }
        break;
    case ZT_COLD:
        // Freeze water/lava
        if (loc.typ === 10 /* POOL */ || loc.typ === 11 /* MOAT */) {
            rangemod -= 3;
        }
        break;
    case ZT_POISON_GAS:
        if (ZAP_POS(loc.typ)) {
            await create_gas_cloud(x, y, 1, 8);
        }
        break;
    case ZT_LIGHTNING:
    case ZT_ACID:
        // Iron bars dissolution
        break;
    default:
        break;
    }
    // Secret door reveal
    if (loc.typ === 7 /* SDOOR */) {
        loc.typ = 8; // DOOR
        newsym(x, y);
    }
    // Closed door absorbs zap
    if (closed_door(x, y)) {
        rangemod = -1000;
        switch (damgtype) {
        case ZT_FIRE:
            loc.doormask = 1; // D_NODOOR
            newsym(x, y);
            break;
        case ZT_COLD:
            loc.doormask = 1; // D_NODOOR
            newsym(x, y);
            break;
        case ZT_LIGHTNING:
            loc.doormask = 16; // D_BROKEN
            newsym(x, y);
            break;
        default:
            break;
        }
    }
    // Burn floor objects for fire
    if (damgtype === ZT_FIRE) {
        burn_floor_objects(x, y, false, type > 0);
    }
    if (!ignoremon) {
        const mon = m_at(x, y);
        if (mon) wakeup(mon, type >= 0);
    }
    return rangemod;
}
// ── burn_floor_objects — C ref: zap.c:4591 ──
function burn_floor_objects(x, y, give_feedback, u_caused) {
    let cnt = 0;
    const SCROLL_CLASS = 7, SPBOOK_CLASS = 11, FOOD_CLASS = 4;
    const SCR_FIRE = 227, SPE_FIREBALL = 367;
    const GLOB_OF_GREEN_SLIME = 216; // food otyp
    for (let obj = obj_at(x, y); obj; ) {
        const obj2 = obj.nexthere;
        if (obj.oclass === SCROLL_CLASS || obj.oclass === SPBOOK_CLASS
            || (obj.oclass === FOOD_CLASS && obj.otyp === GLOB_OF_GREEN_SLIME)) {
            if (obj.otyp === SCR_FIRE || obj.otyp === SPE_FIREBALL
                || obj_resists(obj, 2, 100)) {
                obj = obj2;
                continue;
            }
            const scrquan = obj.quan || 1;
            let delquan = 0;
            for (let i = scrquan; i > 0; i--)
                if (!rn2(3))
                    delquan++;
            if (delquan) {
                if (u_caused) {
                    // useupf: simplified — reduce quantity
                    if (delquan < scrquan) {
                        obj.quan = scrquan - delquan;
                        obj.owt = weight(obj);
                    } else {
                        obj_extract_self(obj);
                        dealloc_obj(obj);
                    }
                } else if (delquan < scrquan) {
                    obj.quan = scrquan - delquan;
                    obj.owt = weight(obj);
                } else {
                    obj_extract_self(obj);
                    dealloc_obj(obj);
                }
                cnt += delquan;
            }
        }
        obj = obj2;
    }
    return cnt;
}
// ── zap_updown — C ref: zap.c:3214 ──
async function zap_updown(obj) {
    let disclose = false;
    const x = game.u.ux, y = game.u.uy;
    switch (obj.otyp) {
    case WAN_PROBING:
        if (game.u.dz < 0) {
            await You("probe towards the ceiling.");
        } else {
            await bhitpile(obj, bhito, x, y, game.u.dz);
            await zap_map(x, y, obj);
            await You("probe beneath the floor.");
        }
        return true;
    case WAN_OPENING: case SPE_KNOCK:
        if (game.u.dz > 0 && game.u.utrap) {
            // openholdingtrap() -- stub
        }
        break;
    case WAN_STRIKING: case SPE_FORCE_BOLT:
        if (game.u.dz < 0 && rn2(3)) {
            const dmg = rnd(6);
            await pline("A rock is dislodged from the ceiling and falls on your head.");
            await losehp(dmg, "falling rock", 'KILLED_BY_AN');
        }
        break;
    case WAN_LOCKING: case SPE_WIZARD_LOCK:
        break;
    case SPE_STONE_TO_FLESH:
        if (game.u.dz < 0) {
            await pline("Blood drips on your face.");
        }
        break;
    default:
        break;
    }
    if (game.u.dz > 0) {
        await bhitpile(obj, bhito, x, y, game.u.dz);
        await zap_map(x, y, obj);
    }
    return disclose;
}
// ── stone_to_flesh_obj — C ref: zap.c:1993 ──
function stone_to_flesh_obj(obj) {
    // Simplified: only handles material check and obj_resists
    const mat = game.objects[obj.otyp]?.oc_material;
    if (mat !== 7 /* MINERAL */ && mat !== 8 /* GEMSTONE */)
        return 0;
    if (obj_resists(obj, 2, 98))
        return 0;
    // Full poly_obj and animate_statue not yet available
    return 0;
}
// ── poly_obj — C ref: zap.c:1702 ──
// Polymorph an object into a different object of the same class.
function poly_obj(obj, id) {
    if (!obj) return obj;
    const g = game;
    let otmp;
    const can_merge = (id === STRANGE_OBJECT);
    const obj_location = obj.where;
 
    if (id === STRANGE_OBJECT) {
        // Preserve magic/non-magic status — retry up to 3 times
        let try_limit = 3;
        const magic_obj = g.objects[obj.otyp]?.oc_magic ? 1 : 0;
        otmp = null;
        do {
            if (otmp) delobj(otmp);
            otmp = mkobj(obj.oclass, false);
        } while (--try_limit > 0
                 && (g.objects[otmp.otyp]?.oc_magic ? 1 : 0) !== magic_obj);
    } else {
        otmp = mksobj(id, false, false);
    }
    if (!otmp) return obj;
 
    // Preserve quantity
    otmp.quan = obj.quan || 1;
    otmp.no_charge = obj.no_charge;
    if (obj_location === OBJ_INVENT)
        otmp.invlet = obj.invlet;
 
    // C charged_objs: WAND_CLASS, WEAPON_CLASS, ARMOR_CLASS.
    if (otmp.oclass === WAND_CLASS
        || otmp.oclass === WEAPON_CLASS
        || otmp.oclass === ARMOR_CLASS)
        otmp.spe = obj.spe;
    otmp.recharged = obj.recharged;
    otmp.cursed = obj.cursed;
    otmp.blessed = obj.blessed;
 
    // Preserve erosion where applicable
    if (erosion_matters(otmp)) {
        if (is_flammable(otmp) || is_rustprone(otmp) || is_crackable(otmp))
            otmp.oeroded = obj.oeroded || 0;
        if (is_corrodeable(otmp) || is_rottable(otmp))
            otmp.oeroded2 = obj.oeroded2 || 0;
        if (is_damageable(otmp))
            otmp.oerodeproof = obj.oerodeproof;
    }
    if (obj.otrapped && Is_box(otmp)) otmp.otrapped = 1;
    if (obj.opoisoned && is_poisonable(otmp)) otmp.opoisoned = 1;
 
    // Crocodile corpse → boots
    if (id === STRANGE_OBJECT && obj.otyp === CORPSE && obj.corpsenm === PM_CROCODILE) {
        otmp.otyp = LOW_BOOTS;
        otmp.oclass = ARMOR_CLASS;
        otmp.spe = 0;
        otmp.oeroded = 0;
        otmp.oerodeproof = true;
        otmp.quan = 1;
        otmp.cursed = false;
    }
 
    // Quantity merge for stacks
    if ((otmp.quan || 1) > 1 && (!g.objects[otmp.otyp]?.oc_merge
        || (can_merge && (otmp.quan || 1) > rn2(1000))))
        otmp.quan = 1;
 
    // Per-class adjustments
    switch (otmp.oclass) {
    case TOOL_CLASS:
        if (otmp.otyp === MAGIC_LAMP) { otmp.otyp = OIL_LAMP; otmp.age = 1500; }
        else if (otmp.otyp === MAGIC_MARKER) { otmp.recharged = 1; }
        break;
    case WAND_CLASS:
        while (otmp.otyp === WAN_WISHING || otmp.otyp === WAN_POLYMORPH)
            otmp.otyp = rnd_class(WAN_LIGHT, WAN_LIGHTNING);
        if ((otmp.recharged || 0) < rn2(7)) otmp.recharged = (otmp.recharged || 0) + 1;
        break;
    case POTION_CLASS:
        while (otmp.otyp === POT_POLYMORPH)
            otmp.otyp = rnd_class(POT_GAIN_ABILITY, POT_WATER);
        break;
    case SPBOOK_CLASS:
        while (otmp.otyp === SPE_POLYMORPH)
            otmp.otyp = rnd_class(g.bases_spbook ?? 0, SPE_BLANK_PAPER);
        if (otmp.otyp !== SPE_BLANK_PAPER && otmp.otyp !== SPE_NOVEL) {
            otmp.spestudied = (obj.spestudied || 0) + 1;
            if (otmp.spestudied > 3) { // MAX_SPELL_STUDY
                otmp.otyp = SPE_BLANK_PAPER;
                otmp.spestudied = rn2(otmp.spestudied);
            }
        }
        break;
    case GEM_CLASS:
        if ((otmp.quan || 1) > rnd(4)
            && (g.objects[obj.otyp]?.oc_material || 0) === 10 // MINERAL
            && (g.objects[otmp.otyp]?.oc_material || 0) !== 10) {
            otmp.otyp = ROCK;
            otmp.quan = Math.trunc((otmp.quan || 1) / 2);
        }
        break;
    }
 
    otmp.owt = weight(otmp);
 
    // Replace old object with new one.
    // C ref: mkobj.c:replace_object() + zap.c:poly_obj() floor path.
    if (obj_location === OBJ_FLOOR) {
        // Literal in-place swap: preserve chain position and avoid
        // remove/place side-effects from extract+place.
        otmp.where = OBJ_FLOOR;
        otmp.ox = obj.ox;
        otmp.oy = obj.oy;
        otmp.nobj = obj.nobj || null;
        otmp.nexthere = obj.nexthere || null;
        obj.nobj = otmp;
        obj.nexthere = otmp;
 
        const objs = g.level?.objects || [];
        for (let i = 0; i < objs.length; i++) {
            const cur = objs[i];
            if (cur === obj) {
                objs[i] = otmp;
                continue;
            }
            if (cur?.nobj === obj) cur.nobj = otmp;
            if (cur?.nexthere === obj) cur.nexthere = otmp;
        }
 
        obj.where = OBJ_FREE;
        obj.nobj = null;
        obj.nexthere = null;
    } else if (obj_location === OBJ_INVENT) {
        // Replace in inventory — simplified
        obj_extract_self(obj);
        otmp.nobj = g.invent;
        g.invent = otmp;
        otmp.where = OBJ_INVENT;
    } else if (obj_location === OBJ_MINVENT) {
        obj_extract_self(obj);
    }
 
    // C ref: zap.c:1987 — poly_obj() always delobj()'s the original object.
    // This consumes obj_resists(0,0) and must occur even after in-place swap.
    delobj(obj);
 
    return otmp;
}
// ── do_osshock — C ref: zap.c:1637 ──
async function do_osshock(obj) {
    game.obj_zapped = true;
    if (game.poly_zapped < 0) {
        for (let i = obj.quan || 1; i > 0; i--) {
            if (!rn2((game.u?.uluck ?? 0) + 45)) {
                game.poly_zapped = game.objects[obj.otyp]?.oc_material || 0;
                break;
            }
        }
    }
 
    if (obj.quan > 1) {
        if (obj.quan > 0x7fffffff) {
            obj = splitobj(obj, rnd(30000));
        } else {
            obj = splitobj(obj, rnd((obj.quan | 0) - 1));
        }
    }
 
    if (costly_spot(obj.ox, obj.oy)) {
        if (game.u?.ushops) {
            await addtobill(obj, false, false, false);
        } else {
            await stolen_value(obj, obj.ox, obj.oy, false, false);
        }
    }
 
    delobj(obj);
}
// ── obj_unpolyable — C ref: zap.c:1678 ──
function obj_unpolyable(obj) {
    if (obj?.otyp === WAN_POLYMORPH
        || obj?.otyp === SPE_POLYMORPH
        || obj?.otyp === POT_POLYMORPH
        || obj?.otyp === AMULET_OF_UNCHANGING
        || obj === game.u?.uball
        || obj === game.u?.uskin)
        return true;
    return obj_resists(obj, 5, 95);
}
// ── zaptype — C ref: zap.c:89 ──
function zaptype(type) {
    if (type <= -30 && -39 <= type) type += 30;
    type = Math.abs(type);
    return type;
}
// ── flash_str — C ref: zap.c:6422 ──
function flash_str(fltyp) {
    if (fltyp >= 0 && fltyp < flash_types.length)
        return flash_types[fltyp] || 'magical energy';
    return 'magical energy';
}
// ── zappable — C ref: zap.c:2514 ──
export async function zappable(wand) {
    if (wand.spe < 0 || (wand.spe === 0 && rn2(WAND_WREST_CHANCE)))
        return 0;
    if (wand.spe === 0)
        await You('wrest one last charge from the worn-out wand.');
    wand.spe--;
    return 1;
}
// ── backfire — C ref: zap.c:2600 ──
async function backfire(otmp) {
    otmp.in_use = true;
    await pline(`${The(xname(otmp))} suddenly explodes!`);
    const dmg = c_d(otmp.spe + 2, 6);
    await losehp(dmg, 'exploding wand', 'KILLED_BY_AN');
    useupall(otmp);
}
// ── zap_ok — C ref: zap.c:2613 ──
function zap_ok(obj) {
    if (obj && obj.oclass === WAND_CLASS) return GETOBJ_SUGGEST;
    return GETOBJ_EXCLUDE;
}
// ── learnwand — C ref: zap.c:123 ──
export function learnwand(obj) {
    if (obj.oclass !== SPBOOK_CLASS) {
        if (game.objects[obj.otyp]?.oc_name_known) {
            // C ref: observe_object — already known, mark as seen
            obj.dknown = 1;
        } else {
            // discover the type if we can see the item
            if (!Blind()) obj.dknown = 1;
            if (obj.dknown) {
                makeknown(obj.otyp);
            }
        }
        update_inventory();
    }
}
// ── exclam — C ref: zap.c:3542 ──
export function exclam(force) {
    return (force < 0) ? '?' : (force <= 4) ? '.' : '!';
}
// ── hit — C ref: zap.c:3551 ──
export async function hit(str, mtmp, force) {
    const g = game;
    const verbosely = (mtmp === g.youmonst
        || (g.flags?.verbose && (cansee(g.bhitpos?.x, g.bhitpos?.y)
            || canspotmon(mtmp))));
    await pline(`${The(str)} ${vtense(str, 'hit')} ${verbosely ? mon_nam(mtmp) : 'it'}${force}`);
}
// ── miss — C ref: zap.c:3566 ──
export async function miss(str, mtmp) {
    const g = game;
    await pline(`${The(str)} ${vtense(str, 'miss')} ${
        ((cansee(g.bhitpos?.x, g.bhitpos?.y) || canspotmon(mtmp)) && g.flags?.verbose)
            ? mon_nam(mtmp) : 'it'}.`);
}
// ── spell_damage_bonus — C ref: zap.c:3475 ──
export function spell_damage_bonus(dmg) {
    const intell = ACURR(A_INT);
    if (intell <= 9) {
        if (dmg > 1) dmg = (dmg <= 3) ? 1 : dmg - 3;
    } else if (intell <= 13 || game.u.ulevel < 5) { /* noop */ }
    else if (intell <= 18) dmg += 1;
    else if (intell <= 24 || game.u.ulevel < 14) dmg += 2;
    else dmg += 3;
    return dmg;
}
// ── spell_hit_bonus — C ref: zap.c:3504 ──
function spell_hit_bonus(skill) {
    let hit_bon = 0;
    const dex = ACURR(A_DEX);
    switch (P_SKILL(spell_skilltype(skill))) {
    case P_ISRESTRICTED:
    case P_UNSKILLED:
        hit_bon = -4;
        break;
    case P_BASIC:
        hit_bon = 0;
        break;
    case P_SKILLED:
        hit_bon = 2;
        break;
    case P_EXPERT:
        hit_bon = 3;
        break;
    }
    if (dex < 4)
        hit_bon -= 3;
    else if (dex < 6)
        hit_bon -= 2;
    else if (dex < 8)
        hit_bon -= 1;
    else if (dex < 14)
        hit_bon -= 0;
    else
        hit_bon += dex - 14;
    return hit_bon;
}
// ── zap_hit — C ref: zap.c:4698 ──
export function zap_hit(ac, type) {
    const chance = rn2(20);
    const spell_bonus = type ? spell_hit_bonus(type) : 0;
    if (!chance) return rnd(10) < ac + spell_bonus;
    // C: AC_VALUE(AC) = ((AC) >= 0 ? (AC) : -rnd(-(AC)))
    ac = (ac >= 0) ? ac : -rnd(-ac);
    return (3 - chance < ac + spell_bonus);
}
// ── skiprange — C ref: zap.c:3574 ──
function skiprange(range, result) {
    const tr = Math.trunc(range / 4);
    const tmp = range - ((tr > 0) ? rnd(tr) : 0);
    result.start = tmp;
    let end = tmp - (Math.trunc(tmp / 4) * rnd(3));
    if (end >= tmp) end = tmp - 1;
    result.end = end;
}
// ── do_enlightenment_effect — C ref: zap.c:2525 ──
async function do_enlightenment_effect() {
    await You_feel('self-knowledgeable...');
    // display_nhwindow(WIN_MESSAGE, FALSE) -- stub
    // enlightenment(MAGICENLIGHTENMENT, ENL_GAMEINPROGRESS) -- stub
    await pline_The('feeling subsides.');
    exercise(A_WIS, true);
}
// ── zapnodir — C ref: zap.c:2539 ──
async function zapnodir(obj) {
    const g = game;
    let known = false;
    switch (obj.otyp) {
    case WAN_LIGHT: case SPE_LIGHT:
        known = !!(obj.dknown && !g.u?.prop?.BLINDED);
        await litroom(true, obj);
        await lightdamage(obj, true, 5);
        break;
    case WAN_SECRET_DOOR_DETECTION: case SPE_DETECT_UNSEEN:
        known = !!obj.dknown;
        await findit();
        break;
    case WAN_STASIS:
        if (g.level?.flags) {
            g.level.flags.stasis_until = (g.moves || 0) + rn1(21, 10);
        }
        break;
    case WAN_CREATE_MONSTER:
        { const cnt = rn2(23) ? 1 : rn1(7, 2); }
        // create_critters(cnt, null, false) -- stub
        break;
    case WAN_WISHING:
        if ((g.u?.uluck ?? 0) + rn2(5) < 0) {
            await pline('Unfortunately, nothing happens.');
        } else {
            known = !!obj.dknown;
            await makewish();
        }
        break;
    case WAN_ENLIGHTENMENT:
        known = !!obj.dknown;
        await do_enlightenment_effect();
        break;
    default: break;
    }
    if (known) {
        if (!game.objects[obj.otyp]?.oc_name_known) { more_experienced(0, 10); }
        learnwand(obj);
    }
}
// ── zapyourself — C ref: zap.c:2700 ──
export async function zapyourself(obj, ordinary) {
    let learn_it = false, damage = 0;
    let orig_dmg = 0;
    switch (obj.otyp) {
    case WAN_STRIKING: case SPE_FORCE_BOLT:
        learn_it = true;
        if (ordinary) { await You('bash yourself!'); damage = c_d(2, 12); }
        else damage = c_d(1 + obj.spe, 6);
        exercise(A_STR, false);
        break;
    case WAN_LIGHTNING: {
        learn_it = true;
        orig_dmg = c_d(12, 6);
        if (!hero_shock_resistance()) {
            await You('shock yourself!');
            damage = orig_dmg;
            exercise(A_CON, false);
        } else {
            shieldeff(game.u.ux, game.u.uy);
            await You('zap yourself, but seem unharmed.');
        }
        await destroy_items(game.youmonst || game.u, AD_ELEC, orig_dmg);
        await flashburn(rnd(100), true);
        break;
    }
    case SPE_FIREBALL:
        await You('explode a fireball on top of yourself!');
        await explode(game.u.ux, game.u.uy, 11, c_d(6, 6), WAND_CLASS, 1 /* EXPL_FIERY */);
        break;
    case WAN_FIRE:
        learn_it = true;
        orig_dmg = c_d(12, 6);
        // Fire_resistance check would go here
        await pline("You've set yourself afire!");
        damage = orig_dmg;
        // burn_away_slime(), await burnarmor(), destroy_items(), ignite_items()
        await destroy_items(game.youmonst || game.u, AD_FIRE, orig_dmg);
        break;
    case WAN_COLD: case SPE_CONE_OF_COLD:
        learn_it = true;
        orig_dmg = c_d(12, 6);
        // Cold_resistance check would go here
        await You('imitate a popsicle!');
        damage = orig_dmg;
        await destroy_items(game.youmonst || game.u, AD_COLD, orig_dmg);
        break;
    case WAN_MAGIC_MISSILE: case SPE_MAGIC_MISSILE:
        learn_it = true;
        damage = c_d(4, 6);
        await pline("Idiot!  You've shot yourself!");
        break;
    case WAN_POLYMORPH: case SPE_POLYMORPH:
        if (!Unchanging()) {
            learn_it = true;
            await polyself(POLY_NOFLAGS);
        }
        break;
    case WAN_CANCELLATION: case SPE_CANCELLATION:
        cancel_monst(game.youmonst, obj, true, true, true);
        break;
    case SPE_DRAIN_LIFE:
        damage = 0;
        break;
    case WAN_MAKE_INVISIBLE:
        rn1(15, 31);
        break;
    case WAN_SPEED_MONSTER:
        rn1(25, 50);
        learn_it = true;
        break;
    case WAN_SLEEP: case SPE_SLEEP:
        learn_it = true;
        if (Sleep_resistance()) {
            shieldeff(game.u.ux, game.u.uy);
            await You("don't feel sleepy!");
        } else {
            if (ordinary) await pline_The('sleep ray hits you!');
            else await You('fall asleep!');
            await fall_asleep(-rnd(50), true);
        }
        break;
    case WAN_SLOW_MONSTER: case SPE_SLOW_MONSTER:
        break;
    case WAN_TELEPORTATION: case SPE_TELEPORT_AWAY:
        // tele() -- stub
        break;
    case WAN_DEATH: case SPE_FINGER_OF_DEATH:
        learn_it = true;
        await pline('You irradiate yourself with pure energy!');
        await pline('You die.');
        // done(DIED)
        break;
    case WAN_UNDEAD_TURNING: case SPE_TURN_UNDEAD:
        learn_it = true;
        await unturn_you();
        break;
    case SPE_HEALING: case SPE_EXTRA_HEALING:
        learn_it = true;
        c_d(6, obj.otyp === SPE_EXTRA_HEALING ? 8 : 4);
        await You_feel(`${obj.otyp === SPE_EXTRA_HEALING ? 'much ' : ''}better.`);
        break;
    case WAN_LIGHT:
        damage = c_d(obj.spe, 25);
        if (!damage) damage = 5;
        damage = await lightdamage(obj, ordinary, damage);
        damage += rnd(25);
        await flashburn(damage, false);
        damage = 0;
        break;
    case WAN_OPENING: case SPE_KNOCK:
        if (game.u.ustuck) {
            await release_hold();
            learn_it = true;
        }
        boxlock_invent(obj);
        break;
    case WAN_LOCKING: case SPE_WIZARD_LOCK:
        boxlock_invent(obj);
        break;
    case WAN_DIGGING: case SPE_DIG:
    case SPE_DETECT_UNSEEN: case WAN_NOTHING:
        break;
    case WAN_PROBING:
        probe_objchain(game.invent);
        update_inventory();
        learn_it = true;
        await ustatusline();
        break;
    case SPE_STONE_TO_FLESH:
        // Stone-to-flesh on self: check for stone golem form, petrification
        // Then bhito() each inventory item
        break;
    default: break;
    }
    if (learn_it) learnwand(obj);
    return damage;
}
// ── unturn_you — C ref: zap.c:1225 ──
async function unturn_you() {
    // unturn_dead(&youmonst) -- stub for now
    // if (is_undead(youmonst.data)) ...
    await You('shudder in dread.');
}
// ── unturn_dead — C ref: zap.c:1156 ──
// unturn_dead: imported from mon.js
function zapsetup() { game.obj_zapped = false; }
async function zapwrapup() {
    if (game.obj_zapped) await You_feel('shuddering vibrations.');
    game.obj_zapped = false;
}
// ── weffects — C ref: zap.c:3426 ──
export async function weffects(obj) {
    const g = game;
    const otyp = obj.otyp;
    let disclose = false;
    const was_unkn = !game.objects[otyp]?.oc_name_known;
    exercise(A_WIS, true);
    if (g.u.usteed && (game.objects[otyp]?.oc_dir !== NODIR) && !g.u.dx && !g.u.dy
        && (g.u.dz > 0) && await zap_steed(obj)) {
        disclose = true;
    } else if (game.objects[otyp]?.oc_dir === IMMEDIATE) {
        zapsetup();
        if (g.u?.uswallow) {
            await bhitm(g.u.ustuck, obj);
        } else if (g.u?.dz) {
            disclose = await zap_updown(obj);
        } else {
            const objRef = { obj };
            await bhit(g.u.dx, g.u.dy, rn1(8, 6), ZAPPED_WAND, bhitm, bhito, objRef);
        }
        await zapwrapup();
    } else if (game.objects[otyp]?.oc_dir === NODIR) {
        await zapnodir(obj);
    } else {
        if (otyp === WAN_DIGGING || otyp === SPE_DIG) await zap_dig();
        else if (otyp >= SPE_MAGIC_MISSILE && otyp <= SPE_FINGER_OF_DEATH)
            await ubuzz(BZ_U_SPELL(BZ_OFS_SPE(otyp)), Math.trunc(g.u.ulevel / 2) + 1);
        else if (otyp >= WAN_MAGIC_MISSILE && otyp <= WAN_LIGHTNING)
            await ubuzz(BZ_U_WAND(BZ_OFS_WAN(otyp)), (otyp === WAN_MAGIC_MISSILE) ? 2 : 6);
        disclose = true;
    }
    if (disclose) {
        learnwand(obj);
        if (was_unkn) { more_experienced(0, 10); }
    }
}
// ── dozap — C ref: zap.c:2622 ──
export async function dozap() {
    const g = game;
    if (g.youmonst?.data?.mflags1 & M1_NOHANDS) {
        await You("aren't able to zap anything in your current form.");
        return ECMD_OK;
    }
    if (check_capacity(null)) return ECMD_OK;
    const obj = await getobj('zap', zap_ok, GETOBJ_NOFLAGS);
    if (!obj) return ECMD_CANCEL;
    check_unpaid(obj);
    const need_dir = game.objects[obj.otyp]?.oc_dir !== NODIR;
    if (!await zappable(obj)) {
        await pline(nothing_happens);
    } else if (obj.cursed && !rn2(WAND_BACKFIRE_CHANCE)) {
        await backfire(obj);
        exercise(A_STR, false);
        return ECMD_TIME;
    } else if (need_dir && !(await getdir(null))) {
        if (!g.u?.prop?.BLINDED)
            await pline(`${The(xname(obj))} glows and fades.`);
    } else if (need_dir && !g.u.dx && !g.u.dy && !g.u.dz) {
        const damage = await zapyourself(obj, true);
        if (damage !== 0) {
            await losehp(damage, `zapped ${uhim()}self with ${xname(obj)}`, 'NO_KILLER_PREFIX');
        }
    } else {
        g.current_wand = obj;
        await weffects(obj);
        g.current_wand = null;
    }
    if (obj && obj.spe < 0) {
        await pline(`${Tobjnam(obj, 'turn')} to dust.`);
        useupall(obj);
    } else {
        update_inventory();
    }
    return ECMD_TIME;
}
// ── bhitm — monster hit by IMMEDIATE wand/spell — C ref: zap.c:160 ──
export async function bhitm(mtmp, otmp) {
    let ret = 0;
    let wake = true;
    let reveal_invis = false, learn_it = false;
    const dbldam = false; // Role_if(PM_KNIGHT) && u.uhave.questart -- stub
    let helpful_gesture = false;
    let dmg;
    const otyp = otmp.otyp;
    const zap_type_text_arr = ['spell'];
    const disguised_mimic = false;
    if (mtmp === game.u?.ustuck && game.u?.uswallow)
        reveal_invis = false;
    game.notonhead = (mtmp.mx !== game.bhitpos?.x || mtmp.my !== game.bhitpos?.y);
    const skilled_spell = (otmp.oclass === SPBOOK_CLASS && otmp.blessed);
    switch (otyp) {
    case WAN_STRIKING:
        zap_type_text_arr[0] = 'wand';
        /* FALLTHROUGH */
    case SPE_FORCE_BOLT:
        reveal_invis = true;
        learn_it = cansee(game.bhitpos?.x, game.bhitpos?.y);
        if (resists_magm(mtmp)) {
            shieldeff(mtmp.mx, mtmp.my);
            await pline('Boing!');
        } else if (game.u?.uswallow || rnd(20) < 10 + find_mac(mtmp)) {
            dmg = c_d(2, 12);
            if (dbldam) dmg *= 2;
            if (otyp === SPE_FORCE_BOLT) dmg = spell_damage_bonus(dmg);
            await hit(zap_type_text_arr[0], mtmp, exclam(dmg));
            resist(mtmp, otmp.oclass, dmg, true);
        } else {
            if (!disguised_mimic) await miss(zap_type_text_arr[0], mtmp);
            learn_it = false;
        }
        break;
    case WAN_SLOW_MONSTER: case SPE_SLOW_MONSTER:
        if (!resist(mtmp, otmp.oclass, 0, false)) {
            await mon_adjust_speed(mtmp, -1, otmp);
            check_gear_next_turn(mtmp);
        }
        break;
    case WAN_SPEED_MONSTER:
        if (!resist(mtmp, otmp.oclass, 0, false)) {
            await mon_adjust_speed(mtmp, 1, otmp);
            check_gear_next_turn(mtmp);
        }
        helpful_gesture = true;
        break;
    case WAN_UNDEAD_TURNING: case SPE_TURN_UNDEAD:
        wake = false;
        if (is_undead(mtmp.data) || is_vampshifter(mtmp)) {
            reveal_invis = true;
            wake = true;
            dmg = rnd(8);
            if (dbldam) dmg *= 2;
            if (otyp === SPE_TURN_UNDEAD) dmg = spell_damage_bonus(dmg);
            if (!resist(mtmp, otmp.oclass, dmg, false)) {
                if (mtmp.mhp > 0) await monflee(mtmp, 0, false, true);
            }
        }
        break;
    case WAN_POLYMORPH: case SPE_POLYMORPH:
        if (resists_magm(mtmp)) {
            shieldeff(mtmp.mx, mtmp.my);
        } else if (!resist(mtmp, otmp.oclass, 0, false)) {
            const polyspot = true; // wand/spell, not potion
            const give_msg = !Hallucination()
                && (canseemon(mtmp) || engulfing_u(mtmp));
            // C ref: zap.c:290 — natural shapechangers immune to shock
            if ((mtmp.cham ?? NON_PM) === NON_PM && !rn2(25)) {
                if (canseemon(mtmp)) {
                    await pline(`${Monnam(mtmp)} shudders!`);
                    learn_it = true;
                }
                await xkilled(mtmp, 5); // XKILL_GIVEMSG | XKILL_NOCORPSE
            } else {
                // C ref: zap.c:305 — newcham with random form
                let ncflags = 0;
                if (polyspot) ncflags |= NC_VIA_WAND_OR_SPELL;
                if (give_msg) ncflags |= NC_SHOW_MSG;
                if (await newcham(mtmp, null, ncflags) !== 0
                    || (ismnum(mtmp.cham)
                        && await newcham(mtmp, mons[mtmp.cham], ncflags) !== 0)) {
                    if (give_msg && canspotmon(mtmp))
                        learn_it = true;
                }
            }
        }
        break;
    case WAN_CANCELLATION: case SPE_CANCELLATION:
        cancel_monst(mtmp, otmp, true, true, false);
        break;
    case WAN_TELEPORTATION: case SPE_TELEPORT_AWAY:
        reveal_invis = !(await u_teleport_mon(mtmp, true));
        learn_it = canspotmon(mtmp);
        break;
    case WAN_MAKE_INVISIBLE:
        {
            const oldinvis = mtmp.minvis;
            mon_set_minvis(mtmp, false);
            if (!oldinvis) {
                await pline(`${Monnam(mtmp)} turns transparent!`);
                reveal_invis = true;
                learn_it = true;
            }
        }
        break;
    case WAN_LOCKING: case SPE_WIZARD_LOCK:
        wake = false;
        break;
    case WAN_PROBING:
        wake = false;
        reveal_invis = true;
        await probe_monster(mtmp);
        learn_it = true;
        break;
    case WAN_OPENING: case SPE_KNOCK:
        wake = false;
        if (mtmp === game.u?.ustuck) {
            await release_hold();
            learn_it = true;
        }
        if (otyp === SPE_KNOCK) {
            wake = true;
            ret = 1;
            if (canseemon(mtmp))
                await pline(`${Monnam(mtmp)} doesn't budge.`);
        }
        break;
    case SPE_HEALING: case SPE_EXTRA_HEALING:
        {
            const healamt = c_d(6, otyp === SPE_EXTRA_HEALING ? 8 : 4);
            reveal_invis = true;
            wake = false;
            healmon(mtmp, healamt, 0);
            if (canseemon(mtmp)) {
                await pline(`${Monnam(mtmp)} looks${otyp === SPE_EXTRA_HEALING ? ' much' : ''} better.`);
            }
        }
        break;
    case WAN_LIGHT:
        // flash_hits_mon() -- stub
        break;
    case WAN_SLEEP:
        reveal_invis = true;
        if (sleep_monst(mtmp, c_d(1 + otmp.spe, 12), WAND_CLASS))
            await slept_monst(mtmp);
        learn_it = true;
        break;
    case SPE_STONE_TO_FLESH:
        wake = false;
        break;
    case SPE_DRAIN_LIFE:
        // drain life -- stub
        break;
    case WAN_NOTHING:
        wake = false;
        break;
    default:
        break;
    }
    if (wake && mtmp.mhp > 0) {
        wakeup(mtmp, helpful_gesture ? false : true);
    }
    if (learn_it) learnwand(otmp);
    return ret;
}
// ── bhito — object hit by IMMEDIATE wand/spell — C ref: zap.c:2119 ──
export async function bhito(obj, otmp) {
    if (obj === otmp) return 0;
    if (obj?.bypass) {
        // C ref: zap.c:2133-2169 — while bypass context is active, skip
        // objects explicitly marked bypassed for this effect traversal.
        if (game.context?.bypasses) {
            return 0;
        }
        obj.bypass = 0;
    }
    let res = 1;
    let learn_it = false;
    if (obj === game.u?.uball) {
        res = 0;
    } else if (obj === game.u?.uchain) {
        if (otmp.otyp === WAN_OPENING || otmp.otyp === SPE_KNOCK) {
            learn_it = true;
            // unpunish() -- stub
        } else {
            res = 0;
        }
    } else {
        switch (otmp.otyp) {
        case WAN_POLYMORPH: case SPE_POLYMORPH:
            if (obj_unpolyable(obj)) {
                res = 0;
                break;
            }
            const cover = ((obj === obj_at(game.u?.ux, game.u?.uy))
                && !!game.u?.uundetected
                && hides_under(game.youmonst?.data));
            // C ref: zap.c:2203 — any saved lock context for boxes is invalidated
            // before obj_shudders/poly_obj.
            if (Is_box(obj)) {
                await boxlock(obj, otmp);
            }
            if (obj_shudders(obj)) {
                if (cansee(obj.ox, obj.oy)) learn_it = true;
                await do_osshock(obj);
                if (cover) {
                    hideunder(game.youmonst);
                }
                break;
            }
            obj = poly_obj(obj, STRANGE_OBJECT);
            newsym(obj.ox, obj.oy);
            break;
        case WAN_PROBING:
            res = !obj.dknown;
            obj.dknown = true;
            if (res) learn_it = true;
            break;
        case WAN_STRIKING: case SPE_FORCE_BOLT: {
            // C ref: zap.c:2277-2312 — wand/spell of striking hits floor objects
            let maybelearnit = cansee(obj.ox, obj.oy) || !Deaf();
            if (obj.otyp === BOULDER) {
                Soundeffect('se_crumbling_sound', 75);
                if (cansee(obj.ox, obj.oy))
                    await pline_The('boulder falls apart.');
                else
                    await You_hear('a crumbling sound.');
                fracture_rock(obj);
            } else if (obj.otyp === STATUE) {
                if (break_statue(obj)) {
                    if (cansee(obj.ox, obj.oy)) {
                        if (Hallucination())
                            await pline_The(`${rndmonnam(null)} shatters.`);
                        else
                            await pline_The('statue shatters.');
                    } else
                        await You_hear('a crumbling sound.');
                }
            } else {
                const oox = obj.ox, ooy = obj.oy;
                if (game.context?.mon_moving
                    ? !(await breaks(obj, oox, ooy))
                    : !(await hero_breaks(obj, oox, ooy, 0))) {
                    maybelearnit = false;
                } else {
                    newsym(oox, ooy);
                }
                res = 0;
            }
            if (maybelearnit)
                learn_it = true;
            break;
        }
        case WAN_CANCELLATION: case SPE_CANCELLATION:
            cancel_item(obj);
            break;
        case SPE_DRAIN_LIFE:
            drain_item(obj, true);
            break;
        case WAN_TELEPORTATION: case SPE_TELEPORT_AWAY:
            await rloco(obj);
            break;
        case WAN_MAKE_INVISIBLE:
            break;
        case WAN_UNDEAD_TURNING: case SPE_TURN_UNDEAD:
            // revive corpses/eggs -- stub
            break;
        case WAN_OPENING: case SPE_KNOCK:
        case WAN_LOCKING: case SPE_WIZARD_LOCK:
            // boxlock() -- stub
            res = 0;
            break;
        case WAN_SLOW_MONSTER: case SPE_SLOW_MONSTER:
        case WAN_SPEED_MONSTER:
        case WAN_NOTHING:
        case SPE_HEALING: case SPE_EXTRA_HEALING:
            res = 0;
            break;
        case SPE_STONE_TO_FLESH:
            res = stone_to_flesh_obj(obj);
            break;
        default:
            break;
        }
    }
    if (learn_it) learnwand(otmp);
    return res;
}
// ── bhit — beam travel for IMMEDIATE wands and thrown/kicked objects — C ref: zap.c:3822 ──
export async function bhit(ddx, ddy, range, weapon, fhitm, fhito, pobj) {
    const g = game;
    let result = null;
    let obj = (pobj && typeof pobj === 'object' && 'value' in pobj)
        ? pobj.value
        : (pobj?.obj || pobj);
    let shopdoor = false;
    let in_skip = false;
    let allow_skip = false;
    let skiprange_start = 0;
    let skiprange_end = 0;
    let skipcount = 0;
    if (!g.bhitpos) g.bhitpos = { x: 0, y: 0 };
    g.bhitpos.x = g.u.ux;
    g.bhitpos.y = g.u.uy;
    // C ref: zap.c:3851-3853 — thrown rocks may initialize skiprange and
    // consume rn2(3) even when no actual skip ultimately occurs.
    if (weapon === THROWN_WEAPON && obj && obj.otyp === ROCK) {
        const skip = { start: 0, end: 0 };
        skiprange(range, skip);
        skiprange_start = skip.start;
        skiprange_end = skip.end;
        allow_skip = !rn2(3);
    }
    while (range-- > 0) {
        g.bhitpos.x += ddx;
        g.bhitpos.y += ddy;
        const x = g.bhitpos.x;
        const y = g.bhitpos.y;
        if (!isok(x, y)) {
            g.bhitpos.x -= ddx;
            g.bhitpos.y -= ddy;
            break;
        }
        if (weapon === ZAPPED_WAND) {
            await zap_map(x, y, obj);
        }
        const mtmp = m_at(x, y);
        // C ref: zap.c:3941-3959 — skipping rock state machine.
        // We keep this narrow: preserve RNG/event ordering and movement state.
        if (skiprange_start && range === skiprange_start && allow_skip) {
            if (is_pool(x, y) && !mtmp) {
                in_skip = true;
                if (!Blind())
                    await pline(`${Yname2(obj)} ${obj ? vtense(obj, 'skip') : 'skip'}${skipcount ? ' again' : ''}.`);
                else
                    await You_hear(`${obj ? yname(obj) : 'Something'} skip.`);
                skipcount++;
            } else if (skiprange_start > skiprange_end + 1) {
                --skiprange_start;
            }
        }
        if (in_skip && range <= skiprange_end) {
            in_skip = false;
            if (range > 3) {
                const skip = { start: 0, end: 0 };
                skiprange(range, skip);
                skiprange_start = skip.start;
                skiprange_end = skip.end;
            }
        }
        if (mtmp) {
            g.notonhead = (x !== mtmp.mx || y !== mtmp.my);
            if (weapon === ZAPPED_WAND) {
                if (fhitm && (await fhitm(mtmp, obj))) {
                    result = mtmp;
                    break;
                }
                range -= 3;
            } else if (weapon === FLASHED_LIGHT) {
                // C ref: zap.c:3991-4005 — pass through minvis targets by
                // applying flash_hits_mon() inline; stop on non-minvis and
                // return mtmp to caller so caller handles flash_hits_mon().
                if (mtmp.minvis) {
                    if (obj) {
                        obj.ox = g.u.ux;
                        obj.oy = g.u.uy;
                    }
                    await flash_hits_mon(mtmp, obj);
                    continue;
                }
                result = mtmp;
                break;
            } else {
                // THROWN_WEAPON / KICKED_WEAPON
                result = mtmp;
                break;
            }
        }
        if (fhito && weapon === ZAPPED_WAND) {
            if (await bhitpile(obj, fhito, x, y, 0))
                range--;
        }
        // Door handling for ZAPPED_WAND
        const levl = g.level?.locations;
        if (weapon === ZAPPED_WAND && levl) {
            const loc = levl[x]?.[y];
            const typ = loc?.typ || 0;
            if (typ === 8 || typ === 7) { // DOOR or SDOOR
                switch (obj.otyp) {
                case WAN_OPENING: case WAN_LOCKING: case WAN_STRIKING:
                case SPE_KNOCK: case SPE_WIZARD_LOCK: case SPE_FORCE_BOLT:
                    if (await doorlock(obj, x, y)) {
                        if (cansee(x, y)) learnwand(obj);
                    }
                    break;
                }
            }
        }
        const levl2 = g.level?.locations;
        if (levl2) {
            const loc = levl2[g.bhitpos.x]?.[g.bhitpos.y];
            if (loc && (!ZAP_POS(loc.typ) || closed_door(g.bhitpos.x, g.bhitpos.y))) {
                g.bhitpos.x -= ddx;
                g.bhitpos.y -= ddy;
                break;
            }
        }
        // C ref: zap.c:4076-4083 — animation delay for thrown/kicked weapons
        if (weapon !== ZAPPED_WAND) {
            await delay_output();
        }
    }
    return result;
}
// ── boomhit — C ref: zap.c:4143 ──
// Boomerang curving path. Simplified for parity.
export async function boomhit(obj, dx, dy) {
    if (!game.bhitpos) game.bhitpos = { x: 0, y: 0 };
    game.bhitpos.x = game.u.ux;
    game.bhitpos.y = game.u.uy;
    // Simplified stub -- boomerang mechanics require display support
    return null;
}
// ── zhitm — damage calculation when a beam/breath hits a monster — C ref: zap.c:4231 ──
export async function zhitm(mon, type, nd) {
    let tmp = 0;
    const damgtype = zaptype(type) % 10;
    let sho_shieldeff = false;
    const spellcaster = is_hero_spell(type);
    let ootmp = null;
    switch (damgtype) {
    case ZT_MAGIC_MISSILE:
        if (resists_magm(mon) || defended(mon, AD_MAGM)) {
            sho_shieldeff = true;
            break;
        }
        tmp = c_d(nd, 6);
        if (spellcaster) tmp = spell_damage_bonus(tmp);
        break;
    case ZT_FIRE:
        if (resists_fire(mon) || defended(mon, AD_FIRE)) {
            sho_shieldeff = true;
            break;
        }
        tmp = c_d(nd, 6);
        if (spellcaster) tmp = spell_damage_bonus(tmp);
        {
            const orig_dmg = tmp;
            if (resists_cold(mon)) tmp += 7;
            if (await burnarmor(mon)) {
                if (!rn2(3)) {
                    tmp += await destroy_items(mon, AD_FIRE, orig_dmg);
                    ignite_items(mon.minvent);
                }
            }
        }
        break;
    case ZT_COLD:
        if (resists_cold(mon) || defended(mon, AD_COLD)) {
            sho_shieldeff = true;
            break;
        }
        tmp = c_d(nd, 6);
        if (spellcaster) tmp = spell_damage_bonus(tmp);
        {
            const orig_dmg = tmp;
            if (resists_fire(mon)) tmp += c_d(nd, 3);
            if (!rn2(3)) tmp += await destroy_items(mon, AD_COLD, orig_dmg);
        }
        break;
    case ZT_SLEEP:
        tmp = 0;
        sleep_monst(mon, c_d(nd, 25), type === ZT_WAND(ZT_SLEEP) ? WAND_CLASS : '\0');
        break;
    case ZT_DEATH:
        if (Math.abs(type) !== ZT_BREATH(ZT_DEATH)) {
            // Death ray (not disintegration)
            if (nonliving(mon.data) || is_demon(mon.data)
                || is_vampshifter(mon) || resists_magm(mon)) {
                sho_shieldeff = true;
                break;
            }
            type = -1; // no saving throw
        } else {
            // Disintegration breath
            if (resists_disint(mon) || defended(mon, AD_DISN)) {
                sho_shieldeff = true;
            } else if (mon.misc_worn_check & W_ARMS) {
                ootmp = which_armor(mon, W_ARMS);
            } else if (mon.misc_worn_check & W_ARM) {
                ootmp = which_armor(mon, W_ARM);
                const otmp2 = which_armor(mon, W_ARMC);
                if (otmp2) await m_useup(mon, otmp2);
            } else {
                tmp = MAGIC_COOKIE;
                const otmp2c = which_armor(mon, W_ARMC);
                if (otmp2c) await m_useup(mon, otmp2c);
                const otmp2u = which_armor(mon, W_ARMU);
                if (otmp2u) await m_useup(mon, otmp2u);
            }
            type = -1;
            break; // not ordinary damage
        }
        tmp = mon.mhp + 1;
        break;
    case ZT_LIGHTNING:
        tmp = c_d(nd, 6);
        if (spellcaster) tmp = spell_damage_bonus(tmp);
        {
            const orig_dmg = tmp;
            if (resists_elec(mon) || defended(mon, AD_ELEC)) {
                sho_shieldeff = true;
                tmp = 0;
            }
            if (!resists_blnd(mon) && nd > 2) {
                const rnd_tmp = rnd(50);
                mon.mcansee = 0;
                if ((mon.mblinded || 0) + rnd_tmp > 127)
                    mon.mblinded = 127;
                else
                    mon.mblinded = (mon.mblinded || 0) + rnd_tmp;
            }
            if (!rn2(3)) tmp += await destroy_items(mon, AD_ELEC, orig_dmg);
        }
        break;
    case ZT_POISON_GAS:
        if (resists_poison(mon) || defended(mon, AD_DRST)) {
            sho_shieldeff = true;
            break;
        }
        tmp = c_d(nd, 6);
        break;
    case ZT_ACID:
        if (resists_acid(mon) || defended(mon, AD_ACID)) {
            sho_shieldeff = true;
            break;
        }
        tmp = c_d(nd, 6);
        if (!rn2(6)) acid_damage(null); // MON_WEP(mon) stub
        if (!rn2(6)) await erode_armor(mon, 0); // ERODE_CORRODE
        break;
    }
    if (sho_shieldeff) shieldeff(mon.mx, mon.my);
    if (is_hero_spell(type) && false /* Role_if(PM_KNIGHT) && u.uhave.questart */)
        tmp *= 2;
    if (tmp > 0 && type >= 0
        && resist(mon, type < ZT_SPELL(0) ? WAND_CLASS : '\0', 0, false))
        tmp = Math.trunc(tmp / 2);
    if (tmp < 0) tmp = 0;
    mon.mhp -= tmp;
    return { damage: tmp, armor: ootmp };
}
// ── zhitu — beam/breath hits the hero — C ref: zap.c:4394 ──
async function zhitu(type, nd, fltxt, sx, sy) {
    let dam = 0;
    const abstyp = zaptype(type);
    let orig_dam = 0;
    switch (abstyp % 10) {
    case ZT_MAGIC_MISSILE:
        dam = c_d(nd, 6);
        exercise(A_STR, false);
        break;
    case ZT_FIRE:
        orig_dam = c_d(nd, 6);
        if (Fire_resistance()) {
            shieldeff(sx, sy);
            await You("don't feel hot!");
            dam = 0;
        } else {
            dam = orig_dam;
        }
        // burn_away_slime(), burnarmor()
        if (await burnarmor(game.youmonst)) {
            if (!rn2(3)) await destroy_items(game.youmonst || game.u, AD_FIRE, orig_dam);
            if (!rn2(3)) ignite_items(game.invent);
        }
        break;
    case ZT_COLD:
        orig_dam = c_d(nd, 6);
        if (Cold_resistance()) {
            shieldeff(sx, sy);
            await You("don't feel cold.");
            dam = 0;
        } else {
            dam = orig_dam;
        }
        if (!rn2(3)) await destroy_items(game.youmonst || game.u, AD_COLD, orig_dam);
        break;
    case ZT_SLEEP:
        if (Sleep_resistance()) {
            shieldeff(game.u.ux, game.u.uy);
            await You("don't feel sleepy.");
        } else {
            await fall_asleep(-c_d(nd, 25), true);
        }
        break;
    case ZT_DEATH:
        if (abstyp === ZT_BREATH(ZT_DEATH)) {
            // disintegration breath -- stub
        }
        // done(DIED) -- stub
        break;
    case ZT_LIGHTNING:
        orig_dam = c_d(nd, 6);
        if (hero_shock_resistance()) {
            shieldeff(sx, sy);
            await You("aren't affected.");
            dam = 0;
        } else {
            dam = orig_dam;
            exercise(A_CON, false);
        }
        if (!rn2(3)) await destroy_items(game.youmonst || game.u, AD_ELEC, orig_dam);
        break;
    case ZT_POISON_GAS:
        // poisoned("blast", A_DEX, "poisoned blast", 15, FALSE) -- stub
        break;
    case ZT_ACID:
        dam = c_d(nd, 6);
        exercise(A_STR, false);
        if (!rn2(6)) { /* acid_damage uwep */ }
        if (!rn2(6)) { /* erode_armor */ }
        break;
    }
    await losehp(dam, fltxt || 'magical blast', 'KILLED_BY_AN');
}
// ── disintegrate_mon — C ref: zap.c:4716 ──
async function disintegrate_mon(mon, type, fltxt) {
    if (canseemon(mon)) {
        if (!false /* mlifesaver */)
            await pline(`${Monnam(mon)} is disintegrated!`);
    }
    if (type < 0) await monkilled(mon, null, AD_RBRE);
    else await xkilled(mon, 0x01 | 0x04); // XKILL_NOMSG | XKILL_NOCORPSE
}
// ── ubuzz / buzz / dobuzz — C ref: zap.c:4752 ──
export async function ubuzz(type, nd) {
    await dobuzz(type, nd, game.u.ux, game.u.uy, game.u.dx, game.u.dy, true, false, false);
}
export async function buzz(type, nd, sx, sy, dx, dy) {
    await dobuzz(type, nd, sx, sy, dx, dy, true, false, false);
}
async function dobuzz(type, nd, sx, sy, dx, dy, sayhit, saymiss, forcemiss) {
    const g = game;
    const fltyp = zaptype(type);
    const damgtype = fltyp % 10;
    const hdmgtype = (g.u?.prop?.HALLUC) ? rn2(6) : damgtype;
    const spell_type = is_hero_spell(type) ? SPE_MAGIC_MISSILE + damgtype : 0;
    const fireball = (type === ZT_SPELL(ZT_FIRE));
    let shopdamage = false;
    if (g.u?.uswallow) {
        if (type < 0) return;
        const result = await zhitm(g.u.ustuck, type, nd);
        if (!g.u.ustuck) {
            g.u.uswallow = 0;
        } else {
            await pline(`${The(flash_str(fltyp))} rips into ${mon_nam(g.u.ustuck)}${exclam(result.damage)}`);
            if (result.damage === MAGIC_COOKIE) g.u.ustuck.mhp = 0;
            if (g.u.ustuck.mhp <= 0) await killed(g.u.ustuck);
        }
        return;
    }
    if (type < 0) newsym(g.u.ux, g.u.uy);
    let range = rn1(7, 7);
    if (dx === 0 && dy === 0) range = 1;
    const save_bhitpos = g.bhitpos ? { ...g.bhitpos } : { x: 0, y: 0 };
    g.bhitpos = g.bhitpos || { x: 0, y: 0 };
    await tmp_at(DISP_BEAM, zapdir_to_glyph(dx, dy, hdmgtype));
    let lsx, lsy;
    let gas_hit = false;
    while (range-- > 0) {
        lsx = sx; sx += dx;
        lsy = sy; sy += dy;
        if (!isok(sx, sy) || (game.level?.locations?.[sx]?.[sy]?.typ || 0) === 0) {
            // make_bounce
            const bchance = (!isok(sx, sy) || (game.level?.locations?.[sx]?.[sy]?.typ || 0) === 0) ? 10 : 75;
            if (--range > 0 && isok(lsx, lsy)) {
                if (fireball) {
                    sx = lsx; sy = lsy;
                    break;
                }
                if (cansee(lsx, lsy))
                    await pline(`${The(flash_str(fltyp))} bounces!`);
                const ddx_ref = { v: dx };
                const ddy_ref = { v: dy };
                bounce_dir(sx, sy, ddx_ref, ddy_ref, bchance);
                dx = ddx_ref.v; dy = ddy_ref.v;
                sx = lsx; sy = lsy;
            } else {
                break;
            }
            continue;
        }
        let mon = m_at(sx, sy);
        g.bhitpos.x = sx; g.bhitpos.y = sy;
        gas_hit = (damgtype === ZT_POISON_GAS);
        if (!fireball && !gas_hit) {
            range += await zap_over_floor(sx, sy, type, { v: shopdamage }, true, 0);
            mon = m_at(sx, sy); // might have drowned
        }
        // C ref: zap.c:4831-4841 — visible beam frame delay before hit/miss resolution.
        const loctyp_here = game.level?.locations?.[sx]?.[sy]?.typ || 0;
        if (cansee(sx, sy)
            && (ZAP_POS(loctyp_here) || (isok(lsx, lsy) && cansee(lsx, lsy)))) {
            await tmp_at(sx, sy);
            await flush_screen(1);
            await delay_output();
        }
        if (mon) {
            if (fireball) break;
            if (type >= 0) {
                if (mon.mstrategy) mon.mstrategy &= ~0x10000000; // STRAT_WAITMASK
            }
            g.notonhead = (mon.mx !== g.bhitpos.x || mon.my !== g.bhitpos.y);
            if (!forcemiss && zap_hit(find_mac(mon), spell_type)) {
                if (await mon_reflects(mon, null)) {
                    if (cansee(mon.mx, mon.my)) {
                        await hit(flash_str(fltyp), mon, exclam(0));
                        shieldeff(mon.mx, mon.my);
                        gas_hit = false;
                    }
                    dx = -dx; dy = -dy;
                } else {
                    const mon_could_move = mon.mcanmove;
                    const result = await zhitm(mon, type, nd);
                    if (is_rider(mon.data) && Math.abs(type) === ZT_BREATH(ZT_DEATH)) {
                        if (canseemon(mon)) {
                            await hit(flash_str(fltyp), mon, '.');
                            await pline(`${Monnam(mon)} disintegrates.`);
                            await pline(`${s_suffix(Monnam(mon))} body reintegrates before your eyes!`);
                            await pline(`${Monnam(mon)} resurrects!`);
                        }
                        mon.mhp = mon.mhpmax;
                        break;
                    }
                    if (result.damage === MAGIC_COOKIE) {
                        await disintegrate_mon(mon, type, flash_str(fltyp));
                    } else if (mon.mhp <= 0) {
                        if (type < 0) {
                            await monkilled(mon, flash_str(fltyp), -7 /* AD_RBRE */);
                        } else {
                            await xkilled(mon, 0); // XKILL_GIVEMSG
                        }
                    } else {
                        if (!result.armor) {
                            if (sayhit || canseemon(mon))
                                await hit(flash_str(fltyp), mon, exclam(result.damage));
                        } else {
                            if (canseemon(mon))
                                await pline(`${s_suffix(Monnam(mon))} ${xname(result.armor)} is disintegrated!`);
                            await m_useup(mon, result.armor);
                        }
                        if (mon_could_move && !mon.mcanmove) await slept_monst(mon);
                        if (damgtype !== ZT_SLEEP) wakeup(mon, type >= 0);
                    }
                }
                range -= 2;
            } else {
                if (saymiss || (canseemon(mon)))
                    await miss(flash_str(fltyp), mon);
            }
        } else if (sx === g.u.ux && sy === g.u.uy && range >= 0) {
            nomul(0);
            if (!forcemiss && zap_hit(g.u?.uac ?? 10, 0)) {
                range -= 2;
                await pline(`${The(flash_str(fltyp))} hits you!`);
                if (Reflecting()) {
                    if (!Blind()) {
                        await ureflects("But %s reflects from your %s!", "it");
                    } else {
                        await pline("For some reason you are not affected.");
                    }
                    monstseesu(M_SEEN_REFL);
                    dx = -dx;
                    dy = -dy;
                    shieldeff(sx, sy);
                    gas_hit = false;
                } else {
                    await zhitu(type, nd, flash_str(fltyp), sx, sy);
                    monstunseesu(M_SEEN_REFL);
                }
            } else if (!g.u?.prop?.BLINDED) {
                await pline(`${The(flash_str(fltyp))} whizzes by you!`);
            }
            if (damgtype === ZT_LIGHTNING) await flashburn(c_d(nd, 50), true);
            await stop_occupation();
            nomul(0);
        }
        // gas cloud for gas that missed or hit without being reflected
        if (gas_hit) {
            await zap_over_floor(sx, sy, type, { v: shopdamage }, true, 0);
        }
        const loctyp = game.level?.locations?.[sx]?.[sy]?.typ || 0;
        if (!ZAP_POS(loctyp) || (closed_door(sx, sy) && range >= 0)) {
            const bchance = 75;
            if (--range > 0 && isok(lsx, lsy)) {
                if (fireball) {
                    sx = lsx; sy = lsy;
                    break;
                }
                if (cansee(lsx, lsy))
                    await pline(`${The(flash_str(fltyp))} bounces!`);
            } else if (fireball) {
                sx = lsx; sy = lsy;
                break;
            }
            const ddx_ref = { v: dx };
            const ddy_ref = { v: dy };
            bounce_dir(sx, sy, ddx_ref, ddy_ref, bchance);
            dx = ddx_ref.v; dy = ddy_ref.v;
            await tmp_at(DISP_CHANGE, zapdir_to_glyph(dx, dy, hdmgtype));
        }
    }
    await tmp_at(DISP_END, 0);
    if (fireball) {
        await explode(sx, sy, type, c_d(12, 6), 0, 1 /* EXPL_FIERY */);
    }
    g.bhitpos = save_bhitpos;
}
// ── resist — C ref: zap.c:6093 ──
export function resist(mtmp, oclass, damage, tell) {
    if (!mtmp) return false;
    let alev;
    switch (oclass) {
    case WAND_CLASS: alev = 12; break;
    case TOOL_CLASS: alev = 10; break;
    case WEAPON_CLASS: alev = 10; break;
    case SCROLL_CLASS: alev = 9; break;
    case POTION_CLASS: alev = 6; break;
    case RING_CLASS: alev = 5; break;
    default: alev = game.u?.ulevel ?? 1; break;
    }
    let dlev = mtmp.m_lev || 0;
    if (dlev > 50) dlev = 50;
    else if (dlev < 1) dlev = is_mplayer(mtmp.data) ? (game.u?.ulevel ?? 1) : 1;
    const resisted = rn2(100 + alev - dlev) < (mtmp.data?.mr ?? 0);
    if (resisted) {
        if (tell) shieldeff(mtmp.mx, mtmp.my);
        damage = Math.trunc((damage + 1) / 2);
    }
    if (damage) {
        mtmp.mhp -= damage;
        if (DEADMONSTER(mtmp)) {
            // C ref: zap.c:6143-6148 — m_using → monkilled, else killed.
            // Both are async in JS; schedule for caller to handle.
            mtmp._resist_killed = true;
        }
    }
    return resisted;
}
// C ref: zap.c:6143-6148 — process deferred monster death from resist().
// Call after resist() if the monster might have died.
export async function resist_death(mtmp) {
    if (!mtmp?._resist_killed) return;
    delete mtmp._resist_killed;
    if (game.m_using) {
        await monkilled(mtmp, '', AD_RBRE);
    } else {
        await killed(mtmp);
    }
}
// ── cancel_monst — C ref: zap.c:3145 ──
export function cancel_monst(mdef, obj, youattack, allow_cancel_kill, self_cancel) {
    const youdefend = (mdef === game.youmonst);
    if (youdefend ? (!youattack && false /* Antimagic */)
                  : resist(mdef, obj?.oclass || 0, 0, false))
        return false;
    if (self_cancel) {
        const inv = youdefend ? game.invent : mdef?.minvent;
        for (let otmp = inv; otmp; otmp = otmp.nobj) {
            cancel_item(otmp);
        }
    }
    if (youdefend) {
        // rehumanize / clay golem handling -- stub
    } else {
        mdef.mcan = 1;
        normal_shape(mdef);
    }
    return true;
}
// ── fracture_rock — C ref: zap.c:5530 ──
export function fracture_rock(obj) {
    obj.otyp = 1; // ROCK -- stub constant
    obj.oclass = 7; // GEM_CLASS -- stub
    obj.quan = rn1(60, 7);
}
// ── break_statue — C ref: zap.c:5575 ──
export function break_statue(obj) {
    fracture_rock(obj);
    return true;
}
// ── obj_shudders — C ref: zap.c:1476 ──
export function obj_shudders(obj) {
    let zap_odds;
    if (game.context?.bypasses && obj?.bypass)
        return false;
    if (obj.oclass === WAND_CLASS) zap_odds = 3;
    else if (obj.cursed) zap_odds = 3;
    else if (obj.blessed) zap_odds = 12;
    else zap_odds = 8;
    if (obj.quan > 4) zap_odds = Math.trunc(zap_odds / 2);
    return !rn2(zap_odds);
}
// ── poly_zapped_mon ── (stub)
export function poly_zapped_mon() { /* stub */ }
// ── mon_spell_hits_spot — C ref: zap.c:5494 ──
async function mon_spell_hits_spot(caster, adtyp, x, y) {
    // Simplified: call zap_over_floor for fire/cold
    if (adtyp === AD_FIRE) {
        await zap_over_floor(x, y, ZT_SPELL(ZT_FIRE), { v: false }, false, 0);
    } else if (adtyp === AD_COLD) {
        await zap_over_floor(x, y, ZT_SPELL(ZT_COLD), { v: false }, false, 0);
    }
}
// ── makewish — C ref: zap.c:6307 ──
export async function makewish() {
    const g = game;
    const nothing = {};
    let tries = 0;
    g.context.resume_wish = false;
    if (g.flags?.verbose) await You('may wish for an object.');
    while (true) {
        let buf = await getlin('For what do you wish?', null, { logHookedLifecycle: true });
        // C ref: zap.c:6339 — ESC sets buf[0]='\0', does NOT return early;
        // readobjnam is still called with the empty string
        if (buf == null) buf = '';
        buf = String(buf).replace(/\s+/g, ' ').trim();
        const otmp = readobjnam(buf, nothing);
        if (!otmp) {
            await pline('Nothing fitting that description exists in the game.');
            tries++;
            if (tries < 5) continue;
            return null;
        }
        if (otmp === nothing) return nothing;
        await hold_another_object(otmp, 'Oops!  %s to the floor!', The(aobjnam(otmp, 'drop')), null);
        if (!g.u.uconduct) g.u.uconduct = {};
        g.u.uconduct.wishes = (g.u.uconduct.wishes || 0) + 1;
        await encumber_msg();
        g.u.ublesscnt += rn1(100, 50);
        return otmp;
    }
}
// maybe_explode_trap: defined above (line ~601)
// trap_to_defsym: defined above
// zap_map: defined above
// ── revive — C ref: zap.c:884 ──
export async function revive(corpse, by_hero) {
    if (corpse.otyp !== CORPSE) {
        return null;
    }
    const montype = corpse.corpsenm;
    const is_zomb = (mons[montype]?.mlet === S_ZOMBIE)
              || (corpse.where === OBJ_BURIED && is_reviver(mons[montype]));
    await cant_finish_meal(corpse);
    let x = 0, y = 0;
    if (corpse.where !== 3 /* OBJ_CONTAINED */) {
        const locflags = is_zomb ? BURIED_TOO : 0;
        const loc = get_obj_location(corpse, locflags);
        if (loc) { x = loc.x; y = loc.y; }
    } else {
        const loc = get_obj_location(corpse, CONTAINED_TOO);
        if (loc) { x = loc.x; y = loc.y; }
    }
    if (x) {
        corpse.ox = x;
        corpse.oy = y;
    }
    if (!x) return null;
    const mptr = mons[montype];
    if (m_at(x, y)) {
        const xy = { x, y };
        if (enexto(xy, x, y, mptr)) {
            x = xy.x; y = xy.y;
        }
    }
    if (corpse.norevive || (mons[montype]?.mlet === S_EEL && !is_pool(x, y))) {
        if (cansee(x, y)) {
            await pline(`${upstart(corpse_xname(corpse, null, CXN_PFX_THE))} twitches feebly.`);
        }
        return null;
    }
    let mmflags = NO_MINVENT | MM_NOWAIT | MM_NOMSG;
    const cgend = (corpse.spe & 0x03 /* CORPSTAT_GENDER */);
    if (cgend === 0x01 /* CORPSTAT_MALE */) mmflags |= MM_MALE;
    else if (cgend === 0x02 /* CORPSTAT_FEMALE */) mmflags |= MM_FEMALE;
    let mtmp = null;
    const mtype_ref = { v: montype };
    if (cant_revive(mtype_ref, true, corpse)) {
        mtmp = await makemon(mons[mtype_ref.v], x, y, mmflags);
        if (mtmp) {
            if (mtmp.data.mlet === 83 /* S_ZOMBIE */) {
                mtmp.mhp = mtmp.mhpmax = 100;
                await mon_adjust_speed(mtmp, 2, null);
            }
        }
    } else {
        mtmp = await makemon(mptr, x, y, mmflags | MM_NOCOUNTBIRTH);
    }
    if (!mtmp) return null;
    if (mtmp.mundetected) {
        mtmp.mundetected = 0;
        newsym(mtmp.mx, mtmp.my);
    }
    if (M_AP_TYPE(mtmp)) seemimic(mtmp);
    const one_of = (corpse.quan > 1);
    if (one_of) corpse = splitobj(corpse, 1);
    if (by_hero) {
        if (cansee(x, y)) {
            const buf = (one_of ? "one of " : "") + corpse_xname(corpse, null, CXN_PFX_THE);
            await pline(`${upstart(buf)} glows iridescently.`);
        }
    }
    if (has_oname(corpse) && !unique_corpstat(mtmp.data)) {
        mtmp = christen_monst(mtmp, ONAME(corpse));
    }
    mtmp.mrevived = 1;
    switch (corpse.where) {
    case OBJ_INVENT:
        useup(corpse);
        break;
    case OBJ_FLOOR:
        obj_extract_self(corpse);
        newsym(x, y);
        break;
    case OBJ_MINVENT:
        await m_useup(corpse.ocarry, corpse);
        break;
    default:
        obj_extract_self(corpse);
        break;
    }
    return mtmp;
}
// ── revive_egg — C ref: zap.c:1143 ──
export function revive_egg(obj) {
    if (obj.otyp !== EGG) return;
    if (obj.corpsenm !== NON_PM && !dead_species(obj.corpsenm, true)) {
        attach_egg_hatch_timeout(obj, 0);
    }
}
// burn_floor_objects: defined above
export {
    zaptype, flash_str,
    ZT_MAGIC_MISSILE, ZT_FIRE, ZT_COLD, ZT_SLEEP, ZT_DEATH,
    ZT_LIGHTNING, ZT_POISON_GAS, ZT_ACID,
    ZT_WAND, ZT_SPELL, ZT_BREATH,
    BZ_OFS_WAN, BZ_OFS_SPE, BZ_U_WAND, BZ_U_SPELL,
    MAGIC_COOKIE,
    closed_door,
    get_obj_location, get_mon_location,
    cancel_item,
    zap_over_floor, zap_updown, zap_map,
    bhitpile,
    unturn_dead, unturn_you,
    lightdamage, flashburn,
    stone_to_flesh_obj, poly_obj, do_osshock, obj_unpolyable,
    melt_ice, mon_spell_hits_spot,
    probe_objchain, probe_monster,
    release_hold, boxlock_invent, zap_steed,
    burn_floor_objects,
};