All files / js muse.js

48.5% Statements 1172/2416
49.31% Branches 359/728
49.12% Functions 28/57
48.5% Lines 1172/2416

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 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 241773x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 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 2x 2x     2x     2x 73x 73x 73x 73x 73x 73x 73x 73x   73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 18x 18x 17x 17x 5x 5x 5x                                       5x 5x 5x                                                   5x 17x 18x                                   17x 18x 73x 10x 10x 10x 1x 1x 1x 1x 1x 10x   9x 9x 9x 9x 10x 10x 73x                                             73x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 73x 5x 5x 1x 1x 5x 4x 4x 4x 5x 73x 73x 10x 10x 10x         10x         10x         10x 10x 73x                             73x 1x 1x 1x 1x 1x 1x 1x                           1x 73x                     73x 73x 15539x 15539x 15539x 15539x 15539x 15539x 15539x 15539x 15539x 15539x 15539x 13474x 15539x 15539x 15539x 15539x 498x 15539x 10x 10x 10x 10x 40x 10x 10x         10x 15539x                                 498x 12915x 15539x 10x 10x 10x 498x 6689x 15539x 15539x 15539x 15539x               2503x 463x 463x 463x 463x 171x             463x 15539x   3242x 1x 1x 1x 1x 1x           38x                     37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 111x 333x 37x 327x 327x 327x 327x 327x 230x 230x 327x 327x 327x 6x 126x 327x 327x         126x         327x 37x 38x 3242x 3242x 15539x       38x 3242x 37x 37x 15539x 15539x 2224x 111x 111x 108x 111x 111x 111x 111x 111x 111x 111x 111x 111x       111x 111x 111x                 111x 111x 111x 111x 111x 2x 2x 1x 1x 1x 2x 106x 106x 106x       106x 106x 1x 1x 1x 106x 106x       106x 106x       111x                       111x 111x 1x 1x 1x 111x 37x 15539x 73x                   73x                   73x 73x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 4x 4x                             4x                 4x             4x                 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x                         1x 1x 1x 1x 1x 1x 1x 1x 4x                                                                                     4x             4x                       4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       4x                                 4x                                   4x 1x 1x 1x 1x 1x 1x 1x 1x 4x                 4x                 4x                     4x                               4x                       4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x                         4x     4x 4x 4x   4x   4x 73x 73x 19x 19x 19x 19x 19x 19x 19x 22x 22x 22x 4x 4x 1x 3x 22x 22x 22x 5x 22x 22x 1x 1x 22x 22x 4x 22x   22x 3x 22x 3x 22x 3x 3x 3x 3x 3x 22x   22x 22x 19x 73x       73x 95x 95x 95x           95x       95x 73x 73x 10380x 10380x 10380x 10380x 10380x 10380x 10380x 10380x 10380x 1072x 8484x 1072x 10380x 10380x 10380x 1072x 6817x 47x 10380x 10380x 10380x 95x 29x 29x 29x       29x 29x 29x       29x 29x 29x       29x 29x 29x       29x 29x 29x       29x 29x 29x       29x 29x 29x       29x 29x 29x       29x 95x 95x 95x 95x 95x 9x 9x 9x 95x 95x 95x 95x   95x     95x       95x 95x       95x 95x       95x 95x       95x 70x 95x       95x 70x 95x       95x 70x 95x     95x 95x 95x 95x       95x 70x 95x   95x 95x       95x 47x 10380x 73x 32x 32x 32x 32x 1x 1x 1x 1x 1x 1x 1x 1x 32x 73x 73x 9x 9x 9x 9x 9x 9x 9x 9x 34x 34x 34x 34x 34x         34x 9x 7x 34x 3x 3x 3x 3x 3x 32x 34x 34x 34x 34x 34x 32x 34x                   32x 34x 34x 2x 2x 2x 2x 34x 9x 73x 73x 73x 73x 73x       73x 73x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x                           9x 9x                           9x 9x 9x 9x 9x 9x 9x 9x 7x 7x 7x 7x 7x 9x                                                         9x                                 9x 9x 9x 9x 9x                 9x   9x   9x   9x 73x 73x 21x 21x 21x 21x 21x 21x 21x 21x 21x 1x 1x 1x 1x 1x 21x 21x 1x 21x 1x 21x 3x 21x 2x 21x 1x 21x 1x 21x 21x 3x 21x 1x 21x 3x 21x 4x 21x   21x   21x 73x 73x 15490x 15490x 15490x 15490x 15490x 15490x 15490x 15490x 15490x 15490x 15490x 15490x 3832x 13037x 15490x 15490x 117x 117x 117x 117x 351x 1053x 1053x 1037x 1037x 1037x 1x           1x 1037x 117x 720x 12893x 12735x 2153x 2153x 2153x 2x 2x 2x 2153x 2153x 2153x 2153x 2153x 2153x 2153x 2153x       2153x 2153x 2153x 2153x       2153x 2153x 2153x 2153x       2153x 2153x 2153x 1x 1x 1x 2153x 2153x 2x 2x 2x 2153x 2153x 2153x       2153x 2153x 2153x       2153x 2153x 2153x 2153x 2153x       2153x 704x 15490x 73x                     73x 73x                                                                                                                                     73x 73x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 1x                                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 2x 1x 1x 2x 1x 5x 5x                                                     5x 1x 1x 1x 5x 2x 2x 2x 2x 5x           5x                 5x                                 5x   5x                                                                                                   5x   5x   5x   5x 73x 73x                               73x 73x 12x 12x 12x 12x 3x 3x     3x 12x 12x 12x 12x 9x 9x 9x           9x 9x 6x 6x 6x 6x 6x 6x 4x 9x 3x 3x 9x 6x 6x 6x 12x         3x 1x 1x 1x 1x 1x 3x 2x 2x 12x 12x 12x 10x 12x                         12x     12x                                         12x   12x 12x 12x 12x 12x 10x 12x 73x 73x 73x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 8x 8x 19x 6x 6x 19x 5x 19x   19x 73x 73x 2x 2x           2x     2x 2x           2x 2x 2x     2x 2x       2x 2x 73x 73x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 73x 73x               73x 73x                             73x 73x                                                                                                             73x 73x 49x 49x 49x 49x 49x 49x 49x 49x 49x 49x 73x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 73x 73x                                                                                           73x 73x                                                                                                                                                                                     73x 73x                 73x 73x           73x 73x     73x 73x 838x 838x 838x 838x     838x 838x 838x 838x 838x 2x 838x 838x 826x 838x                     838x 25x 25x 25x 25x 25x 25x 25x 8x 838x 378x 378x 378x 367x 838x 1x 1x 1x 1x 1x 838x 53x 53x 53x 53x   53x 53x 53x 53x 53x 52x 52x 52x 838x 96x 96x 49x 49x 49x 47x 47x 2x 2x 96x 96x 34x 838x 273x 838x 735x 838x 73x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x 72x  
// muse.js — Monster item use AI (port of muse.c)
// Handles monsters using items defensively, offensively, and miscellaneously.
import { game } from './gstate.js';
import { rn2, rnd, rn1, c_d, rn2_on_display_rng } from './rng.js';
import { pline, You, You_hear, You_feel, pline_The, verbalize } from './pline.js';
import { Antimagic, Blind, BlindedTimeout, Deaf, Fire_resistance, Half_spell_damage, Hallucination, In_endgame, In_quest, In_V_tower, Inhell, Invis, Maybe_Half_Phys, See_invisible, Teleport_control, Unaware } from './macros.js';
import { cansee, couldsee } from './vision.js';
import { accessible, mon_would_take_item } from './monmove.js';
import { unbless, unknow_object } from './mkobj.js';
import { canseemon, canspotmon, cls, display_nhwindow, display_self, docrt, find_ac, flush_screen, map_invisible, mon_to_glyph, newsym, recalc_block_point, seemimic, shieldeff, show_glyph } from './display.js';
import { levl, m_at, obj_at, t_at } from './map_access.js';
import { depth, dist2, distmin, MON_WEP, monnear, monverbself, on_level, s_suffix, sgn, strsubst, surface, unsolid, upstart } from './hacklib.js';
// rn1 imported above from rng.js
import { acidic, amorphous, attacktype, attacktype_fordmg, can_blow, cvt_adtyp_to_mseenres, dmgtype, haseyes, hates_light, is_animal, is_floater, is_flyer, is_mercenary, is_mindless, is_undead, is_unicorn, is_vampshifter, locomotion, m_seenres, mdistu, mon_hates_silver, mon_knows_traps, mon_learns_traps, monsndx, monstseesu, monstunseesu, needspick, nohands, noncorporeal, nonliving, objdescr_is, passes_walls, perceives, poly_when_stoned, resists_acid, resists_blnd, resists_cold, resists_fire, resists_magm, resists_ston, same_race, slimeproof, throws_rocks, touch_petrifies, verysmall } from './mondata.js';
import { hard_helmet } from './do_wear.js';
import { find_mac, mon_set_minvis, which_armor, Dragon_scales_to_pm, Dragon_mail_to_pm } from './worn.js';
import { mon_adjust_speed, extract_from_minvent } from './worn.js';
import { lined_up, linedup_callback, m_carrying, m_useup } from './mthrowu.js';
import { m_throw } from './mthrowu.js';
import { enexto, makemon } from './makemon.js';
import { bcsign, splitobj, obj_extract_self, obfree, add_to_container,
         weight, place_object, sobj_at } from './mkobj.js';
import { DEADMONSTER, Monnam, Some_Monnam, a_monnam, healmon, m_next2u, maybe_unhide_at, mhe, mhim, mon_nam, mondead, monflee, mongone, newcham, noit_mon_nam, stop_occupation, unturn_dead, wakeup } from './mon.js';
import { helpless, losehp, monkilled, NODIAG } from './hack.js';
import { an, ansimpleoname, distant_name, doname, makeplural, simpleonames, singular, vtense, xname } from './objnam.js';
import { is_plural } from './objnam.js';
import { makeknown, carrying, freeinv, observe_object } from './invent.js';
import { closed_door, grow_up, onscary } from './monmove.js';
import { stairway_at } from './stairs.js';
import { any_quest_artifact } from './artifact.js';
import { artilist, SPFX_REFLECT } from './artifacts.js';
import { rloc, tele, tele_restrict, noteleport_level } from './teleport.js';
import { fill_pit, maketrap, mintrap, seetrap, trapname, unconscious } from './trap.js';
import { migrate_to_level, set_malign } from './dog.js';
import { dog_nutrition } from './dogmove.js';
import { can_carry } from './dogmove.js';
import { mpickobj } from './steal.js';
import { remove_worn_item } from './steal.js';
import { welded } from './wield.js';
import { mwelded } from './wield.js';
import { bhito, buzz, BZ_OFS_WAN, cancel_monst, exclam, hit, miss, resist, resist_death, zhitm } from './zap.js';
import { awaken_soldiers } from './music.js';
import { body_part } from './polyself.js';
import { begin_burn } from './light.js';
import { hcolor, rndmonnam } from './do_name.js';
import { rndmonst } from './makemon.js';
import { dropy, canletgo, trycall } from './do.js';
import { explode } from './explode.js';
import { doorlock } from './lock.js';
import { worm_move } from './worm.js';
import { get_level, ledger_no, dunlev, dunlevs_in_dungeon } from './dungeon.js';
import { place_monster, remove_monster } from './steed.js';
import { add_damage, in_rooms, inhishop } from './shk.js';
import { ARTICLE_A, AUGMENT_IT, BEAR_TRAP, BOLT_LIM, BZ_OFS_AD, CORR, D_BROKEN, D_CLOSED, D_LOCKED, DRAWBRIDGE_UP, FIRE_TRAP, FORCEBUNGLE, FORCETRAP, G_GONE, HAND, Has_contents, HOLE, IS_AIR, Is_botlevel, IS_DOOR, IS_DRAWBRIDGE, Is_earthlevel, IS_FURNITURE, is_hole, IS_OBSTRUCTED, is_pit, Is_rogue_level, isok, KILLED_BY_AN, M_SEEN_ACID, M_SEEN_COLD, M_SEEN_ELEC, M_SEEN_FIRE, M_SEEN_MAGR, M_SEEN_REFL, M_SEEN_SLEEP, MFAST, MIGR_LADDER_DOWN, MIGR_LADDER_UP, MIGR_RANDOM, MIGR_SSTAIRS, MIGR_STAIRS_DOWN, MIGR_STAIRS_UP, MM_NOMSG, NC_SHOW_MSG, NC_VIA_WAND_OR_SPELL, NO_MM_FLAGS, NON_PM, NORMAL_SPEED, OBJ_AT, PIT, POLY_TRAP, RLOC_MSG, SCORR, SDOOR, SHOPBASE, STRAT_WAITFORU, TELEP_TRAP, TEMPLE, TRAPDOOR, u_at, W_AMUL, W_ARM, W_ARMC, W_ARMF, W_ARMG, W_ARMH, W_ARMS, W_ART, W_WEP, WAND_BACKFIRE_CHANCE, WEB, XKILL_NOCONDUCT, XKILL_NOMSG, ZAP_POS } from './const.js';
import { G_UNIQ } from './monsters.js';
import { AMULET_CLASS, AMULET_OF_GUARDING, AMULET_OF_LIFE_SAVING, AMULET_OF_REFLECTION, AMULET_OF_YENDOR, BAG_OF_TRICKS, BELL_OF_OPENING, BOULDER, BUGLE, BULLWHIP, CANDELABRUM_OF_INVOCATION, CORPSE, EGG, EXPENSIVE_CAMERA, FIRE_HORN, FOOD_CLASS, FROST_HORN, GLOB_OF_GREEN_SLIME, HEAVY_IRON_BALL, ICE_BOX, Is_container, Is_dragon_mail, Is_dragon_scales, PICK_AXE, POT_ACID, POT_BLINDNESS, POT_CONFUSION, POT_EXTRA_HEALING, POT_FULL_HEALING, POT_GAIN_LEVEL, POT_HEALING, POT_INVISIBILITY, POT_OIL, POT_PARALYSIS, POT_POLYMORPH, POT_SICKNESS, POT_SLEEPING, POT_SPEED, POTION_CLASS, SchroedingersBox, SCR_CREATE_MONSTER, SCR_EARTH, SCR_FIRE, SCR_TELEPORTATION, SCROLL_CLASS, SHIELD_OF_REFLECTION, SILVER_DRAGON_SCALE_MAIL, SILVER_DRAGON_SCALES, SPE_BOOK_OF_THE_DEAD, STRANGE_OBJECT, TIN, TIN_OPENER, TOOL_CLASS, UNICORN_HORN, WAN_CANCELLATION, WAN_COLD, WAN_CREATE_MONSTER, WAN_DEATH, WAN_DIGGING, WAN_FIRE, WAN_LIGHTNING, WAN_LOCKING, WAN_MAGIC_MISSILE, WAN_MAKE_INVISIBLE, WAN_OPENING, WAN_POLYMORPH, WAN_SLEEP, WAN_SPEED_MONSTER, WAN_STRIKING, WAN_TELEPORTATION, WAN_UNDEAD_TURNING, WAND_CLASS, WEAPON_CLASS } from './objects.js';
import {
    mons, PM_GHOST, PM_DJINNI, PM_PESTILENCE, PM_GUARD, PM_KI_RIN,
    PM_GIANT_EEL, PM_CROCODILE, PM_ACID_BLOB, PM_LIZARD, PM_STALKER,
    PM_SILVER_DRAGON, PM_CHROMATIC_DRAGON, PM_GREEN_SLIME, PM_VLAD_THE_IMPALER,
    S_GHOST, S_KOP, S_GOLEM, AT_EXPL, AT_BREA, AT_GAZE,
    AD_FIRE, AD_COLD, AD_HEAL, AD_RBRE,
} from './monsters.js';
import { CLR_GREEN, CLR_BRIGHT_GREEN } from './terminal.js';
import { SetVoice, Soundeffect } from './sounds.js';
import { Can_fall_thru, destroy_drawbridge, find_drawbridge, is_drawbridge_wall, is_ice, is_lava, is_pool } from './dbridge.js';
import { in_your_sanctuary } from './priest.js';
import { nomul } from './cmd.js';
import { paralyze_monst } from './mhitm.js';
import { drop_boulder_on_monster, drop_boulder_on_player, flash_mon } from './read.js';
import { xkilled } from './uhitm.js';
import { Sokoban } from './mklev.js';
import { Can_dig_down, ceiling } from './dig.js';
import { mon_has_amulet, mon_has_special } from './wizard.js';
import { Is_knox } from './botl.js';
import { fobj_at, Is_mbag } from './pickup.js';
// ── MUSE constants (defensive) ──
const MUSE_SCR_TELEPORTATION = 1;
const MUSE_WAN_TELEPORTATION_SELF = 2;
const MUSE_POT_HEALING = 3;
const MUSE_POT_EXTRA_HEALING = 4;
const MUSE_WAN_DIGGING = 5;
const MUSE_TRAPDOOR = 6;
const MUSE_TELEPORT_TRAP = 7;
const MUSE_UPSTAIRS = 8;
const MUSE_DOWNSTAIRS = 9;
const MUSE_WAN_CREATE_MONSTER = 10;
const MUSE_SCR_CREATE_MONSTER = 11;
const MUSE_UP_LADDER = 12;
const MUSE_DN_LADDER = 13;
const MUSE_SSTAIRS = 14;
const MUSE_WAN_TELEPORTATION = 15;
const MUSE_BUGLE = 16;
const MUSE_UNICORN_HORN = 17;
const MUSE_POT_FULL_HEALING = 18;
const MUSE_LIZARD_CORPSE = 19;
const MUSE_WAN_UNDEAD_TURNING_DEF = 20;
// ── MUSE constants (offensive) ──
const MUSE_OFF_WAN_DEATH = 1;
const MUSE_OFF_WAN_SLEEP = 2;
const MUSE_OFF_WAN_FIRE = 3;
const MUSE_OFF_WAN_COLD = 4;
const MUSE_OFF_WAN_LIGHTNING = 5;
const MUSE_OFF_WAN_MAGIC_MISSILE = 6;
const MUSE_OFF_WAN_STRIKING = 7;
const MUSE_OFF_SCR_FIRE = 8;
const MUSE_OFF_POT_PARALYSIS = 9;
const MUSE_OFF_POT_BLINDNESS = 10;
const MUSE_OFF_POT_CONFUSION = 11;
const MUSE_OFF_FROST_HORN = 12;
const MUSE_OFF_FIRE_HORN = 13;
const MUSE_OFF_POT_ACID = 14;
const MUSE_OFF_WAN_TELEPORTATION = 15;
const MUSE_OFF_POT_SLEEPING = 16;
const MUSE_OFF_SCR_EARTH = 17;
const MUSE_OFF_CAMERA = 18;
const MUSE_OFF_WAN_UNDEAD_TURNING = 20;
// ── MUSE constants (misc) ──
const MUSE_MISC_POT_GAIN_LEVEL = 1;
const MUSE_MISC_WAN_MAKE_INVISIBLE = 2;
const MUSE_MISC_POT_INVISIBILITY = 3;
const MUSE_MISC_POLY_TRAP = 4;
const MUSE_MISC_WAN_POLYMORPH = 5;
const MUSE_MISC_POT_SPEED = 6;
const MUSE_MISC_WAN_SPEED_MONSTER = 7;
const MUSE_MISC_BULLWHIP = 8;
const MUSE_MISC_POT_POLYMORPH = 9;
const MUSE_MISC_BAG = 10;
// ── Module-level state (C static: gm.m) ──
// ── Local stubs for unported functions ──
// Some_Monnam: imported from mon.js
// mon_to_glyph: imported from display.js
// monverbself: imported from hacklib.js
// mon_has_amulet: imported from wizard.js
// mon_has_special: imported from wizard.js
function On_W_tower_level(uz) { return false; } // TODO
// C ref: monst.h:220 is_Vlad — check if monster is Vlad the Impaler
function is_Vlad(mtmp) {
    return mtmp.data === mons[PM_VLAD_THE_IMPALER] || mtmp.cham === PM_VLAD_THE_IMPALER;
}
// Sokoban: imported from mklev.js
// Can_dig_down: imported from dig.js
// Can_fall_thru: imported from dbridge.js
// TODO
// ledger_no, dunlev, dunlevs_in_dungeon: imported from dungeon.js
// get_level: imported from dungeon.js
// C ref: teleport.c:2190 — random_teleport_level: pick random dungeon depth
function random_teleport_level() {
    const cur_depth = depth(game.u?.uz);
    // rn2(5) chance to stay put, or if single branch / endgame
    if (!rn2(5) || Is_knox(game.u?.uz) || In_endgame(game.u?.uz))
        return cur_depth;
    let min_depth, max_depth;
    if (In_quest(game.u?.uz)) {
        min_depth = game.dungeons?.[game.u.uz.dnum]?.depth_start || 1;
        max_depth = dunlevs_in_dungeon(game.u?.uz)
            + (game.dungeons?.[game.u.uz.dnum]?.depth_start || 1) - 1;
    } else {
        min_depth = 1;
        max_depth = dunlevs_in_dungeon(game.u?.uz)
            + (game.dungeons?.[game.u.uz.dnum]?.depth_start || 1) - 1;
        if (Inhell() && !game.u?.uevent?.invoked)
            max_depth -= 1;
    }
    let nlev = rn2(cur_depth + 3 - min_depth) + min_depth;
    if (nlev >= cur_depth) nlev++;
    if (nlev > max_depth) nlev = max_depth;
    if (nlev < min_depth) nlev = min_depth;
    return nlev;
}
function Can_rise_up(x, y, uz) { return false; } // TODO
// ceiling: imported from dig.js
function is_bat(ptr) { return ptr && (ptr.mname === 'bat' || ptr.mname === 'giant bat' || ptr.mname === 'vampire bat'); }
// slimeproof imported from mondata.js
// maybe_unhide_at: imported from mon.js
// SchroedingersBox: imported from objects.js
// Is_dragon_scales: imported from objects.js
// Is_dragon_mail: imported from objects.js
// Dragon_scales_to_pm, Dragon_mail_to_pm: imported from worn.js
 // TODO
// display_self: imported from display.js
// show_glyph: imported from display.js
// TODO
// TODO
// unknow_object: imported from mkobj.js
// C ref: hack.h — POTION_OCCUPANT_CHANCE(n) (13 + 2 * (n))
function POTION_OCCUPANT_CHANCE(n) { return 13 + 2 * (n || 0); }
// mon_would_take_item: imported from monmove.js
// C ref: muse.c:1344 — hero_behind_chokepoint: is hero behind a corridor chokepoint
function hero_behind_chokepoint(mtmp) {
    // Direction arrays from decl.c
    const xd = [-1, -1, 0, 1, 1, 1, 0, -1];
    const yd = [0, -1, -1, -1, 0, 1, 1, 1];
    const N_DIRS = 8;
    const dx = sgn(mtmp.mx - (mtmp.mux ?? game.u?.ux ?? 0));
    const dy = sgn(mtmp.my - (mtmp.muy ?? game.u?.uy ?? 0));
    const x = (mtmp.mux ?? game.u?.ux ?? 0) + dx;
    const y = (mtmp.muy ?? game.u?.uy ?? 0) + dy;
    // xytodir
    let dir = -1;
    for (let dd = 0; dd < N_DIRS; dd++)
        if (dx === xd[dd] && dy === yd[dd]) { dir = dd; break; }
    if (dir < 0) return false;
    const dir_l = ((dir + 6) % N_DIRS); // DIR_LEFT2
    const dir_r = ((dir + 2) % N_DIRS); // DIR_RIGHT2
    const c1x = x + xd[dir_l], c1y = y + yd[dir_l];
    const c2x = x + xd[dir_r], c2y = y + yd[dir_r];
    return (!isok(c1x, c1y) || !accessible(c1x, c1y))
        && (!isok(c2x, c2y) || !accessible(c2x, c2y));
}
// C ref: muse.c:1371 — mon_has_friends: hostile monster has another hostile adjacent
function mon_has_friends(mtmp) {
    if (mtmp.mtame || mtmp.mpeaceful) return false;
    for (let dx = -1; dx <= 1; dx++)
        for (let dy = -1; dy <= 1; dy++) {
            const x = mtmp.mx + dx, y = mtmp.my + dy;
            if (isok(x, y)) {
                const mon2 = m_at(x, y);
                if (mon2 && mon2 !== mtmp && !mon2.mtame && !mon2.mpeaceful)
                    return true;
            }
        }
    return false;
}
// C ref: muse.c:1395 — mon_likes_objpile_at: monster wants items at location
function mon_likes_objpile_at(mtmp, x, y) {
    if (!isok(x, y)) return false;
    let otmp = fobj_at(x, y);
    if (!otmp) return false;
    // monster likes any of the top 3 items in the pile?
    let i = 0;
    for (; otmp && i < 3; i++, otmp = otmp.nexthere) {
        if (mon_would_take_item(mtmp, otmp)) return true;
    }
    // pile is larger than 3 stacks?
    return i >= 3;
}
// accessible: imported from monmove.js
// C ref: artifact.c:537 arti_reflects — does artifact provide reflection?
function arti_reflects(obj) {
    if (!obj?.oartifact) return false;
    const arti = artilist[obj.oartifact];
    if (!arti) return false;
    if ((obj.owornmask & ~W_ART) && (arti.spfx & SPFX_REFLECT)) return true;
    if (arti.cspfx & SPFX_REFLECT) return true;
    return false;
}
// flash_mon: imported from read.js
import { lightdamage, unturn_you } from './zap.js';
// drop_boulder_on_monster: imported from read.js
 // TODO
function removed_from_icebox(obj) { } // TODO
// unturn_you: imported from zap.js
// unturn_dead: imported from mon.js
// C ref: decl.h — uskin: dragon scales merged into player's body
function uskin() { return game.u?.uskin ?? null; }
 // const
 // TODO: import from cmd.js
// C: fakename[0] used for vtense subject; any string works
const fakename = ['someone'];
// C: Trap_Killed_Mon return value from mintrap
const Trap_Killed_Mon = 4; // from const.js if available
// BZ_OFS_AD: imported from const.js
function BZ_M_WAND(bztyp) { return 30 + bztyp; } // C: (30 + (x))
// ── trapname (from const.js or trap.js) ──
// C: W_NONDIGGABLE etc.
const W_NONDIGGABLE = 8;
// ── precheck (C ref: muse.c:58) ──
async function precheck(mon, obj) {
    if (!obj) return 0;
    const vis = cansee(mon.mx, mon.my);
    if (obj.oclass === POTION_CLASS) {
        const cc = {};
        const empty_msg = "The potion turns out to be empty.";
        if (objdescr_is(obj, 'milky')) {
            if (!(game.mvitals?.[PM_GHOST]?.mvflags & G_GONE)
                && !rn2(POTION_OCCUPANT_CHANCE(game.mvitals?.[PM_GHOST]?.born || 0))) {
                if (!enexto(cc, mon.mx, mon.my, mons[PM_GHOST]))
                    return 0;
                await mquaffmsg(mon, obj);
                await m_useup(mon, obj);
                const mtmp = await makemon(mons[PM_GHOST], cc.x, cc.y, MM_NOMSG);
                if (!mtmp) {
                    if (vis) await pline(empty_msg);
                } else {
                    if (vis) {
                        await pline(`As ${mon_nam(mon)} opens the bottle, an enormous ${Hallucination() ? rndmonnam(null) : 'ghost'} emerges!`);
                        await pline(`${Monnam(mon)} is frightened to death, and unable to move.`);
                    }
                    paralyze_monst(mon, 3);
                }
                return 2;
            }
        }
        if (objdescr_is(obj, 'smoky')
            && !(game.mvitals?.[PM_DJINNI]?.mvflags & G_GONE)
            && !rn2(POTION_OCCUPANT_CHANCE(game.mvitals?.[PM_DJINNI]?.born || 0))) {
            if (!enexto(cc, mon.mx, mon.my, mons[PM_DJINNI]))
                return 0;
            await mquaffmsg(mon, obj);
            await m_useup(mon, obj);
            const mtmp = await makemon(mons[PM_DJINNI], cc.x, cc.y, MM_NOMSG);
            if (!mtmp) {
                if (vis) await pline(empty_msg);
            } else {
                if (vis)
                    await pline(`In a cloud of smoke, ${a_monnam(mtmp)} emerges!`);
                await pline(`${vis ? Monnam(mtmp) : 'Something'} speaks.`);
                SetVoice(mtmp, 0, 80, 0);
                if (rn2(2)) {
                    await verbalize("You freed me!");
                    mtmp.mpeaceful = 1;
                    set_malign(mtmp);
                } else {
                    await verbalize("It is about time.");
                    if (vis)
                        await pline(`${Monnam(mtmp)} vanishes.`);
                    mongone(mtmp);
                }
            }
            return 2;
        }
    }
    if (obj.oclass === WAND_CLASS && obj.cursed
        && !rn2(WAND_BACKFIRE_CHANCE)) {
        const dam = c_d(obj.spe + 2, 6);
        if (vis) {
            await pline(`${Monnam(mon)} zaps ${an(xname(obj))}, which suddenly explodes!`);
        } else {
            const range = couldsee(mon.mx, mon.my)
                           ? (BOLT_LIM + 1) : (BOLT_LIM - 3);
            Soundeffect('se_zap_then_explosion', 100);
            await You_hear(`a zap and an explosion ${(mdistu(mon) <= range * range) ? 'nearby' : 'in the distance'}.`);
        }
        await m_useup(mon, obj);
        mon.mhp -= dam;
        if (DEADMONSTER(mon)) {
            await monkilled(mon, "", AD_RBRE);
            return 1;
        }
        game.m_has_defense = game.m_has_offense = game.m_has_misc = 0;
    }
    return 0;
}
// ── mzapwand (C ref: muse.c:164) ──
async function mzapwand(mtmp, otmp, self) {
    if (otmp.spe < 1) return;
    if (!canseemon(mtmp)) {
        const range = couldsee(mtmp.mx, mtmp.my)
                       ? (BOLT_LIM + 1) : (BOLT_LIM - 3);
        Soundeffect('se_zap', 100);
        await You_hear(`a ${(mdistu(mtmp) <= range * range) ? 'nearby' : 'distant'} zap.`);
        unknow_object(otmp);
    } else if (self) {
        await pline(`${monverbself(mtmp, Monnam(mtmp), 'zap', null)} with ${doname(otmp)}!`);
    } else {
        await pline(`${Monnam(mtmp)} zaps ${an(xname(otmp))}!`);
        await stop_occupation();
    }
    otmp.spe -= 1;
}
// ── mplayhorn (C ref: muse.c:194) ──
async function mplayhorn(mtmp, otmp, self) {
    if (!canseemon(mtmp)) {
        const range = couldsee(mtmp.mx, mtmp.my)
                       ? (BOLT_LIM + 1) : (BOLT_LIM - 3);
        Soundeffect('se_horn_being_played', 50);
        await You_hear(`a horn being played ${(mdistu(mtmp) <= range * range) ? 'nearby' : 'in the distance'}.`);
        unknow_object(otmp);
    } else if (self) {
        observe_object(otmp);
        let objnamp = xname(otmp);
        const objbuf = `a ${objnamp} directed at`;
        await pline(`${monverbself(mtmp, Monnam(mtmp), 'play', objbuf)}!`);
        makeknown(otmp.otyp);
    } else {
        observe_object(otmp);
        let objnamp = xname(otmp);
        await pline(`${Monnam(mtmp)} plays ${an(objnamp)} directed at you!`);
        makeknown(otmp.otyp);
        await stop_occupation();
    }
    otmp.spe -= 1;
}
// ── mreadmsg (C ref: muse.c:237) ──
async function mreadmsg(mtmp, otmp) {
    const vismon = canseemon(mtmp);
    if (!vismon && Deaf()) return;
    observe_object(otmp);
    const onambuf = singular(otmp, vismon ? doname : ansimpleoname);
    if (vismon) {
        await pline(`${Monnam(mtmp)} reads ${onambuf}!`);
    } else {
        let blindbuf = `reading ${onambuf}`;
        blindbuf = strsubst(blindbuf, 'reading a scroll labeled',
                     mtmp.mconf ? 'attempting to incant' : 'incant');
        await You_hear(`${mon_nam(mtmp)} ${blindbuf}.`);
    }
    if (mtmp.mconf)
        await pline(`Being confused, ${vismon ? mon_nam(mtmp) : mhe(mtmp)} mispronounces the magic words...`);
}
// ── mquaffmsg (C ref: muse.c:292) ──
async function mquaffmsg(mtmp, otmp) {
    if (canseemon(mtmp)) {
        observe_object(otmp);
        await pline(`${Monnam(mtmp)} drinks ${singular(otmp, doname)}!`);
    } else if (!Deaf()) {
        Soundeffect('se_mon_chugging_potion', 25);
        await You_hear("a chugging sound.");
    }
}
// objdescr_is imported from mondata.js
// ── m_use_healing (C ref: muse.c:336) ──
function m_use_healing(mtmp) {
    let obj;
    if ((obj = m_carrying(mtmp, POT_FULL_HEALING)) != null) {
        game.m_defensive = obj;
        game.m_has_defense = MUSE_POT_FULL_HEALING;
        return true;
    }
    if ((obj = m_carrying(mtmp, POT_EXTRA_HEALING)) != null) {
        game.m_defensive = obj;
        game.m_has_defense = MUSE_POT_EXTRA_HEALING;
        return true;
    }
    if ((obj = m_carrying(mtmp, POT_HEALING)) != null) {
        game.m_defensive = obj;
        game.m_has_defense = MUSE_POT_HEALING;
        return true;
    }
    return false;
}
// ── m_sees_sleepy_soldier (C ref: muse.c:360) ──
function m_sees_sleepy_soldier(mtmp) {
    const x = mtmp.mx, y = mtmp.my;
    for (let xx = x - 3; xx <= x + 3; xx++)
        for (let yy = y - 3; yy <= y + 3; yy++) {
            if (!isok(xx, yy) || (xx === x && yy === y))
                continue;
            const mon = m_at(xx, yy);
            if (mon && is_mercenary(mon.data)
                && mon.data !== mons[PM_GUARD]
                && helpless(mon))
                return true;
        }
    return false;
}
// ── m_tele (C ref: muse.c:383) ──
async function m_tele(mtmp, vismon, oseen, how) {
    if (tele_restrict(mtmp)) {
        if (vismon && how)
            makeknown(how);
        if (noteleport_level(mtmp))
            mon_learns_traps(mtmp, TELEP_TRAP);
    } else if ((mon_has_amulet(mtmp) || On_W_tower_level(game.u?.uz)) && !rn2(3)) {
        if (vismon)
            await pline(`${Monnam(mtmp)} seems disoriented for a moment.`);
    } else {
        if (how) {
            if (oseen)
                makeknown(how);
            await rloc(mtmp, RLOC_MSG);
        } else {
            mtmp.mx = game.trapx;
            mtmp.my = game.trapy;
            await mintrap(mtmp, FORCETRAP);
        }
    }
}
// ── m_next2m (C ref: muse.c:419) ──
function m_next2m(mtmp) {
    if (DEADMONSTER(mtmp)) return false;
    for (let x = mtmp.mx - 1; x <= mtmp.mx + 1; x++)
        for (let y = mtmp.my - 1; y <= mtmp.my + 1; y++) {
            if (!isok(x, y)) continue;
            const m2 = m_at(x, y);
            if (m2 && m2 !== mtmp) return true;
        }
    return false;
}
// ── find_defensive (C ref: muse.c:440) ──
export function find_defensive(mtmp, tryescape) {
    let obj;
    let t;
    const x = mtmp.mx, y = mtmp.my;
    const stuck = (mtmp === game.u?.ustuck);
    const immobile = (mtmp.data?.mmove === 0);
    game.m_defensive = null;
    game.m_has_defense = 0;
    if (is_animal(mtmp.data) || is_mindless(mtmp.data))
        return false;
    if (!tryescape && dist2(x, y, mtmp.mux, mtmp.muy) > 25)
        return false;
    if (tryescape && Is_knox(game.u?.uz)
        && !m_next2u(mtmp) && m_next2m(mtmp))
        return false;
    if (game.u?.uswallow && stuck)
        return false;
    // unicorn horn for confused/stunned/blind
    if (mtmp.mconf || mtmp.mstun || !mtmp.mcansee) {
        obj = null;
        if (!nohands(mtmp.data)) {
            for (obj = mtmp.minvent; obj; obj = obj.nobj)
                if (obj.otyp === UNICORN_HORN && !obj.cursed)
                    break;
        }
        if (obj || is_unicorn(mtmp.data) || mtmp.data === mons[PM_KI_RIN]) {
            game.m_defensive = obj;
            game.m_has_defense = MUSE_UNICORN_HORN;
            return true;
        }
    }
    if (mtmp.mconf || mtmp.mstun) {
        let liztin = null;
        for (obj = mtmp.minvent; obj; obj = obj.nobj) {
            if (obj.otyp === CORPSE && obj.corpsenm === PM_LIZARD) {
                game.m_defensive = obj;
                game.m_has_defense = MUSE_LIZARD_CORPSE;
                return true;
            } else if (obj.otyp === TIN && obj.corpsenm === PM_LIZARD) {
                liztin = obj;
            }
        }
        if (liztin && mcould_eat_tin(mtmp) && rn2(3)) {
            game.m_defensive = liztin;
            game.m_has_defense = MUSE_LIZARD_CORPSE;
            return true;
        }
    }
    // blind non-Pestilence tries healing to cure blindness
    if (!mtmp.mcansee && !nohands(mtmp.data)
        && mtmp.data !== mons[PM_PESTILENCE]) {
        if (m_use_healing(mtmp))
            return true;
    }
    // wand of undead turning against cockatrice-corpse-wielding hero
    if (!mtmp.mpeaceful && !nohands(mtmp.data)
        && game.u.uwep && game.u.uwep.otyp === CORPSE
        && touch_petrifies(mons[game.u.uwep.corpsenm])
        && !poly_when_stoned(mtmp.data) && !resists_ston(mtmp)
        && lined_up(mtmp)) {
        for (obj = mtmp.minvent; obj; obj = obj.nobj)
            if (obj.otyp === WAN_UNDEAD_TURNING && obj.spe > 0) {
                game.m_defensive = obj;
                game.m_has_defense = MUSE_WAN_UNDEAD_TURNING_DEF;
                return true;
            }
    }
    if (!tryescape) {
        const fraction = game.u?.ulevel < 10 ? 5 : game.u?.ulevel < 14 ? 4 : 3;
        if (mtmp.mhp >= mtmp.mhpmax
            || (mtmp.mhp >= 10 && mtmp.mhp * fraction >= mtmp.mhpmax))
            return false;
        if (mtmp.mpeaceful) {
            if (!nohands(mtmp.data)) {
                if (m_use_healing(mtmp))
                    return true;
            }
            return false;
        }
    }
    if (stuck || immobile || mtmp.mtrapped) {
        ; // can't flee via stairs/traps
    } else if (levl(x, y)?.typ === 26 /* STAIRS */) {
        const stway = stairway_at(x, y);
        if (stway && !stway.up && stway.tolev?.dnum === game.u?.uz?.dnum) {
            if (!is_floater(mtmp.data))
                game.m_has_defense = MUSE_DOWNSTAIRS;
        } else if (stway && stway.up && stway.tolev?.dnum === game.u?.uz?.dnum) {
            game.m_has_defense = MUSE_UPSTAIRS;
        } else if (stway && stway.tolev?.dnum !== game.u?.uz?.dnum) {
            if (stway.up || !is_floater(mtmp.data))
                game.m_has_defense = MUSE_SSTAIRS;
        }
    } else if (levl(x, y)?.typ === 27 /* LADDER */) {
        const stway = stairway_at(x, y);
        if (stway && stway.up && stway.tolev?.dnum === game.u?.uz?.dnum) {
            game.m_has_defense = MUSE_UP_LADDER;
        } else if (stway && !stway.up && stway.tolev?.dnum === game.u?.uz?.dnum) {
            if (!is_floater(mtmp.data))
                game.m_has_defense = MUSE_DN_LADDER;
        } else if (stway && stway.tolev?.dnum !== game.u?.uz?.dnum) {
            if (stway.up || !is_floater(mtmp.data))
                game.m_has_defense = MUSE_SSTAIRS;
        }
    } else {
        // check for trap doors and teleport traps
        const locs = [];
        const ignore_boulders = (verysmall(mtmp.data)
                                || throws_rocks(mtmp.data)
                                || passes_walls(mtmp.data));
        const diag_ok = !NODIAG(monsndx(mtmp.data));
        locs.push([x, y]);
        for (let xx = x - 1; xx <= x + 1; xx++)
            for (let yy = y - 1; yy <= y + 1; yy++)
                if (isok(xx, yy) && (xx !== x || yy !== y))
                    locs.push([xx, yy]);
        for (let i = 0; i < locs.length; i++) {
            const [xx, yy] = locs[i];
            if (u_at(xx, yy)
                || (xx !== x && yy !== y && !diag_ok)
                || (m_at(xx, yy) && !(xx === x && yy === y)))
                continue;
            t = t_at(xx, yy);
            if (!t
                || (!ignore_boulders && sobj_at(BOULDER, xx, yy))
                || onscary(xx, yy, mtmp))
                continue;
            if (is_hole(t.ttyp)
                && !is_floater(mtmp.data)
                && !mtmp.isshk && !mtmp.isgd && !mtmp.ispriest
                && Can_fall_thru(game.u?.uz)) {
                game.trapx = xx;
                game.trapy = yy;
                game.m_has_defense = MUSE_TRAPDOOR;
                break;
            } else if (t.ttyp === TELEP_TRAP) {
                game.trapx = xx;
                game.trapy = yy;
                game.m_has_defense = MUSE_TELEPORT_TRAP;
            }
        }
    }
    if (nohands(mtmp.data))
        return !!game.m_has_defense;
    if (is_mercenary(mtmp.data) && (obj = m_carrying(mtmp, BUGLE)) != null
        && m_sees_sleepy_soldier(mtmp)) {
        game.m_defensive = obj;
        game.m_has_defense = MUSE_BUGLE;
    }
    if (game.m_has_defense) // stairs, trap door, tele-trap, bugle
        return !!game.m_has_defense;
    // kludge to cut down on trap destruction
    t = t_at(x, y);
    if (t && (is_pit(t.ttyp) || t.ttyp === WEB || t.ttyp === BEAR_TRAP))
        t = null;
    for (obj = mtmp.minvent; obj; obj = obj.nobj) {
        if (game.m_has_defense && !rn2(3))
            break;
        if (game.m_has_defense === MUSE_WAN_DIGGING)
            break;
        if (obj.otyp === WAN_DIGGING && obj.spe > 0 && !stuck && !t
            && !mtmp.isshk && !mtmp.isgd && !mtmp.ispriest
            && !is_floater(mtmp.data)
            && !Sokoban()
            && !(levl(x, y)?.wall_info & W_NONDIGGABLE)
            && !(Is_botlevel(game.u?.uz) || In_endgame(game.u?.uz))
            && !(is_ice(x, y) || is_pool(x, y) || is_lava(x, y))
            && !(is_Vlad(mtmp) && In_V_tower(game.u?.uz))) {
            game.m_defensive = obj;
            game.m_has_defense = MUSE_WAN_DIGGING;
        }
        if (game.m_has_defense === MUSE_WAN_TELEPORTATION_SELF) continue;
        if (game.m_has_defense === MUSE_WAN_TELEPORTATION) continue;
        if (obj.otyp === WAN_TELEPORTATION && obj.spe > 0) {
            if (!noteleport_level(mtmp)
                || !mon_knows_traps(mtmp, TELEP_TRAP)) {
                game.m_defensive = obj;
                game.m_has_defense = mon_has_amulet(mtmp)
                                ? MUSE_WAN_TELEPORTATION
                                : MUSE_WAN_TELEPORTATION_SELF;
            }
        }
        if (game.m_has_defense === MUSE_SCR_TELEPORTATION) continue;
        if (obj.otyp === SCR_TELEPORTATION && mtmp.mcansee
            && haseyes(mtmp.data)
            && (!obj.cursed || (!(mtmp.isshk && inhishop(mtmp))
                                && !mtmp.isgd && !mtmp.ispriest))) {
            if (!noteleport_level(mtmp)
                || !mon_knows_traps(mtmp, TELEP_TRAP)) {
                game.m_defensive = obj;
                game.m_has_defense = MUSE_SCR_TELEPORTATION;
            }
        }
        if (mtmp.data !== mons[PM_PESTILENCE]) {
            if (game.m_has_defense === MUSE_POT_FULL_HEALING) continue;
            if (obj.otyp === POT_FULL_HEALING) {
                game.m_defensive = obj;
                game.m_has_defense = MUSE_POT_FULL_HEALING;
            }
            if (game.m_has_defense === MUSE_POT_EXTRA_HEALING) continue;
            if (obj.otyp === POT_EXTRA_HEALING) {
                game.m_defensive = obj;
                game.m_has_defense = MUSE_POT_EXTRA_HEALING;
            }
            if (game.m_has_defense === MUSE_WAN_CREATE_MONSTER) continue;
            if (obj.otyp === WAN_CREATE_MONSTER && obj.spe > 0) {
                game.m_defensive = obj;
                game.m_has_defense = MUSE_WAN_CREATE_MONSTER;
            }
            if (game.m_has_defense === MUSE_POT_HEALING) continue;
            if (obj.otyp === POT_HEALING) {
                game.m_defensive = obj;
                game.m_has_defense = MUSE_POT_HEALING;
            }
        } else { // Pestilence
            if (game.m_has_defense === MUSE_POT_FULL_HEALING) continue;
            if (obj.otyp === POT_SICKNESS) {
                game.m_defensive = obj;
                game.m_has_defense = MUSE_POT_FULL_HEALING;
            }
            if (game.m_has_defense === MUSE_WAN_CREATE_MONSTER) continue;
            if (obj.otyp === WAN_CREATE_MONSTER && obj.spe > 0) {
                game.m_defensive = obj;
                game.m_has_defense = MUSE_WAN_CREATE_MONSTER;
            }
        }
        if (game.m_has_defense === MUSE_SCR_CREATE_MONSTER) continue;
        if (obj.otyp === SCR_CREATE_MONSTER) {
            game.m_defensive = obj;
            game.m_has_defense = MUSE_SCR_CREATE_MONSTER;
        }
    }
    return !!game.m_has_defense;
}
// ── reveal_trap (C ref: muse.c:756) ──
function reveal_trap(t, seeit) {
    const lev = levl(t.tx, t.ty);
    if (lev && lev.typ === SCORR) {
        lev.typ = CORR;
        lev.flags = 0;
    }
    if (seeit)
        seetrap(t);
}
// ── mon_escape (C ref: muse.c:779) ──
async function mon_escape(mtmp, vismon) {
    if (mon_has_special(mtmp)
        || (mtmp.iswiz && (game.context?.no_of_wizards || 0) < 2))
        return 0;
    if (vismon)
        await pline(`${Monnam(mtmp)} escapes the dungeon!`);
    mongone(mtmp);
    return 2;
}
// ── use_defensive (C ref: muse.c:795) ──
export async function use_defensive(mtmp) {
    let i, fleetim;
    let otmp = game.m_defensive;
    let vis, vismon, oseen;
    let t;
    if ((i = await precheck(mtmp, otmp)) !== 0)
        return i;
    vis = cansee(mtmp.mx, mtmp.my);
    vismon = canseemon(mtmp);
    oseen = otmp && vismon;
    fleetim = !mtmp.mflee ? (33 - Math.trunc(30 * mtmp.mhp / mtmp.mhpmax)) : 0;
    async function m_flee(m) {
        if (fleetim && !m.iswiz) {
            await monflee(m, fleetim, false, false);
        }
    }
    switch (game.m_has_defense) {
    case MUSE_UNICORN_HORN:
        if (vismon) {
            if (otmp)
                await pline(`${Monnam(mtmp)} uses a unicorn horn!`);
            else
                await pline_The(`tip of ${mon_nam(mtmp)}'s horn glows!`);
        }
        if (!mtmp.mcansee) {
            await mcureblindness(mtmp, vismon);
        } else if (mtmp.mconf || mtmp.mstun) {
            mtmp.mconf = mtmp.mstun = 0;
            if (vismon)
                await pline(`${Monnam(mtmp)} seems steadier now.`);
        }
        return 2;
    case MUSE_BUGLE:
        if (vismon) {
            await pline(`${Monnam(mtmp)} plays ${doname(otmp)}!`);
        } else if (!Deaf()) {
            Soundeffect('se_bugle_playing_reveille', 100);
            await You_hear("a bugle playing reveille!");
        }
        await awaken_soldiers(mtmp);
        return 2;
    case MUSE_WAN_TELEPORTATION_SELF:
        if ((mtmp.isshk && inhishop(mtmp)) || mtmp.isgd || mtmp.ispriest)
            return 2;
        await m_flee(mtmp);
        await mzapwand(mtmp, otmp, true);
        await m_tele(mtmp, vismon, oseen, WAN_TELEPORTATION);
        return 2;
    case MUSE_WAN_TELEPORTATION:
        game.zap_oseen = oseen;
        await mzapwand(mtmp, otmp, false);
        game.m_using = true;
        await mbhit(mtmp, rn1(8, 6), mbhitm, bhito, otmp);
        if (noteleport_level(mtmp))
            mon_learns_traps(mtmp, TELEP_TRAP);
        game.m_using = false;
        return 2;
    case MUSE_SCR_TELEPORTATION: {
        let obj_is_cursed = otmp.cursed;
        if (mtmp.isshk || mtmp.isgd || mtmp.ispriest)
            return 2;
        await m_flee(mtmp);
        if (otmp.quan > 1)
            otmp = splitobj(otmp, 1);
        await extract_from_minvent(mtmp, otmp, false, false);
        await mreadmsg(mtmp, otmp);
        if (obj_is_cursed || mtmp.mconf) {
            const nlev = random_teleport_level();
            if (mon_has_amulet(mtmp) || In_endgame(game.u?.uz)) {
                if (vismon)
                    await pline(`${Monnam(mtmp)} seems very disoriented for a moment.`);
            } else if (nlev === depth(game.u?.uz)) {
                if (vismon)
                    await pline(`${Monnam(mtmp)} shudders for a moment.`);
            } else {
                const flev = {};
                get_level(flev, nlev);
                await migrate_to_level(mtmp, ledger_no(flev), MIGR_RANDOM, null);
            }
        } else {
            await m_tele(mtmp, vismon, oseen, SCR_TELEPORTATION);
        }
        if (otmp.dknown)
            await trycall(otmp);
        obfree(otmp, null);
        return 2;
    }
    case MUSE_WAN_DIGGING:
        await m_flee(mtmp);
        await mzapwand(mtmp, otmp, false);
        if (oseen)
            makeknown(WAN_DIGGING);
        if (IS_FURNITURE(levl(mtmp.mx, mtmp.my)?.typ)
            || IS_DRAWBRIDGE(levl(mtmp.mx, mtmp.my)?.typ)
            || (is_drawbridge_wall(mtmp.mx, mtmp.my) >= 0)
            || stairway_at(mtmp.mx, mtmp.my)) {
            await pline_The("digging ray is ineffective.");
            return 2;
        }
        if (!Can_dig_down(game.u?.uz) && !(levl(mtmp.mx, mtmp.my)?.candig)) {
            if (t_at(mtmp.mx, mtmp.my)
                || !(t = await maketrap(mtmp.mx, mtmp.my, PIT))) {
                if (vismon) {
                    await pline_The(`${surface(mtmp.mx, mtmp.my)} here is too hard to dig in.`);
                }
                return 2;
            }
            if (vis) {
                seetrap(t);
                await pline(`${Monnam(mtmp)} has made a pit in the ${surface(mtmp.mx, mtmp.my)}.`);
            }
            fill_pit(mtmp.mx, mtmp.my);
            recalc_block_point(mtmp.mx, mtmp.my);
            return (await mintrap(mtmp, FORCEBUNGLE) === Trap_Killed_Mon) ? 1 : 2;
        }
        t = await maketrap(mtmp.mx, mtmp.my, HOLE);
        if (!t)
            return 2;
        recalc_block_point(mtmp.mx, mtmp.my);
        seetrap(t);
        if (vis) {
            await pline(`${Monnam(mtmp)} has made a hole in the ${surface(mtmp.mx, mtmp.my)}.`);
            await pline(`${Monnam(mtmp)} ${is_flyer(mtmp.data) ? 'dives' : 'falls'} through...`);
        } else if (!Deaf()) {
            Soundeffect('se_crash_through_floor', 100);
            await You_hear(`something crash through the ${surface(mtmp.mx, mtmp.my)}.`);
        }
        fill_pit(mtmp.mx, mtmp.my);
        await migrate_to_level(mtmp, ledger_no(game.u?.uz) + 1, MIGR_RANDOM, null);
        return 2;
    case MUSE_WAN_UNDEAD_TURNING_DEF:
        game.zap_oseen = oseen;
        await mzapwand(mtmp, otmp, false);
        game.m_using = true;
        await mbhit(mtmp, rn1(8, 6), mbhitm, bhito, otmp);
        game.m_using = false;
        return 2;
    case MUSE_WAN_CREATE_MONSTER: {
        const cc = {};
        const pm = !is_pool(mtmp.mx, mtmp.my) ? null
                 : mons[game.u?.uinwater ? PM_GIANT_EEL : PM_CROCODILE];
        if (!enexto(cc, mtmp.mx, mtmp.my, pm))
            return 0;
        await mzapwand(mtmp, otmp, false);
        const mon = await makemon(null, cc.x, cc.y, NO_MM_FLAGS);
        if (mon && canspotmon(mon) && oseen)
            makeknown(WAN_CREATE_MONSTER);
        return 2;
    }
    case MUSE_SCR_CREATE_MONSTER: {
        const cc = {};
        let pm = null, fish = null;
        let cnt = 1;
        let known = false;
        if (!rn2(73))
            cnt += rnd(4);
        if (mtmp.mconf || otmp.cursed)
            cnt += 12;
        if (mtmp.mconf)
            pm = fish = mons[PM_ACID_BLOB];
        else if (is_pool(mtmp.mx, mtmp.my))
            fish = mons[game.u?.uinwater ? PM_GIANT_EEL : PM_CROCODILE];
        await mreadmsg(mtmp, otmp);
        while (cnt-- > 0) {
            if (!enexto(cc, mtmp.mx, mtmp.my, fish))
                break;
            const mon = await makemon(pm, cc.x, cc.y, NO_MM_FLAGS);
            if (mon && canspotmon(mon))
                known = true;
        }
        if (known)
            makeknown(SCR_CREATE_MONSTER);
        else
            await trycall(otmp);
        await m_useup(mtmp, otmp);
        return 2;
    }
    case MUSE_TRAPDOOR:
        if (Is_botlevel(game.u?.uz))
            return 0;
        await m_flee(mtmp);
        t = t_at(game.trapx, game.trapy);
        if (vis) {
            await pline(`${Monnam(mtmp)} ${vtense(fakename[0], locomotion(mtmp.data, 'jump'))} into a ${trapname(t.ttyp, false)}!`);
        }
        reveal_trap(t, vis);
        remove_monster(mtmp.mx, mtmp.my);
        newsym(mtmp.mx, mtmp.my);
        place_monster(mtmp, game.trapx, game.trapy);
        if (mtmp.wormno)
            worm_move(mtmp);
        newsym(game.trapx, game.trapy);
        await migrate_to_level(mtmp, ledger_no(game.u?.uz) + 1, MIGR_RANDOM, null);
        return 2;
    case MUSE_UPSTAIRS: {
        await m_flee(mtmp);
        const stway = stairway_at(mtmp.mx, mtmp.my);
        if (!stway) return 0;
        if (ledger_no(game.u?.uz) === 1)
            return await mon_escape(mtmp, vismon);
        if (Inhell() && mon_has_amulet(mtmp) && !rn2(4)
            && (dunlev(game.u?.uz) < dunlevs_in_dungeon(game.u?.uz) - 3)) {
            if (vismon)
                await pline(`As ${mon_nam(mtmp)} climbs the stairs, a mysterious force momentarily surrounds ${mhim(mtmp)}...`);
            await migrate_to_level(mtmp, ledger_no(game.u?.uz) + 1, MIGR_RANDOM, null);
        } else {
            if (vismon)
                await pline(`${Monnam(mtmp)} escapes upstairs!`);
            await migrate_to_level(mtmp, ledger_no(stway.tolev), MIGR_STAIRS_DOWN, null);
        }
        return 2;
    }
    case MUSE_DOWNSTAIRS: {
        await m_flee(mtmp);
        const stway = stairway_at(mtmp.mx, mtmp.my);
        if (!stway) return 0;
        if (vismon)
            await pline(`${Monnam(mtmp)} escapes downstairs!`);
        await migrate_to_level(mtmp, ledger_no(stway.tolev), MIGR_STAIRS_UP, null);
        return 2;
    }
    case MUSE_UP_LADDER: {
        await m_flee(mtmp);
        const stway = stairway_at(mtmp.mx, mtmp.my);
        if (!stway) return 0;
        if (vismon)
            await pline(`${Monnam(mtmp)} escapes up the ladder!`);
        await migrate_to_level(mtmp, ledger_no(stway.tolev), MIGR_LADDER_DOWN, null);
        return 2;
    }
    case MUSE_DN_LADDER: {
        await m_flee(mtmp);
        const stway = stairway_at(mtmp.mx, mtmp.my);
        if (!stway) return 0;
        if (vismon)
            await pline(`${Monnam(mtmp)} escapes down the ladder!`);
        await migrate_to_level(mtmp, ledger_no(stway.tolev), MIGR_LADDER_UP, null);
        return 2;
    }
    case MUSE_SSTAIRS: {
        await m_flee(mtmp);
        const stway = stairway_at(mtmp.mx, mtmp.my);
        if (!stway) return 0;
        if (ledger_no(game.u?.uz) === 1)
            return await mon_escape(mtmp, vismon);
        if (vismon)
            await pline(`${Monnam(mtmp)} escapes ${stway.up ? 'up' : 'down'}stairs!`);
        await migrate_to_level(mtmp, ledger_no(stway.tolev), MIGR_SSTAIRS, null);
        return 2;
    }
    case MUSE_TELEPORT_TRAP:
        await m_flee(mtmp);
        t = t_at(game.trapx, game.trapy);
        if (vis) {
            await pline(`${Monnam(mtmp)} ${vtense(fakename[0], locomotion(mtmp.data, 'jump'))} onto a ${trapname(t.ttyp, false)}!`);
        }
        reveal_trap(t, vis);
        remove_monster(mtmp.mx, mtmp.my);
        newsym(mtmp.mx, mtmp.my);
        place_monster(mtmp, game.trapx, game.trapy);
        if (mtmp.wormno)
            worm_move(mtmp);
        maybe_unhide_at(mtmp.mx, mtmp.my);
        newsym(game.trapx, game.trapy);
        await m_tele(mtmp, vismon, false, 0);
        return 2;
    case MUSE_POT_HEALING:
        await mquaffmsg(mtmp, otmp);
        i = c_d(6 + 2 * bcsign(otmp), 4);
        healmon(mtmp, i, 1);
        if (!otmp.cursed && !mtmp.mcansee)
            await mcureblindness(mtmp, vismon);
        if (vismon)
            await pline(`${Monnam(mtmp)} looks better.`);
        if (oseen)
            makeknown(POT_HEALING);
        await m_useup(mtmp, otmp);
        return 2;
    case MUSE_POT_EXTRA_HEALING:
        await mquaffmsg(mtmp, otmp);
        i = c_d(6 + 2 * bcsign(otmp), 8);
        healmon(mtmp, i, otmp.blessed ? 5 : 2);
        if (!mtmp.mcansee)
            await mcureblindness(mtmp, vismon);
        if (vismon)
            await pline(`${Monnam(mtmp)} looks much better.`);
        if (oseen)
            makeknown(POT_EXTRA_HEALING);
        await m_useup(mtmp, otmp);
        return 2;
    case MUSE_POT_FULL_HEALING:
        await mquaffmsg(mtmp, otmp);
        if (otmp.otyp === POT_SICKNESS)
            unbless(otmp);
        healmon(mtmp, mtmp.mhpmax, otmp.blessed ? 8 : 4);
        if (!mtmp.mcansee && otmp.otyp !== POT_SICKNESS)
            await mcureblindness(mtmp, vismon);
        if (vismon)
            await pline(`${Monnam(mtmp)} looks completely healed.`);
        if (oseen)
            makeknown(otmp.otyp);
        await m_useup(mtmp, otmp);
        return 2;
    case MUSE_LIZARD_CORPSE:
        await mon_consume_unstone(mtmp, otmp, false, false);
        return 2;
    case 0:
        return 0; // exploded wand
    default:
        break;
    }
    return 0;
}
// ── rnd_defensive_item (C ref: muse.c:1221) ──
export function rnd_defensive_item(mtmp) {
    const pm = mtmp.data;
    const difficulty = mons[monsndx(pm)]?.difficulty || 0;
    let trycnt = 0;
    if (is_animal(pm) || attacktype(pm, AT_EXPL) || is_mindless(pm)
        || pm?.mlet === S_GHOST || pm?.mlet === S_KOP)
        return 0;
    for (;;) {
        switch (rn2(8 + (difficulty > 3 ? 1 : 0) + (difficulty > 6 ? 1 : 0) + (difficulty > 8 ? 1 : 0))) {
        case 6:
        case 9:
            if (noteleport_level(mtmp) && ++trycnt < 2)
                continue;
            if (!rn2(3))
                return WAN_TELEPORTATION;
            // FALLTHROUGH
        case 0:
        case 1:
            return SCR_TELEPORTATION;
        case 8:
        case 10:
            if (!rn2(3))
                return WAN_CREATE_MONSTER;
            // FALLTHROUGH
        case 2:
            return SCR_CREATE_MONSTER;
        case 3:
            return POT_HEALING;
        case 4:
            return POT_EXTRA_HEALING;
        case 5:
            return (mtmp.data !== mons[PM_PESTILENCE]) ? POT_FULL_HEALING : POT_SICKNESS;
        case 7:
            if (Sokoban() && rn2(4))
                continue;
            if (is_floater(pm) || mtmp.isshk || mtmp.isgd || mtmp.ispriest)
                return 0;
            return WAN_DIGGING;
        default:
            return 0;
        }
    }
}
// ── linedup_chk_corpse (C ref: muse.c:1293) ──
function linedup_chk_corpse(x, y) {
    return sobj_at(CORPSE, x, y) !== null;
}
// ── m_use_undead_turning (C ref: muse.c:1299) ──
function m_use_undead_turning(mtmp, obj) {
    if (!(obj.otyp === WAN_UNDEAD_TURNING && obj.spe > 0))
        return;
    if (carrying(CORPSE)
        || linedup_callback(
            game.u?.ux + sgn(mtmp.mux - mtmp.mx) * 3,
            game.u?.uy + sgn(mtmp.muy - mtmp.my) * 3,
            mtmp.mx, mtmp.my, linedup_chk_corpse)
    ) {
        game.m_offensive = obj;
        game.m_has_offense = MUSE_OFF_WAN_UNDEAD_TURNING;
    }
}
// ── find_offensive (C ref: muse.c:1420) ──
export function find_offensive(mtmp) {
    let obj;
    let reflection_skip;
    game.m_offensive = null;
    game.m_has_offense = 0;
    if (mtmp.mpeaceful || is_animal(mtmp.data) || is_mindless(mtmp.data)
        || nohands(mtmp.data))
        return false;
    if (game.u?.uswallow)
        return false;
    if (in_your_sanctuary(mtmp, 0, 0))
        return false;
    if (dmgtype(mtmp.data, AD_HEAL)
        && !game.u.uwep && !game.u.uarmu && !game.u.uarm && !game.u.uarmh
        && !game.u.uarms && !game.u.uarmg && !game.u.uarmc && !game.u.uarmf)
        return false;
    if (!lined_up(mtmp))
        return false;
    reflection_skip = (m_seenres(mtmp, M_SEEN_REFL)
                       || monnear(mtmp, mtmp.mux, mtmp.muy));
    const mtmp_helmet = which_armor(mtmp, W_ARMH);
    for (obj = mtmp.minvent; obj; obj = obj.nobj) {
        if (!reflection_skip) {
            if (game.m_has_offense === MUSE_OFF_WAN_DEATH) continue;
            if (obj.otyp === WAN_DEATH && obj.spe > 0
                && !m_seenres(mtmp, M_SEEN_MAGR)) {
                game.m_offensive = obj;
                game.m_has_offense = MUSE_OFF_WAN_DEATH;
            }
            if (game.m_has_offense === MUSE_OFF_WAN_SLEEP) continue;
            if (obj.otyp === WAN_SLEEP && obj.spe > 0 && (game.multi || 0) >= 0
                && !m_seenres(mtmp, M_SEEN_SLEEP)) {
                game.m_offensive = obj;
                game.m_has_offense = MUSE_OFF_WAN_SLEEP;
            }
            if (game.m_has_offense === MUSE_OFF_WAN_FIRE) continue;
            if (obj.otyp === WAN_FIRE && obj.spe > 0
                && !m_seenres(mtmp, M_SEEN_FIRE)) {
                game.m_offensive = obj;
                game.m_has_offense = MUSE_OFF_WAN_FIRE;
            }
            if (game.m_has_offense === MUSE_OFF_FIRE_HORN) continue;
            if (obj.otyp === FIRE_HORN && obj.spe > 0 && can_blow(mtmp)
                && !m_seenres(mtmp, M_SEEN_FIRE)) {
                game.m_offensive = obj;
                game.m_has_offense = MUSE_OFF_FIRE_HORN;
            }
            if (game.m_has_offense === MUSE_OFF_WAN_COLD) continue;
            if (obj.otyp === WAN_COLD && obj.spe > 0
                && !m_seenres(mtmp, M_SEEN_COLD)) {
                game.m_offensive = obj;
                game.m_has_offense = MUSE_OFF_WAN_COLD;
            }
            if (game.m_has_offense === MUSE_OFF_FROST_HORN) continue;
            if (obj.otyp === FROST_HORN && obj.spe > 0 && can_blow(mtmp)
                && !m_seenres(mtmp, M_SEEN_COLD)) {
                game.m_offensive = obj;
                game.m_has_offense = MUSE_OFF_FROST_HORN;
            }
            if (game.m_has_offense === MUSE_OFF_WAN_LIGHTNING) continue;
            if (obj.otyp === WAN_LIGHTNING && obj.spe > 0
                && !m_seenres(mtmp, M_SEEN_ELEC)) {
                game.m_offensive = obj;
                game.m_has_offense = MUSE_OFF_WAN_LIGHTNING;
            }
            if (game.m_has_offense === MUSE_OFF_WAN_MAGIC_MISSILE) continue;
            if (obj.otyp === WAN_MAGIC_MISSILE && obj.spe > 0
                && !m_seenres(mtmp, M_SEEN_MAGR)) {
                game.m_offensive = obj;
                game.m_has_offense = MUSE_OFF_WAN_MAGIC_MISSILE;
            }
        }
        if (game.m_has_offense === MUSE_OFF_WAN_UNDEAD_TURNING) continue;
        m_use_undead_turning(mtmp, obj);
        if (game.m_has_offense === MUSE_OFF_WAN_STRIKING) continue;
        if (obj.otyp === WAN_STRIKING && obj.spe > 0
            && !m_seenres(mtmp, M_SEEN_MAGR)) {
            game.m_offensive = obj;
            game.m_has_offense = MUSE_OFF_WAN_STRIKING;
        }
        if (game.m_has_offense === MUSE_OFF_WAN_TELEPORTATION) continue;
        if (obj.otyp === WAN_TELEPORTATION && obj.spe > 0
            && !Teleport_control()
            && (!noteleport_level(mtmp)
                || !mon_knows_traps(mtmp, TELEP_TRAP))
            && (onscary(game.u?.ux, game.u?.uy, mtmp)
                || (hero_behind_chokepoint(mtmp) && mon_has_friends(mtmp))
                || mon_likes_objpile_at(mtmp, game.u?.ux, game.u?.uy)
                || stairway_at(game.u?.ux, game.u?.uy))) {
            game.m_offensive = obj;
            game.m_has_offense = MUSE_OFF_WAN_TELEPORTATION;
        }
        if (game.m_has_offense === MUSE_OFF_POT_PARALYSIS) continue;
        if (obj.otyp === POT_PARALYSIS && (game.multi || 0) >= 0) {
            game.m_offensive = obj;
            game.m_has_offense = MUSE_OFF_POT_PARALYSIS;
        }
        if (game.m_has_offense === MUSE_OFF_POT_BLINDNESS) continue;
        if (obj.otyp === POT_BLINDNESS && !attacktype(mtmp.data, AT_GAZE)) {
            game.m_offensive = obj;
            game.m_has_offense = MUSE_OFF_POT_BLINDNESS;
        }
        if (game.m_has_offense === MUSE_OFF_POT_CONFUSION) continue;
        if (obj.otyp === POT_CONFUSION) {
            game.m_offensive = obj;
            game.m_has_offense = MUSE_OFF_POT_CONFUSION;
        }
        if (game.m_has_offense === MUSE_OFF_POT_SLEEPING) continue;
        if (obj.otyp === POT_SLEEPING
            && !m_seenres(mtmp, M_SEEN_SLEEP)) {
            game.m_offensive = obj;
            game.m_has_offense = MUSE_OFF_POT_SLEEPING;
        }
        if (game.m_has_offense === MUSE_OFF_POT_ACID) continue;
        if (obj.otyp === POT_ACID
            && !m_seenres(mtmp, M_SEEN_ACID)) {
            game.m_offensive = obj;
            game.m_has_offense = MUSE_OFF_POT_ACID;
        }
        if (game.m_has_offense === MUSE_OFF_SCR_EARTH) continue;
        if (obj.otyp === SCR_EARTH
            && (hard_helmet(mtmp_helmet) || mtmp.mconf
                || amorphous(mtmp.data) || passes_walls(mtmp.data)
                || noncorporeal(mtmp.data) || unsolid(mtmp.data) || !rn2(10))
            && dist2(mtmp.mx, mtmp.my, mtmp.mux, mtmp.muy) <= 2
            && mtmp.mcansee && haseyes(mtmp.data)
            && !Is_rogue_level(game.u?.uz)
            && (!In_endgame(game.u?.uz) || Is_earthlevel(game.u?.uz))) {
            game.m_offensive = obj;
            game.m_has_offense = MUSE_OFF_SCR_EARTH;
        }
        if (game.m_has_offense === MUSE_OFF_CAMERA) continue;
        if (obj.otyp === EXPENSIVE_CAMERA
            && ((!Blind() && !resists_blnd(game.youmonst || {}))
                || hates_light(game.youmonst?.data))
            && dist2(mtmp.mx, mtmp.my, mtmp.mux, mtmp.muy) <= 2
            && obj.spe > 0 && !rn2(6)) {
            game.m_offensive = obj;
            game.m_has_offense = MUSE_OFF_CAMERA;
        }
    }
    return !!game.m_has_offense;
}
// ── fhito_loc (C ref: muse.c:1706) ──
async function fhito_loc(obj, tx, ty, fhito_fn) {
    let hitanything = 0;
    if (!fhito_fn || !OBJ_AT(tx, ty))
        return false;
    let otmp = obj_at(tx, ty);
    while (otmp) {
        const next = otmp.nexthere;
        if (otmp.where === 1 /* OBJ_FLOOR */ && otmp.ox === tx && otmp.oy === ty)
            hitanything += await fhito_fn(otmp, obj);
        otmp = next;
    }
    return !!hitanything;
}
// bhitpos tracking for mbhit
// ── mbhit (C ref: muse.c:1733) ──
async function mbhit(mon, range, fhitm, fhito_fn, obj) {
    let mtmp;
    const otyp = obj.otyp;
    game.bhitpos_x = mon.mx;
    game.bhitpos_y = mon.my;
    const ddx = sgn(mon.mux - mon.mx);
    const ddy = sgn(mon.muy - mon.my);
    while (range-- > 0) {
        game.bhitpos_x += ddx;
        game.bhitpos_y += ddy;
        const x = game.bhitpos_x;
        const y = game.bhitpos_y;
        if (!isok(x, y)) {
            game.bhitpos_x -= ddx;
            game.bhitpos_y -= ddy;
            break;
        }
        if (u_at(game.bhitpos_x, game.bhitpos_y)) {
            await fhitm(game.youmonst || {}, obj);
            range -= 3;
        } else if ((mtmp = m_at(game.bhitpos_x, game.bhitpos_y)) != null) {
            if (cansee(game.bhitpos_x, game.bhitpos_y) && !canspotmon(mtmp))
                map_invisible(game.bhitpos_x, game.bhitpos_y);
            await fhitm(mtmp, obj);
            range -= 3;
        }
        if (await fhito_loc(obj, game.bhitpos_x, game.bhitpos_y, fhito_fn))
            range--;
        const ltyp = levl(game.bhitpos_x, game.bhitpos_y)?.typ || 0;
        let dbx = x, dby = y;
        if (otyp === WAN_STRIKING
            && ltyp !== DRAWBRIDGE_UP && find_drawbridge(dbx, dby)) {
            await destroy_drawbridge(dbx, dby);
        } else if (IS_DOOR(ltyp) || ltyp === SDOOR) {
            if (otyp === WAN_OPENING || otyp === WAN_LOCKING || otyp === WAN_STRIKING) {
                if (await doorlock(obj, game.bhitpos_x, game.bhitpos_y)) {
                    if (game.zap_oseen) makeknown(otyp);
                    if ((levl(game.bhitpos_x, game.bhitpos_y)?.doormask || 0) === D_BROKEN
                        && in_rooms(game.bhitpos_x, game.bhitpos_y, SHOPBASE))
                        add_damage(game.bhitpos_x, game.bhitpos_y, 0);
                }
            }
        }
        if (!ZAP_POS(ltyp)
            || (IS_DOOR(ltyp) && ((levl(game.bhitpos_x, game.bhitpos_y)?.doormask || 0)
                                  & (D_LOCKED | D_CLOSED)))) {
            game.bhitpos_x -= ddx;
            game.bhitpos_y -= ddy;
            break;
        }
    }
}
export { mbhit };
// ── buzz_force_miss (C ref: muse.c:1814) ──
// C: dobuzz(type, nd, sx, sy, dx, dy, TRUE, FALSE, TRUE)
// Since dobuzz is not exported from zap.js, we use buzz (which passes forcemiss=false).
// TODO: export dobuzz from zap.js for full parity on monster first-shot miss.
async function buzz_force_miss(type, nd, sx, sy, dx, dy) {
    await buzz(type, nd, sx, sy, dx, dy);
}
// ── use_offensive (C ref: muse.c:1823) ──
export async function use_offensive(mtmp) {
    let i;
    let otmp = game.m_offensive;
    let oseen;
    const buzzfn = mtmp.mwandexp ? buzz : buzz_force_miss;
    if (otmp.oclass !== POTION_CLASS && (i = await precheck(mtmp, otmp)) !== 0)
        return i;
    oseen = canseemon(mtmp);
    switch (game.m_has_offense) {
    case MUSE_OFF_WAN_DEATH:
    case MUSE_OFF_WAN_SLEEP:
    case MUSE_OFF_WAN_FIRE:
    case MUSE_OFF_WAN_COLD:
    case MUSE_OFF_WAN_LIGHTNING:
    case MUSE_OFF_WAN_MAGIC_MISSILE:
        await mzapwand(mtmp, otmp, false);
        if (oseen) makeknown(otmp.otyp);
        game.m_using = true;
        game.current_wand = otmp;
        game.buzzer = mtmp;
        await buzzfn(BZ_M_WAND(BZ_OFS_WAN(otmp.otyp)),
               (otmp.otyp === WAN_MAGIC_MISSILE) ? 2 : 6, mtmp.mx, mtmp.my,
               sgn(mtmp.mux - mtmp.mx), sgn(mtmp.muy - mtmp.my));
        game.buzzer = null;
        game.current_wand = null;
        game.m_using = false;
        mtmp.mwandexp = true;
        return DEADMONSTER(mtmp) ? 1 : 2;
    case MUSE_OFF_FIRE_HORN:
    case MUSE_OFF_FROST_HORN:
        await mplayhorn(mtmp, otmp, false);
        game.m_using = true;
        game.buzzer = mtmp;
        game.current_wand = otmp;
        await buzzfn(BZ_M_WAND(BZ_OFS_AD(
                         (otmp.otyp === FROST_HORN) ? AD_COLD : AD_FIRE)),
             rn1(6, 6), mtmp.mx, mtmp.my, sgn(mtmp.mux - mtmp.mx),
             sgn(mtmp.muy - mtmp.my));
        game.buzzer = null;
        game.current_wand = null;
        game.m_using = false;
        mtmp.mwandexp = true;
        return DEADMONSTER(mtmp) ? 1 : 2;
    case MUSE_OFF_WAN_TELEPORTATION:
    case MUSE_OFF_WAN_UNDEAD_TURNING:
    case MUSE_OFF_WAN_STRIKING:
        game.zap_oseen = oseen;
        await mzapwand(mtmp, otmp, false);
        game.m_using = true;
        game.buzzer = mtmp;
        await mbhit(mtmp, rn1(8, 6), mbhitm, bhito, otmp);
        game.buzzer = null;
        game.m_using = false;
        if (game.m_has_offense === MUSE_OFF_WAN_STRIKING)
            mtmp.mwandexp = true;
        return 2;
    case MUSE_OFF_SCR_EARTH: {
        const confused = mtmp.mconf ? true : false;
        const mmx = mtmp.mx, mmy = mtmp.my;
        const is_cursed = otmp.cursed, is_blessed = otmp.blessed;
        await mreadmsg(mtmp, otmp);
        if (canspotmon(mtmp)) {
            await pline_The(`${ceiling(mtmp.mx, mtmp.my)} rumbles ${otmp.blessed ? 'around' : 'above'} ${mon_nam(mtmp)}!`);
            if (oseen) makeknown(otmp.otyp);
        } else if (cansee(mtmp.mx, mtmp.my)) {
            await pline_The(`${ceiling(mtmp.mx, mtmp.my)} rumbles in the middle of nowhere!`);
            if (mtmp.minvis) map_invisible(mtmp.mx, mtmp.my);
            if (oseen) makeknown(otmp.otyp);
        }
        await m_useup(mtmp, otmp);
        for (let bx = mmx - 1; bx <= mmx + 1; bx++) {
            for (let by = mmy - 1; by <= mmy + 1; by++) {
                if (isok(bx, by) && !closed_door(bx, by)
                    && !IS_OBSTRUCTED(levl(bx, by)?.typ) && !IS_AIR(levl(bx, by)?.typ)
                    && (((bx === mmx) && (by === mmy)) ? !is_blessed : !is_cursed)
                    && (bx !== game.u?.ux || by !== game.u?.uy)) {
                    await drop_boulder_on_monster(bx, by, confused, false);
                }
            }
        }
        if (distmin(mmx, mmy, game.u?.ux, game.u?.uy) === 1 && !is_cursed) {
            await drop_boulder_on_player(confused, !is_cursed, false, true);
        }
        return DEADMONSTER(mtmp) ? 1 : 2;
    }
    case MUSE_OFF_CAMERA: {
        if (Hallucination()) {
            SetVoice(mtmp, 0, 80, 0);
            await verbalize("Say cheese!");
        } else if (!Blind()) {
            await pline(`${Monnam(mtmp)} takes a picture of you with ${an(xname(otmp))}!`);
        }
        game.m_using = true;
        if (!Blind() && !resists_blnd(game.youmonst || {})) {
            await You("are blinded by the flash of light!");
            // make_blinded(BlindedTimeout() + rnd(1 + 50), false); // TODO
        }
        await lightdamage(otmp, true, 5);
        game.m_using = false;
        otmp.spe--;
        return 1;
    }
    case MUSE_OFF_POT_PARALYSIS:
    case MUSE_OFF_POT_BLINDNESS:
    case MUSE_OFF_POT_CONFUSION:
    case MUSE_OFF_POT_SLEEPING:
    case MUSE_OFF_POT_ACID:
        if (cansee(mtmp.mx, mtmp.my)) {
            observe_object(otmp);
            await pline(`${Monnam(mtmp)} hurls ${singular(otmp, doname)}!`);
        }
        await m_throw(mtmp, mtmp.mx, mtmp.my, sgn(mtmp.mux - mtmp.mx),
                sgn(mtmp.muy - mtmp.my),
                distmin(mtmp.mx, mtmp.my, mtmp.mux, mtmp.muy), otmp);
        return 2;
    case 0:
        return 0;
    default:
        break;
    }
    return 0;
}
// ── rnd_offensive_item (C ref: muse.c:2034) ──
export function rnd_offensive_item(mtmp) {
    const pm = mtmp.data;
    const difficulty = mons[monsndx(pm)]?.difficulty || 0;
    if (is_animal(pm) || attacktype(pm, AT_EXPL) || is_mindless(pm)
        || pm?.mlet === S_GHOST || pm?.mlet === S_KOP)
        return 0;
    if (difficulty > 7 && !rn2(35))
        return WAN_DEATH;
    switch (rn2(9 - (difficulty < 4 ? 1 : 0) + 4 * (difficulty > 6 ? 1 : 0))) {
    case 0: {
        const mtmp_helmet = which_armor(mtmp, W_ARMH);
        if (hard_helmet(mtmp_helmet) || amorphous(pm)
            || passes_walls(pm) || noncorporeal(pm) || unsolid(pm))
            return SCR_EARTH;
    }
    // FALLTHROUGH
    case 1:
        return WAN_STRIKING;
    case 2:
        return POT_ACID;
    case 3:
        return POT_CONFUSION;
    case 4:
        return POT_BLINDNESS;
    case 5:
        return POT_SLEEPING;
    case 6:
        return POT_PARALYSIS;
    case 7:
    case 8:
        return WAN_MAGIC_MISSILE;
    case 9:
        return WAN_SLEEP;
    case 10:
        return WAN_FIRE;
    case 11:
        return WAN_COLD;
    case 12:
        return WAN_LIGHTNING;
    }
    return 0;
}
// ── find_misc (C ref: muse.c:2094) ──
export async function find_misc(mtmp) {
    let obj;
    const mdat = mtmp.data;
    const x = mtmp.mx, y = mtmp.my;
    let pmidx = NON_PM;
    const immobile = (mdat?.mmove === 0);
    const stuck = (mtmp === game.u?.ustuck);
    game.m_misc = null;
    game.m_has_misc = 0;
    if (is_animal(mdat) || is_mindless(mdat))
        return false;
    if (game.u?.uswallow && stuck)
        return false;
    if (dist2(x, y, mtmp.mux, mtmp.muy) > 36)
        return false;
    if (!stuck && !immobile && !mtmp.mtrapped && (mtmp.cham === NON_PM)
        && mons[(pmidx = monsndx(mdat))]?.difficulty < 6) {
        const ignore_boulders = (verysmall(mdat) || throws_rocks(mdat) || passes_walls(mdat));
        const diag_ok = !NODIAG(pmidx);
        for (let xx = x - 1; xx <= x + 1; xx++)
            for (let yy = y - 1; yy <= y + 1; yy++)
                if (isok(xx, yy) && !u_at(xx, yy)
                    && (diag_ok || xx === x || yy === y)
                    && ((xx === x && yy === y) || !m_at(xx, yy))) {
                    const t = t_at(xx, yy);
                    if (t && (ignore_boulders || !sobj_at(BOULDER, xx, yy))
                        && !onscary(xx, yy, mtmp)) {
                        if (t.ttyp === POLY_TRAP) {
                            game.trapx = xx;
                            game.trapy = yy;
                            game.m_has_misc = MUSE_MISC_POLY_TRAP;
                            return true;
                        }
                    }
                }
    }
    if (nohands(mdat))
        return false;
    for (obj = mtmp.minvent; obj; obj = obj.nobj) {
        if (obj.otyp === POT_GAIN_LEVEL
            && (!obj.cursed
                || (!mtmp.isgd && !mtmp.isshk && !mtmp.ispriest))) {
            game.m_misc = obj;
            game.m_has_misc = MUSE_MISC_POT_GAIN_LEVEL;
        }
        if (game.m_has_misc === MUSE_MISC_BULLWHIP) continue;
        if (obj.otyp === BULLWHIP && !mtmp.mpeaceful
            && game.u.uwep && !rn2(5) && obj === MON_WEP(mtmp)
            && u_at(mtmp.mux, mtmp.muy)
            && m_next2u(mtmp)
            && !game.u?.uswallow
            && (await canletgo(game.u.uwep, '')
                || (game.u?.twoweap && await canletgo(game.u.uswapwep, '')))) {
            game.m_misc = obj;
            game.m_has_misc = MUSE_MISC_BULLWHIP;
        }
        if (game.m_has_misc === MUSE_MISC_WAN_MAKE_INVISIBLE) continue;
        if (obj.otyp === WAN_MAKE_INVISIBLE && obj.spe > 0 && !mtmp.minvis
            && !mtmp.invis_blkd && (!mtmp.mpeaceful || See_invisible())
            && (!attacktype(mtmp.data, AT_GAZE) || mtmp.mcan)) {
            game.m_misc = obj;
            game.m_has_misc = MUSE_MISC_WAN_MAKE_INVISIBLE;
        }
        if (game.m_has_misc === MUSE_MISC_POT_INVISIBILITY) continue;
        if (obj.otyp === POT_INVISIBILITY && !mtmp.minvis
            && !mtmp.invis_blkd && (!mtmp.mpeaceful || See_invisible())
            && (!attacktype(mtmp.data, AT_GAZE) || mtmp.mcan)) {
            game.m_misc = obj;
            game.m_has_misc = MUSE_MISC_POT_INVISIBILITY;
        }
        if (game.m_has_misc === MUSE_MISC_WAN_SPEED_MONSTER) continue;
        if (obj.otyp === WAN_SPEED_MONSTER && obj.spe > 0
            && mtmp.mspeed !== MFAST && !mtmp.isgd) {
            game.m_misc = obj;
            game.m_has_misc = MUSE_MISC_WAN_SPEED_MONSTER;
        }
        if (game.m_has_misc === MUSE_MISC_POT_SPEED) continue;
        if (obj.otyp === POT_SPEED && mtmp.mspeed !== MFAST && !mtmp.isgd) {
            game.m_misc = obj;
            game.m_has_misc = MUSE_MISC_POT_SPEED;
        }
        if (game.m_has_misc === MUSE_MISC_WAN_POLYMORPH) continue;
        if (obj.otyp === WAN_POLYMORPH && obj.spe > 0
            && (mtmp.cham === NON_PM) && mons[monsndx(mdat)]?.difficulty < 6) {
            game.m_misc = obj;
            game.m_has_misc = MUSE_MISC_WAN_POLYMORPH;
        }
        if (game.m_has_misc === MUSE_MISC_POT_POLYMORPH) continue;
        if (obj.otyp === POT_POLYMORPH && (mtmp.cham === NON_PM)
            && mons[monsndx(mdat)]?.difficulty < 6) {
            game.m_misc = obj;
            game.m_has_misc = MUSE_MISC_POT_POLYMORPH;
        }
        if (game.m_has_misc === MUSE_MISC_BAG) continue;
        if (Is_container(obj) && obj.otyp !== BAG_OF_TRICKS && !rn2(5)
            && !SchroedingersBox(obj)
            && !game.m_has_misc && Has_contents(obj)
            && !obj.olocked && !obj.otrapped) {
            game.m_misc = obj;
            game.m_has_misc = MUSE_MISC_BAG;
        }
    }
    return !!game.m_has_misc;
}
// ── muse_newcham_mon (C ref: muse.c:2247) ──
function muse_newcham_mon(mon) {
    const m_armr = which_armor(mon, W_ARM);
    if (m_armr) {
        if (Is_dragon_scales(m_armr))
            return Dragon_scales_to_pm(m_armr);
        else if (Is_dragon_mail(m_armr))
            return Dragon_mail_to_pm(m_armr);
    }
    return rndmonst();
}
// ── mloot_container (C ref: muse.c:2261) ──
export async function mloot_container(mon, container, vismon) {
    let res = 0;
    if (!container || !Has_contents(container) || container.olocked)
        return res;
    if (Is_mbag(container) && container.cursed)
        return res;
    if (SchroedingersBox(container))
        return res;
    let takeout_count;
    const rval = rn2(10);
    if (rval <= 3) takeout_count = 1;
    else if (rval <= 6) takeout_count = 2;
    else if (rval <= 8) takeout_count = 3;
    else takeout_count = 4;
    const howfar = mdistu(mon);
    const nearby = (howfar <= 7 * 7);
    let contnr_nam = '';
    let mpronounbuf = '';
    if (vismon) {
        mpronounbuf = mhe(mon);
    }
    for (let takeout_indx = 0; takeout_indx < takeout_count; ++takeout_indx) {
        if (!Has_contents(container))
            break;
        let nitems = 0;
        for (let xobj = container.cobj; xobj; xobj = xobj.nobj)
            ++nitems;
        if (!rn2(nitems + 1))
            break;
        let target_idx = rn2(nitems);
        let xobj = container.cobj;
        for (; xobj; xobj = xobj.nobj)
            if (--target_idx < 0)
                break;
        if (!xobj) break;
        container.cknown = 0;
        if (!contnr_nam) {
            contnr_nam = an(nearby ? xname(container) : distant_name(container, xname));
        }
        obj_extract_self(xobj);
        if (can_carry(mon, xobj)) {
            if (vismon) {
                if (howfar > 2)
                    await pline(`${Monnam(mon)} rummages through ${contnr_nam}.`);
                else if (takeout_indx === 0)
                    await pline(`${Monnam(mon)} removes ${doname(xobj)} from ${contnr_nam}.`);
                else
                    await pline(`${upstart(mpronounbuf)} removes ${doname(xobj)}.`);
            }
            if (container.otyp === ICE_BOX)
                removed_from_icebox(xobj);
            await mpickobj(mon, xobj);
            res = 2;
        } else {
            const already_nomerge = !!xobj.nomerge;
            const just_xobj = !Has_contents(container);
            xobj.nomerge = 1;
            xobj = add_to_container(container, xobj);
            if (!already_nomerge)
                xobj.nomerge = 0;
            container.owt = weight(container);
            if (just_xobj)
                break;
        }
    }
    return res;
}
// ── use_misc (C ref: muse.c:2380) ──
export async function use_misc(mtmp) {
    let vis, vismon, oseen, vistrapspot;
    let i;
    let t;
    let otmp = game.m_misc;
    if ((i = await precheck(mtmp, otmp)) !== 0)
        return i;
    vis = cansee(mtmp.mx, mtmp.my);
    vismon = canseemon(mtmp);
    oseen = otmp && vismon;
    switch (game.m_has_misc) {
    case MUSE_MISC_POT_GAIN_LEVEL:
        await mquaffmsg(mtmp, otmp);
        if (otmp.cursed) {
            if (Can_rise_up(mtmp.mx, mtmp.my, game.u?.uz)) {
                const tolev = depth(game.u?.uz) - 1;
                const tolevel = {};
                get_level(tolevel, tolev);
                if (on_level(tolevel, game.u?.uz)) {
                    // skipmsg
                    if (vismon) {
                        await pline(`${Monnam(mtmp)} looks uneasy.`);
                        await trycall(otmp);
                    }
                    await m_useup(mtmp, otmp);
                    return 2;
                }
                if (vismon) {
                    await pline(`${Monnam(mtmp)} rises up, through the ${ceiling(mtmp.mx, mtmp.my)}!`);
                    await trycall(otmp);
                }
                await m_useup(mtmp, otmp);
                await migrate_to_level(mtmp, ledger_no(tolevel), MIGR_RANDOM, null);
                return 2;
            } else {
                if (vismon) {
                    await pline(`${Monnam(mtmp)} looks uneasy.`);
                    await trycall(otmp);
                }
                await m_useup(mtmp, otmp);
                return 2;
            }
        }
        if (vismon)
            await pline(`${Monnam(mtmp)} seems more experienced.`);
        if (oseen)
            makeknown(POT_GAIN_LEVEL);
        await m_useup(mtmp, otmp);
        if (!grow_up(mtmp, null))
            return 1;
        return 2;
    case MUSE_MISC_WAN_MAKE_INVISIBLE:
    case MUSE_MISC_POT_INVISIBILITY: {
        if (otmp.otyp === WAN_MAKE_INVISIBLE) {
            await mzapwand(mtmp, otmp, true);
        } else
            await mquaffmsg(mtmp, otmp);
        const nambuf = mon_nam(mtmp);
        mon_set_minvis(mtmp, otmp.cursed ? true : false);
        if (vismon && mtmp.minvis) {
            if (canspotmon(mtmp)) {
                await pline(`${upstart(s_suffix(nambuf))} body takes on a ${Hallucination() ? 'normal' : 'strange'} transparency.`);
            } else {
                await pline(`Suddenly you cannot see ${nambuf}.`);
                if (vis) map_invisible(mtmp.mx, mtmp.my);
            }
            if (oseen) makeknown(otmp.otyp);
        } else if (vismon && !mtmp.minvis) {
            await pline(`${Monnam(mtmp)} briefly seems to be transparent.`);
        } else if (!vismon && canseemon(mtmp)) {
            await pline(`${Monnam(mtmp)} suddenly appears!`);
        }
        if (otmp.otyp === POT_INVISIBILITY) {
            if (otmp.cursed)
                await you_aggravate(mtmp);
            await m_useup(mtmp, otmp);
        }
        return 2;
    }
    case MUSE_MISC_WAN_SPEED_MONSTER:
        await mzapwand(mtmp, otmp, true);
        await mon_adjust_speed(mtmp, 1, otmp);
        return 2;
    case MUSE_MISC_POT_SPEED:
        await mquaffmsg(mtmp, otmp);
        await mon_adjust_speed(mtmp, 1, otmp);
        await m_useup(mtmp, otmp);
        return 2;
    case MUSE_MISC_WAN_POLYMORPH:
        await mzapwand(mtmp, otmp, true);
        await newcham(mtmp, muse_newcham_mon(mtmp), NC_VIA_WAND_OR_SPELL | NC_SHOW_MSG);
        if (oseen)
            makeknown(WAN_POLYMORPH);
        return 2;
    case MUSE_MISC_POT_POLYMORPH:
        await mquaffmsg(mtmp, otmp);
        await m_useup(mtmp, otmp);
        if (vismon)
            await pline(`${Monnam(mtmp)} suddenly mutates!`);
        await newcham(mtmp, muse_newcham_mon(mtmp), NC_SHOW_MSG);
        if (oseen)
            makeknown(POT_POLYMORPH);
        return 2;
    case MUSE_MISC_POLY_TRAP:
        t = t_at(game.trapx, game.trapy);
        vistrapspot = cansee(t.tx, t.ty);
        if (vis || vistrapspot)
            seetrap(t);
        if (vismon || vistrapspot) {
            await pline(`${Some_Monnam(mtmp)} deliberately ${vtense(fakename[0], locomotion(mtmp.data, 'jump'))} onto a ${t.tseen ? trapname(t.ttyp, false) : 'hidden trap'}!`);
        }
        remove_monster(mtmp.mx, mtmp.my);
        newsym(mtmp.mx, mtmp.my);
        place_monster(mtmp, game.trapx, game.trapy);
        maybe_unhide_at(game.trapx, game.trapy);
        if (mtmp.wormno)
            worm_move(mtmp);
        newsym(game.trapx, game.trapy);
        await newcham(mtmp, null, NC_SHOW_MSG);
        return 2;
    case MUSE_MISC_BAG:
        return await mloot_container(mtmp, otmp, vismon);
    case MUSE_MISC_BULLWHIP: {
        const The_whip = vismon ? "The bullwhip" : "A whip";
        let where_to = rn2(4);
        let obj = game.u.uwep;
        let hand;
        if (!obj || !await canletgo(obj, '')
            || (game.u?.twoweap && await canletgo(game.u.uswapwep, '') && rn2(2)))
            obj = game.u.uswapwep;
        if (!obj) break;
        const the_weapon = `the ${xname(obj)}`;
        hand = body_part(HAND);
        if (obj.bimanual) // simplified check
            hand = makeplural(hand);
        const hand_buf = hand;
        if (vismon)
            await pline(`${Monnam(mtmp)} flicks a bullwhip towards your ${hand_buf}!`);
        if (obj.otyp === HEAVY_IRON_BALL) {
            await pline(`${The_whip} fails to wrap around ${the_weapon}.`);
            return 1;
        }
        await pline(`${The_whip} wraps around ${the_weapon} you're wielding!`);
        if (welded(obj)) {
            await pline(`${!is_plural(obj) ? 'It is' : 'They are'} welded to your ${hand_buf}${!obj.bknown ? '!' : '.'}`);
            where_to = 0;
        }
        if (!where_to) {
            await pline_The("whip slips free.");
            return 1;
        } else if (where_to === 3 && mon_hates_silver(mtmp)
                   && game.objects[obj.otyp]?.oc_material === 14 /* SILVER */) {
            where_to = 2;
        }
        await remove_worn_item(obj, false);
        freeinv(obj);
        switch (where_to) {
        case 1:
            await pline(`${Monnam(mtmp)} yanks ${the_weapon} from your ${hand_buf}!`);
            place_object(obj, mtmp.mx, mtmp.my);
            break;
        case 2:
            await pline(`${Monnam(mtmp)} yanks ${the_weapon} to the ${surface(game.u?.ux, game.u?.uy)}!`);
            await dropy(obj);
            break;
        case 3:
            await pline(`${Monnam(mtmp)} snatches ${the_weapon}!`);
            await mpickobj(mtmp, obj);
            break;
        }
        return 1;
    }
    case 0:
        return 0;
    default:
        break;
    }
    return 0;
}
// ── you_aggravate (C ref: muse.c:2628) ──
export async function you_aggravate(mtmp) {
    await pline(`For some reason, ${s_suffix(noit_mon_nam(mtmp))} presence is known to you.`);
    await cls();
    show_glyph(mtmp.mx, mtmp.my, mon_to_glyph(mtmp, rn2_on_display_rng));
    display_self();
    await You_feel(`aggravated at ${noit_mon_nam(mtmp)}.`);
    await display_nhwindow(2 /* WIN_MAP */, true);
    await docrt();
    if (unconscious()) {
        game.multi = -1;
        game.nomovemsg = "Aggravated, you are jolted into full consciousness.";
    }
    newsym(mtmp.mx, mtmp.my);
    if (!canspotmon(mtmp))
        map_invisible(mtmp.mx, mtmp.my);
}
// C ref: muse.c:1597 mbhitm
export async function mbhitm(mtmp, otmp) {
    let tmp;
    let reveal_invis = false, learnit = false;
    const hits_you = (mtmp === (game.youmonst || {}));
    if (!hits_you && otmp.otyp !== WAN_UNDEAD_TURNING) {
        mtmp.msleeping = 0;
        if (mtmp.m_ap_type) {
            // seemimic(mtmp); // TODO
        }
    }
    switch (otmp.otyp) {
    case WAN_STRIKING:
        reveal_invis = true;
        if (hits_you) {
            // C tracks u.uac globally; ensure JS AC is current before using it.
            find_ac();
            if (Antimagic()) {
                monstseesu(M_SEEN_MAGR);
                shieldeff(game.u.ux, game.u.uy);
                Soundeffect('se_boing', 40);
                await pline("Boing!");
                learnit = true;
            } else if (rnd(20) < 10 + (game.u?.uac || 0)
                       && !(game.buzzer && !game.buzzer.mwandexp)) {
                monstunseesu(M_SEEN_MAGR);
                await pline_The("wand hits you!");
                tmp = c_d(2, 12);
                if (Half_spell_damage())
                    tmp = Math.trunc((tmp + 1) / 2);
                await losehp(tmp, "wand", KILLED_BY_AN);
                learnit = true;
            } else {
                await pline_The("wand misses you.");
            }
            if (!game.program_state?.gameover) {
                await stop_occupation();
                nomul(0);
            }
        } else if (resists_magm(mtmp)) {
            shieldeff(mtmp.mx, mtmp.my);
            Soundeffect('se_boing', 40);
            await pline("Boing!");
            learnit = true;
        } else if (rnd(20) < 10 + find_mac(mtmp)) {
            tmp = c_d(2, 12);
            await hit("wand", mtmp, exclam(tmp));
            resist(mtmp, otmp.oclass, tmp, 1 /* TELL */);
            await resist_death(mtmp);
            learnit = true;
        } else {
            await miss("wand", mtmp);
        }
        if (learnit && game.zap_oseen && (hits_you
                                      || cansee(mtmp.mx, mtmp.my)))
            makeknown(WAN_STRIKING);
        break;
    case WAN_TELEPORTATION:
        if (hits_you) {
            await tele();
            if (game.zap_oseen)
                makeknown(WAN_TELEPORTATION);
        } else {
            if (mtmp.ispriest && in_rooms(mtmp.mx, mtmp.my, TEMPLE).length > 0) {
                if (cansee(mtmp.mx, mtmp.my))
                    await pline(`${Monnam(mtmp)} resists the magic!`);
            } else if (!tele_restrict(mtmp))
                await rloc(mtmp, RLOC_MSG);
        }
        break;
    case WAN_CANCELLATION:
        cancel_monst(mtmp, otmp, false, true, false);
        break;
    case WAN_UNDEAD_TURNING:
        if (hits_you) {
            await unturn_you();
            learnit = game.zap_oseen;
        } else {
            let wake = false;
            if (unturn_dead(mtmp))
                wake = true;
            if (is_undead(mtmp.data) || is_vampshifter(mtmp)) {
                wake = reveal_invis = true;
                // resist(mtmp, WAND_CLASS, rnd(8), NOTELL); // TODO
            }
            if (wake) {
                if (!DEADMONSTER(mtmp))
                    wakeup(mtmp, false);
                learnit = game.zap_oseen;
            }
        }
        if (learnit)
            makeknown(WAN_UNDEAD_TURNING);
        break;
    default:
        break;
    }
    if (reveal_invis && !hits_you && !DEADMONSTER(mtmp)
        && isok(game.bhitpos_x, game.bhitpos_y)
        && cansee(game.bhitpos_x, game.bhitpos_y) && !canspotmon(mtmp))
        map_invisible(game.bhitpos_x, game.bhitpos_y);
    return 0;
}
 
// ── rnd_misc_item (C ref: muse.c:2652) ──
export function rnd_misc_item(mtmp) {
    const pm = mtmp.data;
    const difficulty = mons[monsndx(pm)]?.difficulty || 0;
    if (is_animal(pm) || attacktype(pm, AT_EXPL) || is_mindless(pm)
        || pm?.mlet === S_GHOST || pm?.mlet === S_KOP)
        return 0;
    if (difficulty < 6 && !rn2(30))
        return rn2(6) ? POT_POLYMORPH : WAN_POLYMORPH;
    if (!rn2(40) && !nonliving(pm) && !is_vampshifter(mtmp))
        return AMULET_OF_LIFE_SAVING;
    switch (rn2(3)) {
    case 0:
        if (mtmp.isgd) return 0;
        return rn2(6) ? POT_SPEED : WAN_SPEED_MONSTER;
    case 1:
        if (mtmp.mpeaceful && !See_invisible()) return 0;
        return rn2(6) ? POT_INVISIBILITY : WAN_MAKE_INVISIBLE;
    case 2:
        return POT_GAIN_LEVEL;
    }
    return 0;
}
// ── mon_reflects (C ref: muse.c:2795) ──
export async function mon_reflects(mon, str) {
    let orefl = which_armor(mon, W_ARMS);
    if (orefl && orefl.otyp === SHIELD_OF_REFLECTION) {
        if (str) {
            await pline(str, s_suffix(mon_nam(mon)), "shield");
            makeknown(SHIELD_OF_REFLECTION);
        }
        return true;
    } else if (arti_reflects(MON_WEP(mon))) {
        if (str) await pline(str, s_suffix(mon_nam(mon)), "weapon");
        return true;
    } else if ((orefl = which_armor(mon, W_AMUL))
               && orefl.otyp === AMULET_OF_REFLECTION) {
        if (str) {
            await pline(str, s_suffix(mon_nam(mon)), "amulet");
            makeknown(AMULET_OF_REFLECTION);
        }
        return true;
    } else if ((orefl = which_armor(mon, W_ARM))
               && (orefl.otyp === SILVER_DRAGON_SCALES
                   || orefl.otyp === SILVER_DRAGON_SCALE_MAIL)) {
        if (str) await pline(str, s_suffix(mon_nam(mon)), "armor");
        return true;
    } else if (mon.data === mons[PM_SILVER_DRAGON]
               || mon.data === mons[PM_CHROMATIC_DRAGON]) {
        if (str) await pline(str, s_suffix(mon_nam(mon)), "scales");
        return true;
    }
    return false;
}
// ── ureflects (C ref: muse.c:2834) ──
export async function ureflects(fmt, str) {
    // TODO: need EReflecting from macros; for now check armor directly
    const u = game.u;
    if (u?.uarms && u.uarms.otyp === SHIELD_OF_REFLECTION) {
        if (fmt && str) {
            await pline(fmt, str, "shield");
            makeknown(SHIELD_OF_REFLECTION);
        }
        return true;
    }
    // TODO: check wielded artifact, amulet, armor, dragon form
    return false;
}
// ── mcureblindness (C ref: muse.c:2870) ──
export async function mcureblindness(mon, verbos) {
    if (!mon.mcansee) {
        mon.mcansee = 1;
        mon.mblinded = 0;
        if (verbos && haseyes(mon.data))
            await pline(`${Monnam(mon)} can see again.`);
    }
}
// ── munstone (C ref: muse.c:2882) ──
export async function munstone(mon, by_you) {
    if (resists_ston(mon))
        return false;
    if (mon.meating || helpless(mon))
        return false;
    mon.mstrategy &= ~STRAT_WAITFORU;
    const tinok = mcould_eat_tin(mon);
    for (let obj = mon.minvent; obj; obj = obj.nobj) {
        if (cures_stoning(mon, obj, tinok)) {
            await mon_consume_unstone(mon, obj, by_you, true);
            return true;
        }
    }
    return false;
}
// ── mon_consume_unstone (C ref: muse.c:2904) ──
export async function mon_consume_unstone(mon, obj, by_you, stoning) {
    const vis = canseemon(mon);
    const tinned = obj.otyp === TIN;
    const food = obj.otyp === CORPSE || tinned;
    const acid = obj.otyp === POT_ACID || (food && acidic(mons[obj.corpsenm]));
    const lizard = food && obj.corpsenm === PM_LIZARD;
    const nutrit = food ? dog_nutrition(mon, obj) : 0;
    if (stoning)
        await mon_adjust_speed(mon, -3, null);
    if (vis) {
        const save_quan = obj.quan;
        obj.quan = 1;
        await pline(`${Monnam(mon)} ${(obj.oclass === POTION_CLASS) ? 'quaffs' : (obj.otyp === TIN) ? 'opens and eats the contents of' : 'eats'} ${distant_name(obj, doname)}.`);
        obj.quan = save_quan;
    } else if (!Deaf()) {
        await You_hear(`${(obj.oclass === POTION_CLASS) ? 'drinking' : 'chewing'}.`);
    }
    await m_useup(mon, obj);
    if (acid && !tinned && !resists_acid(mon)) {
        mon.mhp -= rnd(15);
        if (vis)
            await pline(`${Monnam(mon)} has a very bad case of stomach acid.`);
        if (DEADMONSTER(mon)) {
            await pline(`${Monnam(mon)} dies!`);
            if (by_you)
                await xkilled(mon, XKILL_NOMSG | XKILL_NOCONDUCT);
            else
                mondead(mon);
            return;
        }
    }
    if (stoning && vis) {
        if (Hallucination())
            await pline(`What a pity - ${mon_nam(mon)} just ruined a future piece of art!`);
        else
            await pline(`${Monnam(mon)} seems limber!`);
    }
    if (lizard && (mon.mconf || mon.mstun)) {
        mon.mconf = 0;
        mon.mstun = 0;
        if (vis && !is_bat(mon.data) && mon.data !== mons[PM_STALKER])
            await pline(`${Monnam(mon)} seems steadier now.`);
    }
    if (mon.mtame && !mon.isminion && nutrit > 0) {
        const edog = mon.mextra?.edog;
        if (edog) {
            if (edog.hungrytime < (game.moves || 0))
                edog.hungrytime = game.moves || 0;
            edog.hungrytime += nutrit;
            mon.mconf = 0;
        }
    }
    mon.movement -= NORMAL_SPEED;
    mon.mlstmv = game.moves || 0;
}
// ── cures_stoning (C ref: muse.c:2982) ──
export function cures_stoning(mon, obj, tin_ok) {
    if (obj.otyp === POT_ACID)
        return true;
    if (obj.otyp === GLOB_OF_GREEN_SLIME)
        return slimeproof(mon.data);
    if (obj.otyp !== CORPSE && (obj.otyp !== TIN || !tin_ok))
        return false;
    if (obj.corpsenm === NON_PM)
        return false;
    return (obj.corpsenm === PM_LIZARD || acidic(mons[obj.corpsenm]));
}
// ── mcould_eat_tin (C ref: muse.c:2999) ──
function mcould_eat_tin(mon) {
    if (is_animal(mon.data))
        return false;
    const mwep = MON_WEP(mon);
    const welded_wep = mwep && mwelded(mwep);
    for (let obj = mon.minvent; obj; obj = obj.nobj) {
        if (welded_wep && obj !== mwep)
            continue;
        if (obj.otyp === TIN_OPENER
            || (obj.oclass === WEAPON_CLASS
                && (game.objects[obj.otyp]?.oc_skill === 1 /* P_DAGGER */
                    || game.objects[obj.otyp]?.oc_skill === 2 /* P_KNIFE */)))
            return true;
    }
    return false;
}
// ── munslime (C ref: muse.c:3029) ──
export async function munslime(mon, by_you) {
    const mptr = mon.data;
    if (slimeproof(mptr))
        return false;
    if (mon.meating || helpless(mon))
        return false;
    mon.mstrategy &= ~STRAT_WAITFORU;
    // fire breath on self
    if (!mon.mcan && !mon.mspec_used
        && attacktype_fordmg(mptr, AT_BREA, AD_FIRE)) {
        const odummy = { otyp: STRANGE_OBJECT };
        return await muse_unslime(mon, odummy, null, by_you);
    }
    if (!is_animal(mptr) && !is_mindless(mptr)) {
        let t;
        for (let obj = mon.minvent; obj; obj = obj.nobj)
            if (cures_sliming(mon, obj))
                return await muse_unslime(mon, obj, null, by_you);
        t = t_at(mon.mx, mon.my);
        if ((!t || t.ttyp !== FIRE_TRAP) && mptr?.mmove && !mon.mtrapped) {
            const xy = [[], []];
            let nxy = 0;
            for (let x = mon.mx - 1; x <= mon.mx + 1; ++x)
                for (let y = mon.my - 1; y <= mon.my + 1; ++y)
                    if (isok(x, y) && accessible(x, y)
                        && !m_at(x, y) && (x !== game.u?.ux || y !== game.u?.uy)) {
                        xy[0][nxy] = x;
                        xy[1][nxy] = y;
                        ++nxy;
                    }
            for (let idx = 0; idx < nxy; ++idx) {
                const ridx = rn1(nxy - idx, idx);
                if (ridx !== idx) {
                    let tmp = xy[0][idx]; xy[0][idx] = xy[0][ridx]; xy[0][ridx] = tmp;
                    tmp = xy[1][idx]; xy[1][idx] = xy[1][ridx]; xy[1][ridx] = tmp;
                }
                t = t_at(xy[0][idx], xy[1][idx]);
                if (t && t.ttyp === FIRE_TRAP)
                    break;
            }
        }
        if (t && t.ttyp === FIRE_TRAP)
            return await muse_unslime(mon, { otyp: STRANGE_OBJECT }, t, by_you);
    }
    return false;
}
// ── muse_unslime (C ref: muse.c:3102) ──
export async function muse_unslime(mon, obj, trap, by_you) {
    let otyp = obj.otyp, dmg = 0;
    let vis = canseemon(mon), res = true;
    if (vis)
        await pline(`${Monnam(mon)} starts turning ${green_mon(mon) ? 'into ooze' : hcolor('green')}.`);
    await mon_adjust_speed(mon, -4, null);
    if (trap) {
        const Mnam = vis ? Monnam(mon) : null;
        if (mon.mx === trap.tx && mon.my === trap.ty) {
            if (vis)
                await pline(`${Mnam} triggers ${trap.tseen ? 'the' : 'a'} fire trap!`);
        } else {
            remove_monster(mon.mx, mon.my);
            newsym(mon.mx, mon.my);
            place_monster(mon, trap.tx, trap.ty);
            if (mon.wormno) worm_move(mon);
            newsym(mon.mx, mon.my);
            if (vis)
                await pline(`${Mnam} ${vtense(fakename[0], locomotion(mon.data, 'move'))} ${is_floater(mon.data) ? 'over' : 'onto'} ${trap.tseen ? 'the' : 'a'} fire trap!`);
        }
        await mintrap(mon, FORCETRAP);
    } else if (otyp === STRANGE_OBJECT) {
        if (vis)
            await pline(`${monverbself(mon, Monnam(mon), 'breathe', 'fire on')}.`);
        if (!rn2(3))
            mon.mspec_used = rn1(10, 5);
        dmg = await zhitm(mon, by_you ? 21 : -21, 1);
    } else if (otyp === SCR_FIRE) {
        await mreadmsg(mon, obj);
        if (mon.mconf) {
            if (cansee(mon.mx, mon.my))
                await pline("Oh, what a pretty fire!");
            if (vis) await trycall(obj);
            await m_useup(mon, obj);
            vis = false;
            res = false;
        } else {
            dmg = Math.trunc((2 * (rn1(3, 3) + 2 * bcsign(obj)) + 1) / 3);
            await m_useup(mon, obj);
            await explode(mon.mx, mon.my, -11, dmg, SCROLL_CLASS,
                    by_you ? -6 /* -EXPL_FIERY */ : 6 /* EXPL_FIERY */);
            dmg = 0;
        }
    } else if (otyp === POT_OIL) {
        const was_lit = !!obj.lamplit;
        let saw_lit = false;
        if (obj.quan > 1)
            obj = splitobj(obj, 1);
        if (vis && !was_lit) {
            await pline(`${Monnam(mon)} ignites ${ansimpleoname(obj)}.`);
            saw_lit = true;
        }
        begin_burn(obj, was_lit);
        vis |= canseemon(mon);
        if (vis) {
            observe_object(obj);
            await pline(`${saw_lit ? upstart(mhe(mon)) : Monnam(mon)} quaffs a burning ${simpleonames(obj)}`);
            makeknown(POT_OIL);
        }
        dmg = c_d(3, 4);
        await m_useup(mon, obj);
    } else {
        if (obj.otyp === FIRE_HORN)
            await mplayhorn(mon, obj, true);
        else
            await mzapwand(mon, obj, true);
        dmg = await zhitm(mon, by_you ? 1 : -1, 2);
    }
    if (dmg) {
        if (DEADMONSTER(mon)) {
            if (by_you) {
                if (vis)
                    await pline(`${Monnam(mon)} is ${nonliving(mon.data) ? 'destroyed' : 'killed'} by the fire!`);
                await xkilled(mon, XKILL_NOMSG | XKILL_NOCONDUCT);
            } else
                await monkilled(mon, "fire", AD_FIRE);
        } else {
            if (vis)
                await pline(`${Monnam(mon)} is burned${exclam(dmg)}`);
        }
    }
    if (vis) {
        if (res && !DEADMONSTER(mon))
            await pline(`${s_suffix(Monnam(mon))} slime is burned away!`);
        if (otyp !== STRANGE_OBJECT)
            makeknown(otyp);
    }
    mon.movement -= NORMAL_SPEED;
    mon.mlstmv = game.moves || 0;
    return res;
}
// ── cures_sliming (C ref: muse.c:3244) ──
export function cures_sliming(mon, obj) {
    if (obj.otyp === SCR_FIRE)
        return (haseyes(mon.data) && mon.mcansee && !nohands(mon.data));
    if (obj.otyp === POT_OIL)
        return !nohands(mon.data);
    return ((obj.otyp === WAN_FIRE
             || (obj.otyp === FIRE_HORN && can_blow(mon)))
            && obj.spe > 0);
}
// ── green_mon (C ref: muse.c:3267) ──
export function green_mon(mon) {
    const ptr = mon.data;
    if (Hallucination())
        return false;
    return (ptr?.mcolor === CLR_GREEN || ptr?.mcolor === CLR_BRIGHT_GREEN);
}
// ── necrophiliac (C ref: muse.c:2689) — #if 0 in C, stub ──
export function necrophiliac(obj, force) {
    return false;
}
// ── searches_for_item (C ref: muse.c:2704) ──
export function searches_for_item(mon, obj) {
    const typ = obj.otyp;
    if (obj.where === 1 /* OBJ_FLOOR */
        && (obj.ox === mon.mx && obj.oy === mon.my)
        && onscary(obj.ox, obj.oy, mon)) {
        return false;
    }
    if (is_animal(mon.data) || is_mindless(mon.data)
        || mon.data === mons[PM_GHOST])
        return false;
    if (typ === WAN_MAKE_INVISIBLE || typ === POT_INVISIBILITY)
        return (!mon.minvis && !mon.invis_blkd
                && !attacktype(mon.data, AT_GAZE));
    if (typ === WAN_SPEED_MONSTER || typ === POT_SPEED)
        return (mon.mspeed !== MFAST);
    switch (obj.oclass) {
    case WAND_CLASS:
        if (obj.spe <= 0) return false;
        if (typ === WAN_DIGGING)
            return !is_floater(mon.data);
        if (typ === WAN_POLYMORPH)
            return (mons[monsndx(mon.data)]?.difficulty < 6);
        if (game.objects[typ]?.oc_dir === 3 /* RAY */ || typ === WAN_STRIKING
            || typ === WAN_UNDEAD_TURNING
            || typ === WAN_TELEPORTATION || typ === WAN_CREATE_MONSTER)
            return true;
        break;
    case POTION_CLASS:
        if (typ === POT_HEALING || typ === POT_EXTRA_HEALING
            || typ === POT_FULL_HEALING || typ === POT_POLYMORPH
            || typ === POT_GAIN_LEVEL || typ === POT_PARALYSIS
            || typ === POT_SLEEPING || typ === POT_ACID || typ === POT_CONFUSION)
            return true;
        if (typ === POT_BLINDNESS && !attacktype(mon.data, AT_GAZE))
            return true;
        break;
    case SCROLL_CLASS:
        if (typ === SCR_TELEPORTATION || typ === SCR_CREATE_MONSTER
            || typ === SCR_EARTH || typ === SCR_FIRE)
            return true;
        break;
    case AMULET_CLASS:
        if (typ === AMULET_OF_LIFE_SAVING)
            return !(nonliving(mon.data) || is_vampshifter(mon));
        if (typ === AMULET_OF_REFLECTION || typ === AMULET_OF_GUARDING)
            return true;
        break;
    case TOOL_CLASS:
        if (typ === PICK_AXE)
            return needspick(mon.data);
        if (typ === UNICORN_HORN)
            return (!obj.cursed && !is_unicorn(mon.data)
                    && mon.data !== mons[PM_KI_RIN]);
        if (typ === FROST_HORN || typ === FIRE_HORN)
            return (obj.spe > 0 && can_blow(mon));
        if (Is_container(obj) && !(Is_mbag(obj) && obj.cursed)
            && !obj.olocked)
            return true;
        if (typ === EXPENSIVE_CAMERA)
            return (obj.spe > 0);
        break;
    case FOOD_CLASS:
        if (typ === CORPSE)
            return (((mon.misc_worn_check & W_ARMG) !== 0
                     && touch_petrifies(mons[obj.corpsenm]))
                    || (!resists_ston(mon)
                        && cures_stoning(mon, obj, false)));
        if (typ === TIN)
            return (mcould_eat_tin(mon)
                    && (!resists_ston(mon)
                        && cures_stoning(mon, obj, true)));
        if (typ === EGG && obj.corpsenm >= 0)
            return touch_petrifies(mons[obj.corpsenm]);
        break;
    default:
        break;
    }
    return false;
}
export function init_muse_globals() {
    game.m_defensive = null;
    game.m_has_defense = 0;
    game.m_offensive = null;
    game.m_has_offense = 0;
    game.m_misc = null;
    game.m_has_misc = 0;
    game.m_using = false;
    game.zap_oseen = false;
    game.trapx = 0;
    game.trapy = 0;
    game.buzzer = null;
    game.current_wand = null;
    game.bhitpos_x = 0;
    game.bhitpos_y = 0;
}