All files / js read.js

42.64% Statements 1064/2495
35.67% Branches 117/328
42.85% Functions 36/84
42.64% Lines 1064/2495

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 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 249673x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 1x 1x 1x 1x 1x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x               73x 73x                                                                                             73x 73x 73x 73x 73x 73x 73x 73x             1x 1x 1x 1x 2x 2x 2x 2x 2x 2x           2x 2x 2x 1x 1x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x         73x 73x 73x 73x   73x 73x 73x 73x 73x 73x 73x 1x 1x 73x 73x 73x 73x 73x 73x 73x 73x   73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                                                                                                                                                                                                                         73x 73x 73x 73x             73x 73x 73x           73x 1x 1x 73x 73x 73x 73x 73x               1x 1x 1x 1x       73x 73x 73x 73x 73x 73x 73x 73x 73x 8x 8x 8x 8x 8x 8x   8x 73x 73x 5x 5x 5x 73x 2x 2x 2x 2x 2x 2x 73x                     73x       73x       73x       73x                       73x 73x 73x                                 73x 73x 73x 1x 1x 1x 1x 1x                                                               1x 1x 1x 1x 1x 1x 1x 1x           1x 1x     1x 1x 1x 1x                                                                                                                                                                                                                                                                           1x 73x 73x                                     73x 73x                             73x 73x 73x 1x 1x 1x 1x 1x 1x 1x 1x           1x                                           1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x                       1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x                                                                                           73x                                                                                     73x                                           73x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x                           3x 3x 2x 2x         2x 1x 1x 1x 1x 1x 2x 3x 1x 1x                                 1x 2x 2x 2x 2x 73x 73x 73x                           73x 73x                           73x 1x 1x 1x 1x 1x 1x 1x 1x                                           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x                                                                 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                               1x 1x 73x                                                                   73x                                 73x                                                                                                         73x                                                                                         73x 2x 2x 2x 2x 2x 2x       2x 2x 2x 73x                     73x                 73x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 73x               73x           73x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x 73x 1x 1x 1x 1x 1x 1x 1x 1x             1x                   1x 1x 1x         1x 1x 1x               1x 1x 1x 1x                 1x 1x 73x 73x 73x 1x 1x 1x 1x       1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 26x 1x 1x 1x 1x                         1x     1x 1x 1x 1x 73x 73x 73x 73x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 14x     14x 14x     14x 14x     14x     14x 14x 2x 2x 14x 14x     14x 1x 1x 14x 14x     14x 1x 1x 14x 1x 1x 14x 1x 1x 14x     14x 14x     14x 14x 3x 3x 14x     14x 14x 1x 1x 14x     14x     14x     14x 2x 2x 14x     14x 1x 1x 14x       14x 14x 14x 14x 73x 73x 73x 902x 902x 902x 902x 477x 902x 73x 73x 73x 73x 49x 49x 49x 49x 49x 44x 44x 44x 49x               44x 49x 7x 7x 7x 49x                   37x 37x 37x 37x 49x 37x 37x 37x 44x 23x 23x 14x 14x 14x 14x 14x 14x 14x 14x     14x 14x 14x 14x           14x 22x 11x 6x 2x 6x 11x 11x 11x 14x 49x 73x 73x 73x 73x                                                                       73x 73x 73x 73x                                             73x 73x 73x 73x 73x 73x 149x 149x 149x 149x 149x 149x 149x     149x       149x 73x 73x 3x 3x 3x 3x 3x 3x 3x 3x 3x                                         3x 3x           3x                 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                     3x 73x 73x 73x 73x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 2x                 1x 1x 1x     1x 1x 1x 1x 1x 1x 2x 73x 73x           73x 73x 73x 73x                                                                                                                                                                                                                                     73x 73x 73x 73x 1x 1x 1x 1x         1x 1x 1x 1x                 1x 1x 1x 1x 1x             1x 1x               1x         1x 1x 1x       1x 1x       1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                           1x     1x 1x 1x                                           1x 73x 73x 73x 73x 73x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x 3x 3x 3x       3x 3x 3x                               3x 73x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x         3x 3x   3x         3x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 73x 73x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x               3x 3x 3x       3x 3x 73x 73x 73x 73x 3x 3x 3x 3x     3x     3x 3x       3x 3x 73x 73x 73x                                     73x 73x 73x 73x 73x 73x 73x 72x 72x  
// read.js -- Port of read.c
// Scroll reading, scroll effects, genocide, punishment, lighting.
 
import { game } from './gstate.js';
import { erosion_matters } from './mkobj.js';
import { rn2, rnd, rn1, c_d } from './rng.js';
import { pline, pline_The, urgent_pline, verbalize, You, You_cant, You_feel, You_hear, Your } from './pline.js';
import { Antimagic, Blind, Confusion, Deaf, Fire_resistance, Flying, Hallucination, has_ceiling, HConfusion, HStun, In_endgame, Invisible, Levitation, Luck, Maybe_Half_Phys, Passes_walls, Punished, Role_if, See_invisible, Stunned, Ugender, Unchanging, Underwater, Upolyd } from './macros.js';
import { levl, m_at } from './map_access.js';
import { ABASE, ACURR, AMAX, adjalign, adjattrib, exercise } from './attrib.js';
import { canseemon, canspotmon, newsym, setBotl, shieldeff, sensemon, tty_destroy_nhwindow } from './display.js';
import {
    mons, NUMMONS,
    PM_ACID_BLOB, PM_YELLOW_LIGHT, PM_BLACK_LIGHT, PM_GREMLIN,
    PM_GIANT_EEL,
    PM_HIGH_CLERIC, PM_STALKER, PM_LONG_WORM, PM_LONG_WORM_TAIL,
    PM_DOPPELGANGER, PM_HUMAN_ZOMBIE, PM_NINJA, PM_SAMURAI,
    PM_TOURIST, PM_WIZARD, PM_HEALER,
    PM_GUARD, PM_SHOPKEEPER, PM_ALIGNED_CLERIC, PM_ANGEL,
    S_HUMAN, S_invisible, S_WORM_TAIL, S_MIMIC, S_EEL,
    G_GENO, G_NOCORPSE, G_UNIQ,
} from './monsters.js';
import { A_CHA, A_CHAOTIC, A_CON, A_DEX, A_INT, A_LAWFUL, A_MAX, A_NEUTRAL, A_NONE, A_STR, A_WIS, ACCESSIBLE, ALL_SPELLS, COLNO, CONFUSION, COST_DECHNT, COST_DEGRD, COST_UNCHRG, COST_UNCURS, ECMD_CANCEL, ECMD_OK, ECMD_TIME, EYE, FACE, FOOT, FROMOUTSIDE, GENOCIDED, GETOBJ_DOWNPLAY, GETOBJ_EXCLUDE, GETOBJ_EXCLUDE_SELECTABLE, GETOBJ_PROMPT, GETOBJ_SUGGEST, HALLUC, HAND, HEAD, INTRINSIC, IS_AIR, Is_earthlevel, IS_OBSTRUCTED, Is_rogue_level, ismnum, isok, KILLED_BY, KILLED_BY_AN, LEG, LOW_PM, M_AP_MONSTER, M_AP_NOTHING, M_AP_TYPE, MM_EDOG, MM_FEMALE, MM_MALE, MM_MINVIS, MM_NOEXCLAM, MM_NOMSG, NHW_TEXT, NO_MINVENT, NO_MM_FLAGS, NON_PM, nothing_happens, OBJ_AT, ROWNO, SDOOR, SPE_LIM, STOMACH, STUNNED, TIMEOUT, u_at, W_ARM, W_ARMC, W_ARMF, W_ARMG, W_ARMH, W_ARMS, W_ART, W_ARTI, W_BALL, W_CHAIN, W_SADDLE } from './const.js';
import { SCROLL_CLASS, SPBOOK_CLASS, WEAPON_CLASS, COIN_CLASS, FOOD_CLASS, POTION_CLASS, STRANGE_OBJECT, SCR_ENCHANT_ARMOR, SCR_DESTROY_ARMOR, SCR_CONFUSE_MONSTER, SCR_SCARE_MONSTER, SCR_REMOVE_CURSE, SCR_ENCHANT_WEAPON, SCR_CREATE_MONSTER, SCR_TAMING, SCR_GENOCIDE, SCR_LIGHT, SCR_TELEPORTATION, SCR_GOLD_DETECTION, SCR_FOOD_DETECTION, SCR_IDENTIFY, SCR_MAGIC_MAPPING, SCR_AMNESIA, SCR_FIRE, SCR_EARTH, SCR_PUNISHMENT, SCR_CHARGING, SCR_STINKING_CLOUD, SCR_BLANK_PAPER, SCR_MAIL, SPE_CONFUSE_MONSTER, SPE_CAUSE_FEAR, SPE_REMOVE_CURSE, SPE_CREATE_MONSTER, SPE_CHARM_MONSTER, SPE_DETECT_FOOD, SPE_IDENTIFY, SPE_MAGIC_MAPPING, SPE_BOOK_OF_THE_DEAD, SPE_NOVEL, SPE_BLANK_PAPER, FORTUNE_COOKIE, T_SHIRT, HAWAIIAN_SHIRT, ALCHEMY_SMOCK, DUNCE_CAP, CORNUTHAUM, CREDIT_CARD, CAN_OF_GREASE, MAGIC_MARKER, CANDY_BAR, OIL_LAMP, BRASS_LANTERN, MAGIC_LAMP, BELL_OF_OPENING, TINNING_KIT, EXPENSIVE_CAMERA, CRYSTAL_BALL, HORN_OF_PLENTY, BAG_OF_TRICKS, MAGIC_FLUTE, MAGIC_HARP, FROST_HORN, FIRE_HORN, DRUM_OF_EARTHQUAKE, HEAVY_IRON_BALL, LOADSTONE, BOULDER, ROCK, SADDLE, LEASH, UNICORN_HORN, POT_WATER, WAN_WISHING, WAN_CANCELLATION, WAN_DEATH, WAN_POLYMORPH, WAN_UNDEAD_TURNING, WAN_COLD, WAN_FIRE, WAN_LIGHTNING, WAN_MAGIC_MISSILE, WAN_NOTHING, WAND_CLASS, RING_CLASS, TOOL_CLASS, ARMOR_CLASS, BALL_CLASS, CHAIN_CLASS, GEM_CLASS, BLACK_DRAGON_SCALE_MAIL, BLACK_DRAGON_SCALES, SILVER_DRAGON_SCALE_MAIL, SILVER_DRAGON_SCALES, SHIELD_OF_REFLECTION, GRAY_DRAGON_SCALE_MAIL, GRAY_DRAGON_SCALES, YELLOW_DRAGON_SCALES, ARM_SHIELD, ELVEN_LEATHER_HELM, ELVEN_MITHRIL_COAT, ELVEN_CLOAK, ELVEN_SHIELD, ELVEN_BOOTS, POT_OIL, greatest_erosion, is_shield, Is_dragon_scales, has_omonst } from './objects.js';
import { more_experienced } from './exper.js';
import { losespells, study_book } from './spell.js';
import { snuff_lit } from './apply.js';
import { delayed_killer } from './end.js';
import { list_genocided } from './end.js';
import { monster_census } from './minion.js';
import { makemon, rndmonst, mkclass } from './makemon.js';
import { bcsign, bless, blessorcurse, curse, mkobj, mksobj, place_object, unbless, uncurse, weight } from './mkobj.js';
import { Tobjnam, Yname2, Yobjnam2, an, doname, makeplural, otense, suit_simple_name, xname } from './objnam.js';
import { hcolor, type_is_pname, pmname, hliquid } from './do_name.js';
import { distu, mungspaces, plur, s_suffix, sgn, Sprintf, Strcpy, unsolid, upstart, upwords } from './hacklib.js';
import { cansee, couldsee, do_clear_area, vision_recalc } from './vision.js';
import { nomul } from './cmd.js';
import { chwepon } from './wield.js';
import { delobj, getobj, identify_pack, makeknown, stackobj, useup, useupall } from './invent.js';
import { make_confused, make_stunned, impact_arti_light } from './potion.js';
import { DEADMONSTER, mondead, mondied, monflee, Monnam, newcham, setmangry, uhis, update_inventory, wake_nearto, wakeup } from './mon.js';
import { cvt_sdoor_to_door, do_mapping, food_detect, gold_detect, trap_detect } from './detect.js';
import { alter_cost, costly_alteration, shk_your } from './shk.js';
import { create_gas_cloud, valid_cloud_pos } from './region.js';
import { artifact_light, arti_light_radius, end_burn, snuff_light_source } from './light.js';
import { is_pool, is_lava } from './dbridge.js';
import { move_bc, placebc, set_bc } from './ball.js';
import { remove_worn_item } from './steal.js';
import { trycall, flooreffects, dropy } from './do.js';
import { amorphous, can_chant, is_demon, is_female, is_hider, is_human, is_male, is_whirly, monsndx, monstseesu, monstunseesu, name_to_mon, name_to_monclass, noncorporeal, passes_walls, unique_corpstat, vampshifted } from './mondata.js';
import { initedog, set_malign } from './dog.js';
import { Ring_gone, Ring_off, Ring_on, adj_abon, destroy_arm, disintegrate_arm, some_armor, count_worn_armor, any_worn_armor_ok, hard_helmet } from './do_wear.js';
import { setworn } from './worn.js';
import { explode } from './explode.js';
import { buried_ball_to_freedom } from './dig.js';
import { livelog_printf, burn_away_slime, killed, losehp, done, check_capacity } from './hack.js';
import { resist } from './zap.js';
import { which_armor } from './worn.js';
import { hides_under, digests, is_weptool } from './mondata.js';
import { tamedog } from './dog.js';
import { getlin } from './input.js';
import { body_part, mbodypart, rehumanize, polyself, udeadinside } from './polyself.js';
import { closed_door } from './monmove.js';
import { outrumor } from './rumors.js';
import { getpos_sethilite, getpos } from './getpos.js';
import { quest_info } from './questpgr.js';
import { can_saddle, put_saddle_on_mon } from './steed.js';
import { level_tele, scrolltele } from './teleport.js';
import { Soundeffect } from './sounds.js';
import { def_monsyms } from './symbols.js';
import { wipeout_text } from './engrave.js';
import { sokoban_guilt } from './trap.js';
 
// ── Constants ──
 
const NH_AMBER = 'amber';
const NH_BLACK = 'black';
const NH_BLUE = 'blue';
const NH_GOLDEN = 'golden';
const NH_LIGHT_BLUE = 'light blue';
const NH_PURPLE = 'purple';
const NH_RED = 'red';
const NH_SILVER = 'silver';
const NH_WHITE = 'white';
 
const NODIR = 0; // wand direction
 
const G_GENOD   = 0x02;
const G_EXTINCT = 0x01;
const G_GONE    = G_GENOD | G_EXTINCT;
 
const REALLY = 1;
const PLAYER = 2;
const ONTHRONE = 4;
 
const NOTELL = 0;
 
const BUFSZ = 256;
const QBUFSZ = 128;
 
const WT_IRON_BALL_INCR = 160;
 
const EXPL_FIERY = 1;
 
const M_SEEN_FIRE = 0x04;
 
// ── Non-RNG stubs for functions not yet ported ──
 
// Punished imported from macros.js
// body_part imported from polyself.js
// mbodypart imported from polyself.js
// doname imported from objnam.js
// pmname imported from do_name.js
// upwords imported from hacklib.js
 
// useup imported from invent.js
// useupall imported from invent.js
// makeknown imported from invent.js
// trycall imported from do.js
// losehp imported from hack.js
// losehp imported from hack.js
// losehp imported from hack.js
// losehp imported from hack.js
// losehp imported from hack.js
// losehp imported from hack.js
// Maybe_Half_Phys imported from macros.js
// check_capacity imported
// getobj imported from invent.js
// outrumor imported from rumors.js
// study_book imported from spell.js (was local stub returning false)
// can_chant imported from mondata.js
// livelog_printf imported from hack.js
// Luck imported from macros.js
// is_shield: imported from objects.js
function is_elven_armor(otmp) {
    return otmp && (otmp.otyp === ELVEN_LEATHER_HELM
        || otmp.otyp === ELVEN_MITHRIL_COAT || otmp.otyp === ELVEN_CLOAK
        || otmp.otyp === ELVEN_SHIELD || otmp.otyp === ELVEN_BOOTS);
}
// Is_dragon_scales: imported from objects.js
// amorphous imported
// noncorporeal imported
// Passes_walls imported from macros.js
// is_human imported from mondata.js
// is_demon imported from mondata.js
// is_hider imported
// hides_under imported from mondata.js
// is_male imported
// is_female imported
// is_pool imported from dbridge.js
// is_lava imported from dbridge.js
// canspotmon imported from display.js
// canseemon imported from display.js
// resist imported from zap.js
// tamedog imported from dog.js
// set_malign imported
// monflee imported from mon.js
// wakeup imported from mon.js
// killed imported from hack.js
// mondied imported
// shieldeff imported from display.js
// monstseesu imported from mondata.js
// monstunseesu imported from mondata.js
// hliquid imported from do_name.js
// costly_alteration imported from shk.js
// remove_worn_item imported from steal.js
// bless imported from mkobj.js
// curse imported from mkobj.js
// destroy_arm imported
// disintegrate_arm imported
// some_armor imported
// count_worn_armor imported
// any_worn_armor_ok imported
// erosion_matters: imported from mkobj.js
// greatest_erosion: imported from objects.js
// wipeout_text imported from engrave.js
// impact_arti_light imported
// snuff_lit imported from apply.js
// snuff_light_source imported from light.js
// IS_OBSTRUCTED imported
// IS_AIR imported
// ACCESSIBLE imported
// closed_door imported from monmove.js
function avoid_ceiling(uz) {
    // C: dungeon.c avoid_ceiling
    // In_quest check simplified; quest not fully ported
    if (!has_ceiling(uz))
        return true;
    return false;
}
// sokoban_guilt imported from trap.js
export async function drop_boulder_on_monster(x, y, confused, byu) {
    // C: read.c drop_boulder_on_monster
    const otmp2 = mksobj(confused ? ROCK : BOULDER, false, false);
    if (!otmp2) return false;
    otmp2.quan = confused ? rn1(5, 2) : 1;
    otmp2.owt = weight(otmp2);

    const mtmp = m_at(x, y);
    if (mtmp && !amorphous(mtmp.data) && !passes_walls(mtmp.data)
        && !noncorporeal(mtmp.data) && !unsolid(mtmp.data)) {
        if (cansee(mtmp.mx, mtmp.my)) {
            await pline(`${Monnam(mtmp)} is hit by ${doname(otmp2)}!`);
        }
        let mdmg = dmgval(otmp2, mtmp) * otmp2.quan;
        const helmet = which_armor(mtmp, W_ARMH);
        if (helmet) {
            if (hard_helmet(helmet)) {
                if (canspotmon(mtmp))
                    await pline(`Fortunately, ${mtmp.data?.mname || 'it'} is wearing a hard helmet.`);
                else if (!Deaf())
                    await You_hear('a clanging sound.');
                if (mdmg > 2) mdmg = 2;
            } else {
                if (canspotmon(mtmp))
                    await pline(`${Monnam(mtmp)}'s ${xname(helmet)} does not protect ${mtmp.female ? 'her' : 'him'}.`);
            }
        }
        mtmp.mhp -= mdmg;
        if (DEADMONSTER(mtmp)) {
            if (byu) {
                await killed(mtmp);
            } else {
                await pline(`${Monnam(mtmp)} is killed.`);
                await mondied(mtmp);
            }
        } else {
            wakeup(mtmp, byu);
        }
        wake_nearto(x, y, 4 * 4);
    }
    if (!await flooreffects(otmp2, x, y, 'fall')) {
        place_object(otmp2, x, y);
        stackobj(otmp2);
        newsym(x, y);
    }
    return true;
}
// flooreffects imported from do.js
// stackobj imported from invent.js
// hard_helmet imported
// dropy imported
// placebc imported
// set_bc imported from ball.js
// delobj imported from invent.js
// losespells imported from spell.js
function drain_weapon_skill(n) {
    // C: weapon.c drain_weapon_skill — drain n random weapon skills
    // Skills system not fully ported; consume RNG for parity
    // C iterates skill array, picks random eligible skills to drain
    // For now just a no-op since weapon skills aren't tracked
}
async function kill_genocided_monsters() {
    // C: mon.c kill_genocided_monsters
    let mtmp = game.fmon;
    while (mtmp) {
        const mtmp2 = mtmp.nmon;
        if (!DEADMONSTER(mtmp)) {
            const mndx = monsndx(mtmp.data);
            const kill_cham = (ismnum(mtmp.cham)
                && (game.mvitals?.[mtmp.cham]?.mvflags & G_GENOD));
            if ((game.mvitals?.[mndx]?.mvflags & G_GENOD) || kill_cham) {
                if (ismnum(mtmp.cham) && !kill_cham)
                    await newcham(mtmp, null, 0);
                else
                    mondead(mtmp);
            }
        }
        mtmp = mtmp2;
    }
    // kill_eggs not yet ported
}
// rehumanize imported from polyself.js
// udeadinside imported from polyself.js
// vampshifted imported
// Unchanging imported from macros.js
// polyself imported from polyself.js
// uhis: imported from mon.js
// Ugender imported from macros.js
// rndmonst imported
// name_to_mon imported from mondata.js
// name_to_monclass imported from mondata.js
// monsndx imported from mondata.js
// type_is_pname imported
// unique_corpstat: imported from mondata.js
// has_omonst imported from objects.js
// quest_info imported from questpgr.js
// monster_census imported from minion.js
// mkclass imported
// can_saddle imported from steed.js
// put_saddle_on_mon imported from steed.js
export function flash_mon(mtmp) {
    // C: display.c flash_mon — briefly show then hide monster
    // Display-only effect, not critical for parity
    if (mtmp) newsym(mtmp.mx, mtmp.my);
}
// urgent_pline imported from hack.js
// done imported from hack.js
// delayed_killer imported from end.js
// Sprintf, Strcpy imported from hacklib.js
function Snprintf(buf, sz, fmt, ...args) { return fmt; }
// mungspaces imported from hacklib.js
// getlin imported from input.js
// getpos_sethilite imported from getpos.js
// getpos imported from getpos.js
// level_tele imported from teleport.js
// gold_detect imported from detect.js
// trap_detect imported from detect.js
function notice_mon_off() { /* display-only: suppress monster notices during map ops */ }
function notice_mon_on() { /* display-only: resume monster notices */ }
// create_gas_cloud imported from region.js
// explode imported
// burn_away_slime imported from hack.js
import { lightdamage } from './zap.js';
import { dmgval, uslinging } from './weapon.js';
import { add_menu_str, create_nhwindow_menu, destroy_nhwindow_menu, end_menu, select_menu } from './menu.js';
// list_genocided imported from end.js
// uslinging: imported from weapon.js
function wand_explode_fn(obj, chg) { /* see exported version */ }
// weight imported from mkobj.js
// is_weptool imported from mondata.js
const candy_wrappers = [
    '',              'Apollo',          'Moon Crunchy',
    'Snacky Cake',   'Chocolate Nuggie','The Small Bar',
    'Crispy Yum Yum','Nilla Crunchie',  'Berry Bar',
    'Choco Nummer',  'Om-nom',          'Fruity Oaty',
    'Wonka Bar',
];
// shk_your imported from shk.js
// suit_simple_name imported from objnam.js
function hawaiian_design(shirt, buf) {
    // C: read.c hawaiian_design
    const hawaiian_bgs = [
        'purple', 'yellow', 'red', 'blue', 'orange', 'black', 'green',
        'abstract', 'geometric', 'patterned', 'naturalistic',
    ];
    const hawaiian_motifs = [
        'flamingo', 'parrot', 'toucan', 'bird of paradise',
        'sea turtle', 'tropical fish', 'jellyfish', 'giant eel', 'water nymph',
        'plumeria', 'orchid', 'hibiscus flower', 'palm tree',
        'hula dancer', 'sailboat', 'ukulele',
    ];
    const motif = (shirt.o_id ^ (game.u?.ubirthday || 0)) >>> 0;
    const bg = (shirt.o_id ^ (~(game.u?.ubirthday || 0) >>> 0)) >>> 0;
    return `${makeplural(hawaiian_motifs[motif % hawaiian_motifs.length])} on ${an(hawaiian_bgs[bg % hawaiian_bgs.length])} background`;
}
function tshirt_text(tshirt, buf) {
    // C: read.c tshirt_text
    const shirt_msgs = [
        "I explored the Dungeons of Doom and all I got was this lousy T-shirt!",
        "Is that Mjollnir in your pocket or are you just happy to see me?",
        "It's not the size of your sword, it's how #enhance'd you are with it.",
        "Madame Elvira's House O' Succubi Lifetime Customer",
        "Madame Elvira's House O' Succubi Employee of the Month",
        "Ludios Vault Guards Do It In Small, Dark Rooms",
        "Yendor Military Soldiers Do It In Large Groups",
        "I survived Yendor Military Boot Camp",
        "Ludios Accounting School Intra-Mural Lacrosse Team",
        "Oracle(TM) Fountains 10th Annual Wet T-Shirt Contest",
        "Hey, black dragon!  Disintegrate THIS!",
        "I'm With Stupid -->",
        "Don't blame me, I voted for Izchak!",
        "Don't Panic",
        "Furinkan High School Athletic Dept.",
        "Hel-LOOO, Nurse!",
        "=^.^=",
        "100% goblin hair - do not wash",
        "Aberzombie and Fitch",
        "cK -- Cockatrice touches the Kop",
        "Don't ask me, I only adventure here",
        "Down with pants!",
        "d, your dog or a killer?",
        "FREE PUG AND NEWT!",
        "Go team ant!",
        "Got newt?",
        "Hello, my darlings!",
        "Hey!  Nymphs!  Steal This T-Shirt!",
        "I <3 Dungeon of Doom",
        "I <3 Maud",
        "I am a Valkyrie.  If you see me running, try to keep up.",
        "I am not a pack rat - I am a collector",
        "I bounced off a rubber tree",
        "Plunder Island Brimstone Beach Club",
        "If you can read this, I can hit you with my polearm",
        "I'm confused!",
        "I scored with the princess",
        "I want to live forever or die in the attempt.",
        "Lichen Park",
        "LOST IN THOUGHT - please send search party",
        "Meat is Mordor",
        "Minetown Better Business Bureau",
        "Minetown Watch",
        "Ms. Palm's House of Negotiable Affection--A Very Reputable House Of Disrepute",
        "Protection Racketeer",
        "Real men love Crom",
        "Somebody stole my Mojo!",
        "The Hellhound Gang",
        "The Werewolves",
        "They Might Be Storm Giants",
        "Weapons don't kill people, I kill people",
        "White Zombie",
        "You're killing me!",
        "Anhur State University - Home of the Fighting Fire Ants!",
        "FREE HUGS",
        "Serial Ascender",
        "Real men are valkyries",
        "Young Men's Cavedigging Association",
        "Occupy Fort Ludios",
        "I couldn't afford this T-shirt so I stole it!",
        "Mind flayers suck",
        "I'm not wearing any pants",
        "Down with the living!",
        "Pudding farmer",
        "Vegetarian",
        "Hello, I'm War!",
        "It is better to light a candle than to curse the darkness",
        "It is easier to curse the darkness than to light a candle",
        "rock--paper--scissors--lizard--Spock!",
        "/Valar morghulis/ -- /Valar dohaeris/",
    ];
    return erode_obj_text(tshirt, shirt_msgs[tshirt.o_id % shirt_msgs.length]);
}
function apron_text(apron, buf) {
    // C: read.c apron_text
    const apron_msgs = [
        "Kiss the cook",
        "I'm making SCIENCE!",
        "Don't mess with the chef",
        "Don't make me poison you",
        "Gehennom's Kitchen",
        "Rat: The other white meat",
        "If you can't stand the heat, get out of Gehennom!",
        "If we weren't meant to eat animals, why are they made out of meat?",
        "If you don't like the food, I'll stab you",
        "I am an alchemist; if you see me running, try to catch up...",
    ];
    return erode_obj_text(apron, apron_msgs[apron.o_id % apron_msgs.length]);
}
// plur imported from hacklib.js
// passes_walls imported
// digests imported from mondata.js
// unblock_point imported from display.js
function can_center_cloud(x, y) {
    // C: read.c can_center_cloud
    if (!valid_cloud_pos(x, y))
        return false;
    return cansee(x, y) && distu(x, y) < 32;
}
// NOTE: differs from canonical hacklib.js — local takes (x, y) and uses game.u directly;
// canonical takes (player, x, y). Changing signature would require updating all call sites.
// valid_cloud_pos: imported from region.js
function display_stinking_cloud_positions(on_off) {
    // C: read.c display_stinking_cloud_positions
    // Display helper for getpos: highlight valid cloud positions
    // tmp_at display not yet ported; positions still validated by can_center_cloud
}
 
function Your_Own_Role(mndx) { return mndx === game.u?.urole?.mnum; }
function Your_Own_Race(mndx) { return mndx === game.u?.urace?.mnum; }
 
// HConfusion: imported from macros.js
// HStun: imported from macros.js
 
// C accessors — dynamic getters for equipment slots
function get_uarm()  { return game.u.uarm || null; }
function get_uarmc() { return game.u.uarmc || null; }
function get_uarmh() { return game.u.uarmh || null; }
function get_uarms() { return game.u.uarms || null; }
function get_uarmg() { return game.u.uarmg || null; }
function get_uarmf() { return game.u.uarmf || null; }
function get_uarmu() { return game.u.uarmu || null; }
function get_uwep()  { return game.u.uwep || null; }
function get_uleft() { return game.u.uleft || null; }
function get_uright(){ return game.u.uright || null; }
function get_uball() { return game.u.uball || null; }
function get_uchain(){ return game.u.uchain || null; }
function get_uswapwep() { return game.u.uswapwep || null; }
function get_uquiver() { return game.u.uquiver || null; }
 
const thats_enough_tries = "That's enough tries!";
const silly_thing_to = "That is a silly thing to %s.";
const Never_mind = "Never mind.";
 
const something = 'something';
 
// ── Helper functions ──
 
function learnscrolltyp(scrolltyp) {
    if (!game.objects[scrolltyp].oc_name_known) {
        makeknown(scrolltyp);
        more_experienced(0, 10);
        return true;
    }
    return false;
}
 
export function learnscroll(sobj) {
    if (sobj.oclass !== SPBOOK_CLASS)
        learnscrolltyp(sobj.otyp);
}
 
function cap_spe(obj) {
    if (obj) {
        if (Math.abs(obj.spe) > SPE_LIM)
            obj.spe = sgn(obj.spe) * SPE_LIM;
    }
}
 
function erode_obj_text(otmp, buf) {
    // C: read.c erode_obj_text
    const erosion = greatest_erosion(otmp);
    if (erosion) {
        const MAX_ERODE = 3;
        wipeout_text(buf, Math.trunc(buf.length * erosion / (2 * MAX_ERODE)),
                     otmp.o_id ^ (game.u?.ubirthday || 0));
    }
    return buf;
}
 
async function p_glow1(otmp) {
    await pline(`${Yobjnam2(otmp, Blind() ? 'vibrate' : 'glow')} briefly.`);
}
 
async function p_glow2(otmp, color) {
    await pline(`${Yobjnam2(otmp, Blind() ? 'vibrate' : 'glow')}${Blind() ? '' : ' '}${Blind() ? '' : hcolor(color)} for a moment.`);
}
 
async function p_glow3(otmp, color) {
    await pline(`${Yobjnam2(otmp, Blind() ? 'vibrate' : 'glow')} feebly${Blind() ? '' : ' '}${Blind() ? '' : hcolor(color)} for a moment.`);
}
 
async function stripspe(obj) {
    if (obj.blessed || obj.spe <= 0) {
        await pline(nothing_happens);
    } else {
        await pline(`${Yobjnam2(obj, 'vibrate')} briefly.`);
        costly_alteration(obj, COST_UNCHRG);
        obj.spe = 0;
        if (obj.otyp === OIL_LAMP || obj.otyp === BRASS_LANTERN)
            obj.age = 0;
    }
}
 
// ── charge_ok callback ──
export function charge_ok(obj) {
    if (!obj) return GETOBJ_EXCLUDE;
    if (obj.oclass === WAND_CLASS) return GETOBJ_SUGGEST;
    if (obj.oclass === RING_CLASS && game.objects[obj.otyp].oc_charged
        && obj.dknown && game.objects[obj.otyp].oc_name_known)
        return GETOBJ_SUGGEST;
    if (is_weptool(obj)) return GETOBJ_EXCLUDE;
    if (obj.oclass === TOOL_CLASS) {
        if (obj.otyp === BRASS_LANTERN || obj.otyp === OIL_LAMP
            || (obj.otyp === MAGIC_LAMP && !game.objects[MAGIC_LAMP].oc_name_known))
            return GETOBJ_SUGGEST;
        if (game.objects[obj.otyp].oc_charged)
            return (obj.dknown && game.objects[obj.otyp].oc_name_known) ? GETOBJ_SUGGEST : GETOBJ_EXCLUDE_SELECTABLE;
        return GETOBJ_EXCLUDE;
    }
    return GETOBJ_EXCLUDE;
}
 
// ── recharge ──
export async function recharge(obj, curse_bless) {
    let n;
    const is_cursed = curse_bless < 0;
    const is_blessed = curse_bless > 0;
 
    if (obj.oclass === WAND_CLASS) {
        const lim = (obj.otyp === WAN_WISHING)
            ? 1
            : (game.objects[obj.otyp].oc_dir !== NODIR) ? 8 : 15;

        if (obj.spe === -1) obj.spe = 0;

        n = obj.recharged || 0;
        if (n > 0 && (obj.otyp === WAN_WISHING
                      || (n * n * n > rn2(7 * 7 * 7)))) {
            await wand_explode(obj, rnd(lim));
            return;
        }
        obj.recharged = (n + 1);

        if (is_cursed) {
            await stripspe(obj);
        } else {
            n = (lim === 1) ? 1 : rn1(5, lim + 1 - 5);
            if (!is_blessed) n = rnd(n);

            if (obj.spe < n) obj.spe = n;
            else obj.spe++;
            if (obj.otyp === WAN_WISHING && obj.spe > 3) {
                await wand_explode(obj, 1);
                return;
            }
            if (lim === 1) await p_glow3(obj, NH_BLUE);
            else if (obj.spe >= lim) await p_glow2(obj, NH_BLUE);
            else await p_glow1(obj);
        }

    } else if (obj.oclass === RING_CLASS && game.objects[obj.otyp].oc_charged) {
        let s;
        if (is_blessed) s = rnd(3);
        else if (is_cursed) s = -rnd(2);
        else s = 1;
        const is_on = (obj === get_uleft() || obj === get_uright());
 
        if (obj.spe > rn2(7) || obj.spe <= -5) {
            await pline(`${Yobjnam2(obj, 'pulsate')} momentarily, then ${otense(obj, 'explode')}!`);
            if (is_on) await Ring_gone(obj);
            s = rnd(3 * Math.abs(obj.spe));
            useup(obj);
            await losehp(Maybe_Half_Phys(s), 'exploding ring', KILLED_BY_AN);
        } else {
            await pline(`${Yname2(obj)} spins ${s < 0 ? 'counter' : ''}clockwise for a moment.`);
            if (s < 0) costly_alteration(obj, COST_DECHNT);
            obj.spe += s;
            if (s > 0 && obj.unpaid) alter_cost(obj, 0);
        }
 
    } else if (obj.oclass === TOOL_CLASS) {
        let rechrg = obj.recharged || 0;
        if (game.objects[obj.otyp].oc_charged) {
            if (rechrg < 7) obj.recharged = (obj.recharged || 0) + 1;
        }
        switch (obj.otyp) {
        case BELL_OF_OPENING:
            if (is_cursed) await stripspe(obj);
            else if (is_blessed) obj.spe += rnd(3);
            else obj.spe += 1;
            if (obj.spe > 5) obj.spe = 5;
            break;
        case MAGIC_MARKER:
        case TINNING_KIT:
        case EXPENSIVE_CAMERA:
            if (is_cursed) {
                await stripspe(obj);
            } else if (rechrg && obj.otyp === MAGIC_MARKER) {
                obj.recharged = 1;
                if (obj.spe < 3)
                    await Your('marker seems permanently dried out.');
                else
                    await pline(nothing_happens);
            } else if (is_blessed) {
                n = rn1(16, 15);
                if (obj.spe + n <= 50) obj.spe = 50;
                else if (obj.spe + n <= 75) obj.spe = 75;
                else {
                    if ((obj.spe + n) > 127) obj.spe = 127;
                    else obj.spe += n;
                }
                await p_glow2(obj, NH_BLUE);
            } else {
                n = rn1(11, 10);
                if (obj.spe + n <= 50) obj.spe = 50;
                else {
                    if (obj.spe + n > SPE_LIM) obj.spe = SPE_LIM;
                    else obj.spe += n;
                }
                await p_glow2(obj, NH_WHITE);
            }
            break;
        case OIL_LAMP:
        case BRASS_LANTERN:
            if (is_cursed) {
                await stripspe(obj);
                if (obj.lamplit) {
                    if (!Blind()) await pline(`${Tobjnam(obj, 'go')} out!`);
                    end_burn(obj, true);
                }
            } else if (is_blessed) {
                obj.spe = 1;
                obj.age = 1500;
                await p_glow2(obj, NH_BLUE);
            } else {
                obj.spe = 1;
                obj.age = (obj.age || 0) + 750;
                if (obj.age > 1500) obj.age = 1500;
                await p_glow1(obj);
            }
            break;
        case CRYSTAL_BALL:
            if (obj.spe === -1) obj.spe = 0;
            if (is_cursed) {
                if (!obj.cursed) {
                    await p_glow2(obj, NH_BLACK);
                    curse(obj);
                } else {
                    await pline(`${Yobjnam2(obj, 'vibrate')} briefly.`);
                }
                if (obj.spe > 0) costly_alteration(obj, COST_UNCHRG);
                obj.spe = 0;
            } else if (is_blessed) {
                obj.spe = 7;
                await p_glow2(obj, !obj.blessed ? NH_LIGHT_BLUE : NH_BLUE);
                if (!obj.blessed) bless(obj);
            } else {
                if (obj.spe < 7 || obj.cursed) {
                    n = rnd(2);
                    obj.spe = Math.min(obj.spe + n, 7);
                    if (!obj.cursed) await p_glow1(obj);
                    else {
                        await p_glow2(obj, NH_AMBER);
                        uncurse(obj);
                    }
                } else {
                    await pline(nothing_happens);
                }
            }
            break;
        case HORN_OF_PLENTY:
        case BAG_OF_TRICKS:
        case CAN_OF_GREASE:
            if (is_cursed) {
                await stripspe(obj);
            } else if (is_blessed) {
                if (obj.spe <= 10) obj.spe += rn1(10, 6);
                else obj.spe += rn1(5, 6);
                if (obj.spe > 50) obj.spe = 50;
                await p_glow2(obj, NH_BLUE);
            } else {
                obj.spe += rn1(5, 2);
                if (obj.spe > 50) obj.spe = 50;
                await p_glow1(obj);
            }
            break;
        case MAGIC_FLUTE:
        case MAGIC_HARP:
        case FROST_HORN:
        case FIRE_HORN:
        case DRUM_OF_EARTHQUAKE:
            if (is_cursed) {
                await stripspe(obj);
            } else if (is_blessed) {
                obj.spe += c_d(2, 4);
                if (obj.spe > 20) obj.spe = 20;
                await p_glow2(obj, NH_BLUE);
            } else {
                obj.spe += rnd(4);
                if (obj.spe > 20) obj.spe = 20;
                await p_glow1(obj);
            }
            break;
        default:
            // not_chargable
            await You('have a feeling of loss.');
            cap_spe(obj);
            return;
        }
    } else {
        // not_chargable
        await You('have a feeling of loss.');
    }
    cap_spe(obj);
}
 
// ── forget ──
function forget(howmuch) {
    // C: read.c forget
    if (Punished())
        game.u.bc_felt = 0;
    if (howmuch & ALL_SPELLS)
        losespells();
    drain_weapon_skill(rnd(howmuch ? 5 : 3));
    // forget having seen monsters
    for (let mtmp = game.fmon; mtmp; mtmp = mtmp.nmon) {
        if (mtmp !== game.u.usteed && mtmp !== game.u.ustuck)
            mtmp.meverseen = 0;
    }
    // also forget migrating monsters
    if (game.migrating_mons) {
        for (let mtmp = game.migrating_mons; mtmp; mtmp = mtmp.nmon)
            mtmp.meverseen = 0;
    }
}
 
// ── maybe_tame ──
async function maybe_tame(mtmp, sobj) {
    const was_tame = mtmp.mtame;
    const was_peaceful = mtmp.mpeaceful;
    if (sobj.cursed) {
        await setmangry(mtmp, false);
        if (was_peaceful && !mtmp.mpeaceful) return -1;
    } else {
        if (!resist(mtmp, sobj.oclass, 0, NOTELL) || mtmp.isshk)
            await tamedog(mtmp, sobj, false);
        if ((!was_peaceful && mtmp.mpeaceful) || was_tame !== mtmp.mtame)
            return 1;
    }
    return 0;
}
 
// ── Scroll effect helper functions (seffect_*) ──
 
async function seffect_enchant_armor(sobj) {
    let s;
    const otmp = some_armor(game.player);
    const sblessed = sobj.blessed;
    const scursed = sobj.cursed;
    const confused = (!!Confusion());
 
    if (!otmp) {
        // strange_feeling
        exercise(A_CON, !scursed);
        exercise(A_STR, !scursed);
        return null; // signal useup
    }
    if (confused) {
        const old_erodeproof = !!otmp.oerodeproof;
        const new_erodeproof = !scursed;
        otmp.oerodeproof = 0;
        if (Blind()) {
            otmp.rknown = false;
            await pline(`${Yobjnam2(otmp, 'feel')} warm for a moment.`);
        } else {
            otmp.rknown = true;
            await pline(`${Yobjnam2(otmp, 'are')} covered by a ${scursed ? 'mottled' : 'shimmering'} ${hcolor(scursed ? NH_BLACK : NH_GOLDEN)} ${scursed ? 'glow' : (is_shield(otmp) ? 'layer' : 'shield')}!`);
        }
        if (new_erodeproof && (otmp.oeroded || otmp.oeroded2)) {
            otmp.oeroded = otmp.oeroded2 = 0;
            await pline(`${Yobjnam2(otmp, Blind() ? 'feel' : 'look')} as good as new!`);
        }
        if (old_erodeproof && !new_erodeproof) {
            otmp.oerodeproof = 1;
            costly_alteration(otmp, COST_DEGRD);
        }
        otmp.oerodeproof = new_erodeproof ? 1 : 0;
        return sobj;
    }
    const special_armor = is_elven_armor(otmp)
        || (Role_if(PM_WIZARD) && otmp.otyp === CORNUTHAUM);
    let same_color;
    if (scursed)
        same_color = (otmp.otyp === BLACK_DRAGON_SCALE_MAIL
                      || otmp.otyp === BLACK_DRAGON_SCALES);
    else
        same_color = (otmp.otyp === SILVER_DRAGON_SCALE_MAIL
                      || otmp.otyp === SILVER_DRAGON_SCALES
                      || otmp.otyp === SHIELD_OF_REFLECTION);
    if (Blind()) same_color = false;
 
    s = scursed ? -otmp.spe : otmp.spe;
    if (s > (special_armor ? 5 : 3) && rn2(s)) {
        otmp.in_use = true;
        await pline(`${Yname2(otmp)} violently ${otense(otmp, Blind() ? 'vibrate' : 'glow')}${(!Blind() && !same_color) ? ' ' : ''}${(Blind() || same_color) ? '' : hcolor(scursed ? NH_BLACK : NH_SILVER)} for a while, then ${otense(otmp, 'evaporate')}.`);
        await remove_worn_item(otmp, false);
        useup(otmp);
        return sobj;
    }
    if (s < -100) s = -100;
 
    s = Math.trunc((4 - s) / 2);
    if (special_armor) ++s;
    if (!game.objects[otmp.otyp].oc_magic) ++s;
    if (sblessed) ++s;
 
    if (s <= 0) {
        s = 0;
        if (otmp.spe > 0 && !rn2(otmp.spe)) s = 1;
    } else {
        s = rnd(s);
    }
    if (s > 11) s = 11;
 
    if (scursed) s = -s;
 
    if (s >= 0 && Is_dragon_scales(otmp)) {
        // dragon scales -> scale mail
        await pline(`${Yname2(otmp)} merges and hardens!`);
        otmp.otyp += GRAY_DRAGON_SCALE_MAIL - GRAY_DRAGON_SCALES;
        if (sblessed) {
            otmp.spe++;
            cap_spe(otmp);
            if (!otmp.blessed) bless(otmp);
        } else if (otmp.cursed) uncurse(otmp);
        otmp.known = 1;
        return sobj;
    }
    await pline(`${Yname2(otmp)} ${(s === 0) ? 'violently ' : ''}${otense(otmp, Blind() ? 'vibrate' : 'glow')}${(!Blind() && !same_color) ? ' ' : ''}${(Blind() || same_color) ? '' : hcolor(scursed ? NH_BLACK : NH_SILVER)} for a ${(s * s > 1) ? 'while' : 'moment'}.`);
    if (s < 0) costly_alteration(otmp, COST_DECHNT);
    if (scursed && !otmp.cursed) curse(otmp);
    else if (sblessed && !otmp.blessed) bless(otmp);
    else if (!scursed && otmp.cursed) uncurse(otmp);
    if (s) {
        const oldspe = otmp.spe;
        otmp.spe += s;
        cap_spe(otmp);
        const actual_s = otmp.spe - oldspe;
        if (actual_s) adj_abon(otmp, actual_s);
        game.known = otmp.known;
        if (actual_s > 0 && otmp.unpaid) alter_cost(otmp, 0);
    }
    if ((otmp.spe > (special_armor ? 5 : 3))
        && (special_armor || !rn2(7)))
        await pline(`${Yobjnam2(otmp, 'suddenly vibrate')} ${Blind() ? 'again' : 'unexpectedly'}.`);
    return sobj;
}
 
async function seffect_destroy_armor(sobj) {
    const otmp = some_armor(game.player);
    const scursed = sobj.cursed;
    const confused = (!!Confusion());

    if (confused) {
        if (!otmp) {
            exercise(A_STR, false);
            exercise(A_CON, false);
            return null; // strange_feeling -> useup
        }
        const old_erodeproof = !!otmp.oerodeproof;
        const new_erodeproof = scursed;
        otmp.oerodeproof = 0;
        await p_glow2(otmp, NH_PURPLE);
        if (old_erodeproof && !new_erodeproof) {
            otmp.oerodeproof = 1;
            costly_alteration(otmp, COST_DEGRD);
        }
        otmp.oerodeproof = new_erodeproof ? 1 : 0;
        return sobj;
    }
    if (scursed) {
        if (otmp && otmp.cursed) {
            await pline(`${Yobjnam2(otmp, 'vibrate')}.`);
            if (otmp.spe >= -6) {
                otmp.spe += -1;
                adj_abon(otmp, -1);
            }
            await make_stunned((HStun() & TIMEOUT) + rn1(10, 10), true);
        } else if (await disintegrate_arm(otmp)) {
            game.known = true;
            return sobj;
        }
    } else {
        if (!await destroy_arm()) {
            exercise(A_STR, false);
            exercise(A_CON, false);
            return null; // strange_feeling -> useup
        } else {
            game.known = true;
        }
    }
    return sobj;
}
 
async function seffect_confuse_monster(sobj) {
    const sblessed = sobj.blessed;
    const scursed = sobj.cursed;
    const confused = (!!Confusion());
    const altfeedback = (Blind() || Invisible());
    const hands = makeplural(body_part(HAND));

    if ((game.player?.data?.mlet || S_HUMAN) !== S_HUMAN || scursed) {
        if (!HConfusion())
            await You_feel('confused.');
        await make_confused(HConfusion() + rnd(100), false);
    } else if (confused) {
        if (!sblessed) {
            await Your(`${hands} begin to ${altfeedback ? 'tingle' : 'glow '}${altfeedback ? '' : hcolor(NH_PURPLE)}.`);
            await make_confused(HConfusion() + rnd(100), false);
        } else {
            await pline(`A ${altfeedback ? '' : hcolor(NH_RED)}${altfeedback ? 'faint buzz' : ' glow'} surrounds your ${body_part(HEAD)}.`);
            await make_confused(0, true);
        }
    } else {
        let incr = (sobj.oclass === SCROLL_CLASS) ? 3 : 0;
        if (!sblessed) {
            if (altfeedback)
                await Your(`${hands} tingle${game.u.umconf ? ' even more' : ''}.`);
            else if (!game.u.umconf)
                await Your(`${hands} begin to glow ${hcolor(NH_RED)}.`);
            else
                await pline_The(`${hcolor(NH_RED)} glow of your ${hands} intensifies.`);
            incr += rnd(2);
        } else {
            if (altfeedback)
                await Your(`${hands} tingle ${game.u.umconf ? 'even more' : 'very'} sharply.`);
            else
                await Your(`${hands} glow ${game.u.umconf ? 'an even more' : 'a'} brilliant ${hcolor(NH_RED)}.`);
            incr += rn1(8, 2);
        }
        if ((game.u.umconf || 0) >= 40)
            incr = 1;
        game.u.umconf = (game.u.umconf || 0) + incr;
    }
    return sobj;
}
 
async function seffect_scare_monster(sobj) {
    const scursed = sobj.cursed;
    const confused = (!!Confusion());
    let ct = 0;

    for (let mtmp = game.fmon; mtmp; mtmp = mtmp.nmon) {
        if (DEADMONSTER(mtmp)) continue;
        if (cansee(mtmp.mx, mtmp.my)) {
            if (confused || scursed) {
                mtmp.mflee = mtmp.mfrozen = mtmp.msleeping = 0;
                mtmp.mcanmove = 1;
            } else if (!resist(mtmp, sobj.oclass, 0, NOTELL))
                await monflee(mtmp, 0, false, false);
            if (!mtmp.mtame) ct++;
        }
    }
    if (sobj.otyp === SCR_SCARE_MONSTER || !ct) {
        await You_hear(`${(confused || scursed) ? 'sad wailing' : 'maniacal laughter'} ${!ct ? 'in the distance' : 'close by'}.`);
    }
    return sobj;
}
 
async function seffect_remove_curse(sobj) {
    const otyp = sobj.otyp;
    const sblessed = sobj.blessed;
    const scursed = sobj.cursed;
    const confused = (!!Confusion());
 
    await You_feel(!Hallucination()
        ? (!confused ? 'like someone is helping you.'
            : 'like you need some help.')
        : (!confused ? 'in touch with the Universal Oneness.'
            : 'the power of the Force against you!'));
 
    if (scursed) {
        await pline_The('scroll disintegrates.');
    } else {
        // iterate inventory (C: uses nxto for safe iteration)
        let nxto;
        for (let obj = game.invent; obj; obj = nxto) {
            nxto = obj.nobj;
            if (obj.oclass === COIN_CLASS) continue;
            if (obj === sobj && (obj.quan || 1) === 1) continue;
            let wornmask = (obj.owornmask || 0) & ~(W_BALL | W_ART | W_ARTI);
            if (wornmask && !sblessed) {
                // C: auxiliary weapon slot checks
                if (obj === get_uswapwep()) {
                    if (!game.u.twoweap) wornmask = 0;
                } else if (obj === get_uquiver()) {
                    if (obj.oclass === WEAPON_CLASS) {
                        if (!game.objects[obj.otyp]?.oc_merge) wornmask = 0;
                    } else if (obj.oclass === GEM_CLASS) {
                        if (!uslinging()) wornmask = 0;
                    } else {
                        wornmask = 0;
                    }
                }
            }
            if (sblessed || wornmask || obj.otyp === LOADSTONE
                || (obj.otyp === LEASH && obj.leashmon)) {
                const shop_h2o = (obj.unpaid && obj.otyp === POT_WATER);
                if (confused) {
                    blessorcurse(obj, 2);
                    obj.bknown = 0;
                    if (shop_h2o && (obj.cursed || obj.blessed))
                        alter_cost(obj, 0);
                } else if (obj.cursed) {
                    if (shop_h2o) costly_alteration(obj, COST_UNCURS);
                    uncurse(obj);
                    if (obj.bknown && otyp === SCR_REMOVE_CURSE)
                        learnscrolltyp(SCR_REMOVE_CURSE);
                }
            }
        }
        // steed saddle
        if (game.u.usteed) {
            const obj = which_armor(game.u.usteed, W_SADDLE);
            if (obj) {
                if (confused) {
                    blessorcurse(obj, 2);
                    obj.bknown = 0;
                } else if (obj.cursed) {
                    uncurse(obj);
                    if (!Blind()) {
                        await pline(`${Yobjnam2(obj, 'glow')} ${hcolor('amber')}.`);
                        obj.bknown = Hallucination() ? 0 : 1;
                    } else {
                        obj.bknown = 0;
                    }
                }
            }
        }
    }
    if (Punished() && !confused) unpunish();
    update_inventory();
    return sobj;
}
 
// which_armor imported from worn.js
 
async function seffect_create_monster(sobj) {
    // C: read.c seffect_create_monster
    const sblessed = sobj.blessed;
    const scursed = sobj.cursed;
    const confused = (!!Confusion());

    if (await create_critters(1 + ((confused || scursed) ? 12 : 0)
                        + ((sblessed || rn2(73)) ? 0 : rnd(4)),
                        confused ? mons[PM_ACID_BLOB] : null,
                        false))
        game.known = true;
    return sobj;
}
 
// C: makemon.c create_critters — create monsters near hero
async function create_critters(cnt, mptr, neverask) {
    let known = false;
    while (cnt-- > 0) {
        const x = game.u.ux, y = game.u.uy;
        const mon = await makemon(mptr, x, y, NO_MM_FLAGS);
        if (!mon) continue;
        if ((canseemon(mon) && (M_AP_TYPE(mon) === M_AP_NOTHING
                                || M_AP_TYPE(mon) === M_AP_MONSTER))
            || sensemon(mon))
            known = true;
    }
    return known;
}
 
async function seffect_enchant_weapon(sobj) {
    const sblessed = sobj.blessed;
    const scursed = sobj.cursed;
    const confused = (!!Confusion());
    const uwep_local = get_uwep();
 
    if (confused && uwep_local
        && erosion_matters(uwep_local) && uwep_local.oclass !== ARMOR_CLASS) {
        const old_erodeproof = !!uwep_local.oerodeproof;
        const new_erodeproof = !scursed;
        uwep_local.oerodeproof = 0;
        if (Blind()) {
            uwep_local.rknown = false;
            await Your('weapon feels warm for a moment.');
        } else {
            uwep_local.rknown = true;
            await pline(`${Yobjnam2(uwep_local, 'are')} covered by a ${scursed ? 'mottled' : 'shimmering'} ${hcolor(scursed ? NH_PURPLE : NH_GOLDEN)} ${scursed ? 'glow' : 'shield'}!`);
        }
        if (new_erodeproof && (uwep_local.oeroded || uwep_local.oeroded2)) {
            uwep_local.oeroded = uwep_local.oeroded2 = 0;
            await pline(`${Yobjnam2(uwep_local, Blind() ? 'feel' : 'look')} as good as new!`);
        }
        if (old_erodeproof && !new_erodeproof) {
            uwep_local.oerodeproof = 1;
            costly_alteration(uwep_local, COST_DEGRD);
        }
        uwep_local.oerodeproof = new_erodeproof ? 1 : 0;
        return sobj;
    }
    let s;
    if (scursed) s = -1;
    else if (!uwep_local) s = 1;
    else if (uwep_local.spe >= 9) s = (rn2(uwep_local.spe) === 0) ? 1 : 0;
    else if (sblessed) s = rnd(3 - Math.trunc(uwep_local.spe / 3));
    else s = 1;
 
    if (!(await chwepon(sobj, s)))
        return null; // strange_feeling -> useup
    if (uwep_local) cap_spe(uwep_local);
    return sobj;
}
 
async function seffect_taming(sobj) {
    const confused = (!!Confusion());
    let candidates, results, vis_results;

    if (game.u.uswallow) {
        candidates = 1;
        results = vis_results = await maybe_tame(game.u.ustuck, sobj);
    } else {
        const bd = confused ? 5 : 1;
        candidates = results = vis_results = 0;
        for (let i = -bd; i <= bd; i++) {
            for (let j = -bd; j <= bd; j++) {
                if (!isok(game.u.ux + i, game.u.uy + j)) continue;
                let mtmp = m_at(game.u.ux + i, game.u.uy + j);
                if (!mtmp && !i && !j) mtmp = game.u.usteed;
                if (mtmp) {
                    ++candidates;
                    const res = await maybe_tame(mtmp, sobj);
                    results += res;
                    if (canspotmon(mtmp)) vis_results += res;
                }
            }
        }
    }
    if (!results) {
        await pline(`Nothing interesting ${!candidates ? 'happens' : 'seems to happen'}.`);
    } else {
        await pline_The(`neighborhood ${vis_results ? 'is' : 'seems'} ${(results < 0) ? 'un' : ''}friendlier.`);
        if (vis_results > 0) game.known = true;
    }
    return sobj;
}
 
async function seffect_genocide(sobj) {
    const otyp = sobj.otyp;
    const sblessed = sobj.blessed;
    const scursed = sobj.cursed;
    const already_known = (sobj.oclass === SPBOOK_CLASS
                           || game.objects[otyp].oc_name_known);
    if (!already_known)
        await You('have found a scroll of genocide!');
    game.known = true;
    if (sblessed)
        await do_class_genocide();
    else
        await do_genocide((!scursed ? 1 : 0) | (2 * (Confusion() ? 1 : 0)));
    return sobj;
}
 
async function seffect_light(sobj) {
    const sblessed = sobj.blessed;
    const scursed = sobj.cursed;
    const confused = (!!Confusion());
 
    if (!confused) {
        if (!Blind()) game.known = true;
        await litroom(!scursed, sobj);
        if (!scursed) {
            if (await lightdamage(sobj, true, 5))
                game.known = true;
        }
    } else {
        const pm = scursed ? PM_BLACK_LIGHT : PM_YELLOW_LIGHT;
        if (game.mvitals && game.mvitals[pm] && (game.mvitals[pm].mvflags & G_GONE)) {
            await pline('Tiny lights sparkle in the air momentarily.');
        } else {
            let sawlights = false;
            const numlights = rn1(2, 3) + (sblessed ? 2 : 0);
            for (let i = 0; i < numlights; ++i) {
                const mon = await makemon(mons[pm], game.u.ux, game.u.uy,
                    MM_EDOG | NO_MINVENT | MM_NOMSG);
                if (mon) {
                    initedog(mon, true);
                    mon.msleeping = 0;
                    mon.mcan = true;
                    if (canspotmon(mon)) sawlights = true;
                    newsym(mon.mx, mon.my);
                }
            }
            if (sawlights) {
                await pline('Lights appear all around you!');
                game.known = true;
            }
        }
    }
    return sobj;
}
 
async function seffect_charging(sobj) {
    const otyp = sobj.otyp;
    const sblessed = sobj.blessed;
    const scursed = sobj.cursed;
    const confused = (!!Confusion());
    const already_known = (sobj.oclass === SPBOOK_CLASS
                           || game.objects[otyp].oc_name_known);

    if (confused) {
        if (scursed) {
            await You_feel('discharged.');
            game.u.uen = 0;
        } else {
            await You_feel('charged up!');
            game.u.uen = (game.u.uen || 0) + c_d(sblessed ? 6 : 4, 4);
            if (game.u.uen > (game.u.uenmax || 0))
                game.u.uenmax = game.u.uen;
            else
                game.u.uen = game.u.uenmax;
        }
        setBotl('seffect_charging');
        return sobj;
    }
    if (!already_known) {
        await pline('This is a charging scroll.');
        learnscroll(sobj);
    }
    useup(sobj);
    const otmp = await getobj('charge', charge_ok, 1); // GETOBJ_PROMPT
    if (otmp)
        await recharge(otmp, scursed ? -1 : sblessed ? 1 : 0);
    return null; // sobj used up
}
 
async function seffect_amnesia(sobj) {
    const sblessed = sobj.blessed;

    game.known = true;
    forget((!sblessed ? ALL_SPELLS : 0));
    if (Hallucination())
        await Your('mind releases itself from mundane concerns.');
    else if ((game.plname || '').substring(0, 4).toLowerCase() === 'maud')
        await pline('As your mind turns inward on itself, you forget everything else.');
    else if (rn2(2))
        await pline('Who was that Maud person anyway?');
    else
        await pline('Thinking of Maud you forget everything else.');
    exercise(A_WIS, false);
    return sobj;
}
 
async function seffect_fire(sobj) {
    const otyp = sobj.otyp;
    const sblessed = sobj.blessed;
    const confused = (!!Confusion());
    const already_known = (sobj.oclass === SPBOOK_CLASS
                           || game.objects[otyp].oc_name_known);
    const cc = { x: game.u.ux, y: game.u.uy };
    const cval = bcsign(sobj);
    let dam = Math.trunc((2 * (rn1(3, 3) + 2 * cval) + 1) / 3);
    useup(sobj);
    if (!already_known) learnscrolltyp(SCR_FIRE);
    if (confused) {
        if (Underwater()) {
            await pline(`A little ${hliquid('water')} around you vaporizes.`);
        } else if (Fire_resistance()) {
            shieldeff(game.u.ux, game.u.uy);
            monstseesu(M_SEEN_FIRE);
            if (!Blind())
                await pline(`Oh, look, what a pretty fire in your ${makeplural(body_part(HAND))}.`);
            else
                await You_feel(`a pleasant warmth in your ${makeplural(body_part(HAND))}.`);
        } else {
            monstunseesu(M_SEEN_FIRE);
            await pline_The(`scroll catches fire and you burn your ${makeplural(body_part(HAND))}.`);
            await losehp(1, 'scroll of fire', KILLED_BY_AN);
        }
        return null; // used up
    }
    if (Underwater()) {
        await pline_The(`${hliquid('water')} around you vaporizes violently!`);
    } else {
        if (sblessed) {
            if (!already_known)
                await pline('This is a scroll of fire!');
            dam *= 5;
            await pline('Where do you want to center the explosion?');
            getpos_sethilite(display_stinking_cloud_positions, can_center_cloud);
            await getpos(cc, true, 'the desired position');
            if (!can_center_cloud(cc.x, cc.y)) {
                // try to reach too far, get burned
                cc.x = game.u.ux;
                cc.y = game.u.uy;
            }
        }
        if (u_at(cc.x, cc.y)) {
            await pline_The('scroll erupts in a tower of flame!');
            await burn_away_slime();
        }
    }
    await explode(cc.x, cc.y, 11, dam, SCROLL_CLASS, EXPL_FIERY);
    return null; // used up
}
 
async function seffect_earth(sobj) {
    // C: read.c seffect_earth
    const sblessed = sobj.blessed;
    const scursed = sobj.cursed;
    const confused = (!!Confusion());

    if (!Is_rogue_level(game.u.uz) && has_ceiling(game.u.uz)
        && (!In_endgame(game.u.uz) || Is_earthlevel(game.u.uz))) {
        let nboulders = 0;

        if (game.u.uswallow) {
            await You_hear('rumbling.');
        } else {
            if (!avoid_ceiling(game.u.uz)) {
                await pline_The(`ceiling rumbles ${sblessed ? 'around' : 'above'} you!`);
            } else {
                const avalanche = 'avalanche';
                const matbuf = sblessed ? makeplural(avalanche) : an(avalanche);
                await pline(`${upstart(matbuf)} of boulders ${sblessed ? 'materialize' : 'materializes'} ${sblessed ? 'around' : 'above'} you!`);
            }
        }
        game.known = 1;
        sokoban_guilt();

        if (!scursed) {
            for (let x = game.u.ux - 1; x <= game.u.ux + 1; x++) {
                for (let y = game.u.uy - 1; y <= game.u.uy + 1; y++) {
                    if (isok(x, y) && !closed_door(x, y)
                        && !IS_OBSTRUCTED(levl(x, y)?.typ)
                        && !IS_AIR(levl(x, y)?.typ)
                        && (x !== game.u.ux || y !== game.u.uy)) {
                        nboulders += await drop_boulder_on_monster(x, y, confused, true);
                    }
                }
            }
        }
        if (!sblessed) {
            await drop_boulder_on_player(confused, !scursed, true, false);
        } else if (!nboulders) {
            await pline('But nothing else happens.');
        }
    }
    return sobj;
}
 
async function seffect_punishment(sobj) {
    const sblessed = sobj.blessed;
    const confused = (!!Confusion());
 
    game.known = true;
    if (confused || sblessed) {
        await You_feel('guilty.');
        return sobj;
    }
    await punish(sobj);
    return sobj;
}
 
async function seffect_stinking_cloud(sobj) {
    const otyp = sobj.otyp;
    const already_known = (sobj.oclass === SPBOOK_CLASS
                           || game.objects[otyp].oc_name_known);
    if (!already_known)
        await You('have found a scroll of stinking cloud!');
    game.known = true;
    await do_stinking_cloud(sobj, already_known);
    return sobj;
}
 
async function seffect_blank_paper(_sobj) {
    if (Blind())
        await You("don't remember there being any magic words on this scroll.");
    else
        await pline('This scroll seems to be blank.');
    game.known = true;
    return _sobj;
}
 
async function seffect_teleportation(sobj) {
    const scursed = sobj.cursed;
    const confused = (!!Confusion());
 
    if (confused || scursed) {
        await level_tele();
        game.known = true;
    } else {
        await scrolltele(sobj);
    }
    return sobj;
}
 
async function seffect_gold_detection(sobj) {
    const scursed = sobj.cursed;
    const confused = (!!Confusion());
    if ((confused || scursed) ? await trap_detect(sobj) : await gold_detect(sobj))
        return null; // strange_feeling -> useup
    return sobj;
}
 
async function seffect_food_detection(sobj) {
    if (await food_detect(sobj))
        return null; // strange_feeling -> useup
    return sobj;
}
 
async function seffect_identify(sobj) {
    const otyp = sobj.otyp;
    const is_scroll = (sobj.oclass === SCROLL_CLASS);
    const sblessed = sobj.blessed;
    const scursed = sobj.cursed;
    const confused = (!!Confusion());
    const already_known = (sobj.oclass === SPBOOK_CLASS
                           || game.objects[otyp].oc_name_known);
 
    if (is_scroll) {
        useup(sobj);
        sobj = null;
        if (confused || (scursed && !already_known))
            await You('identify this as an identify scroll.');
        else if (!already_known)
            await pline('This is an identify scroll.');
        if (!already_known)
            learnscrolltyp(SCR_IDENTIFY);
        if (confused || (scursed && !already_known))
            return null;
    }
    if (game.invent) {
        let cval = 1;
        if (sblessed || (!scursed && !rn2(5))) {
            cval = rn2(5);
            if (cval === 1 && sblessed && Luck() > 0)
                ++cval;
        }
        await identify_pack(cval, !already_known);
    } else {
        await pline(`You're not carrying anything${is_scroll ? ' else' : ''} to be identified.`);
    }
    return sobj; // null if scroll
}
 
async function seffect_magic_mapping(sobj) {
    const is_scroll = (sobj.oclass === SCROLL_CLASS);
    const sblessed = sobj.blessed;
    const scursed = sobj.cursed;
    const confused = (!!Confusion());
 
    if (is_scroll) {
        if (game.level?.flags?.nommap) {
            await Your('mind is filled with crazy lines!');
            if (Hallucination()) await pline('Wow!  Modern art.');
            else await Your(`${body_part(HEAD)} spins in bewilderment.`);
            await make_confused(HConfusion() + rnd(30), false);
            return sobj;
        }
        if (sblessed) {
            // reveal secret doors
            for (let x = 1; x < COLNO; x++)
                for (let y = 0; y < ROWNO; y++) {
                    const loc = levl(x, y);
                    if (loc && loc.typ === SDOOR) {
                        cvt_sdoor_to_door(loc);
                    }
                }
        }
        game.known = true;
    }
    if (game.level?.flags?.nommap) {
        await Your(`${body_part(HEAD)} spins as ${something} blocks the spell!`);
        await make_confused(HConfusion() + rnd(30), false);
        return sobj;
    }
    await pline('A map coalesces in your mind!');
    const cval = (scursed && !confused);
    if (cval) {
        // set HConfusion = 1 to screw up map
        const uprops = game.u.uprops || {};
        const cprop = uprops[CONFUSION] || {};
        cprop.intrinsic = 1;
        uprops[CONFUSION] = cprop;
        game.u.uprops = uprops;
    }
    notice_mon_off();
    await do_mapping();
    notice_mon_on();
    if (cval) {
        // restore
        const uprops = game.u.uprops || {};
        const cprop = uprops[CONFUSION] || {};
        cprop.intrinsic = 0;
        uprops[CONFUSION] = cprop;
        game.u.uprops = uprops;
        await pline("Unfortunately, you can't grasp the details.");
    }
    return sobj;
}
 
// ── seffect_mail: read a scroll of mail ──
// C ref: read.c:2157 seffect_mail()
async function seffect_mail(sobj) {
    const odd = (sobj.o_id % 2) === 1;
    switch (sobj.spe) {
    case 2:
        // Stamped scroll created via magic marker
        await pline(`This scroll is marked "${odd ? 'Postage Due' : 'Return to Sender'}".`);
        break;
    case 1:
        // Scroll from bones or wishing
        await pline(`This seems to be ${odd ? 'a chain letter threatening your luck' : 'junk mail addressed to the finder of the Eye of Larn'}.`);
        break;
    default:
        // Mail daemon delivery — display the full email in a text window,
        // or fall back to C's junk mail one-liners.
        try {
            const { readMail } = await import('./missives.js'); // lazy // lazy
            const mail = readMail();
            if (mail) {
                // Display in a paged text window (like #overview / help)
                const cachedPickinv = game.cached_pickinv_win;
                if (Number.isInteger(cachedPickinv) && cachedPickinv >= 0) {
                    const cachedWin = game.wins?.[cachedPickinv];
                    if (cachedWin && !cachedWin.active) {
                        tty_destroy_nhwindow(cachedPickinv);
                        game.cached_pickinv_win = -1;
                    }
                }
                const win = create_nhwindow_menu(NHW_TEXT);
                for (const line of mail.fullText.split('\n')) {
                    add_menu_str(win, line);
                }
                end_menu(win, 'On the scroll you read:');
                await select_menu(win, 0); // PICK_NONE — just display
                destroy_nhwindow_menu(win);
            } else {
                // No pending mail — C's junk mail one-liners
                const junkTemplates = [
                    'Welcome to NetHack.',
                    'Please disregard previous letter.',
                    'This mail complies with the Yendorian Anti-Spam Act (YASA)',
                    'Please find enclosed a small token to represent your Owlbear',
                    '**FR33 P0T10N 0F FULL H34L1NG**',
                    'Please return to sender (Asmodeus)',
                    'Buy a potion of gain level for only $19.99!  Guaranteed to be blessed!',
                ];
                await pline(`It reads:  "${junkTemplates[rn2(junkTemplates.length)]}"`);
            }
        } catch {
            await pline('It reads:  "Welcome to NetHack."');
        }
        break;
    }
    return sobj; // consumed
}
 
// ── seffects: main scroll effect dispatch ──
 
export async function seffects(sobj) {
    const otyp = sobj.otyp;
 
    if (game.objects[otyp].oc_magic)
        exercise(A_WIS, true);
 
    let result;
    switch (otyp) {
    case SCR_ENCHANT_ARMOR:
        result = await seffect_enchant_armor(sobj);
        break;
    case SCR_DESTROY_ARMOR:
        result = await seffect_destroy_armor(sobj);
        break;
    case SCR_CONFUSE_MONSTER:
    case SPE_CONFUSE_MONSTER:
        result = await seffect_confuse_monster(sobj);
        break;
    case SCR_SCARE_MONSTER:
    case SPE_CAUSE_FEAR:
        result = await seffect_scare_monster(sobj);
        break;
    case SCR_BLANK_PAPER:
        result = await seffect_blank_paper(sobj);
        break;
    case SCR_REMOVE_CURSE:
    case SPE_REMOVE_CURSE:
        result = await seffect_remove_curse(sobj);
        break;
    case SCR_CREATE_MONSTER:
    case SPE_CREATE_MONSTER:
        result = await seffect_create_monster(sobj);
        break;
    case SCR_ENCHANT_WEAPON:
        result = await seffect_enchant_weapon(sobj);
        break;
    case SCR_TAMING:
    case SPE_CHARM_MONSTER:
        result = await seffect_taming(sobj);
        break;
    case SCR_GENOCIDE:
        result = await seffect_genocide(sobj);
        break;
    case SCR_LIGHT:
        result = await seffect_light(sobj);
        break;
    case SCR_TELEPORTATION:
        result = await seffect_teleportation(sobj);
        break;
    case SCR_GOLD_DETECTION:
        result = await seffect_gold_detection(sobj);
        break;
    case SCR_FOOD_DETECTION:
    case SPE_DETECT_FOOD:
        result = await seffect_food_detection(sobj);
        break;
    case SCR_IDENTIFY:
    case SPE_IDENTIFY:
        result = await seffect_identify(sobj);
        break;
    case SCR_CHARGING:
        result = await seffect_charging(sobj);
        break;
    case SCR_MAGIC_MAPPING:
    case SPE_MAGIC_MAPPING:
        result = await seffect_magic_mapping(sobj);
        break;
    case SCR_AMNESIA:
        result = await seffect_amnesia(sobj);
        break;
    case SCR_FIRE:
        result = await seffect_fire(sobj);
        break;
    case SCR_EARTH:
        result = await seffect_earth(sobj);
        break;
    case SCR_PUNISHMENT:
        result = await seffect_punishment(sobj);
        break;
    case SCR_STINKING_CLOUD:
        result = await seffect_stinking_cloud(sobj);
        break;
    case SCR_MAIL:
        result = await seffect_mail(sobj);
        break;
    default:
        // impossible
        result = sobj;
        break;
    }
    if (!result) update_inventory();
    return result ? 0 : 1;
}
 
// ── read_ok: getobj callback for doread ──
// C ref: read.c:315
function read_ok(obj) {
    if (!obj) return GETOBJ_EXCLUDE;
    if (obj.oclass === SCROLL_CLASS || obj.oclass === SPBOOK_CLASS)
        return GETOBJ_SUGGEST;
    return GETOBJ_DOWNPLAY;
}
 
// ── doread ──
 
export async function doread() {
    game.known = false;
    if (check_capacity(null)) return ECMD_OK;
 
    const scroll = await getobj('read', read_ok, GETOBJ_PROMPT);
    if (!scroll) return ECMD_CANCEL;
    const otyp = scroll.otyp;
    scroll.pickup_prev = 0;
 
    if (otyp === FORTUNE_COOKIE) {
        if (game.flags.verbose)
            await You('break up the cookie and throw away the pieces.');
        await outrumor(bcsign(scroll), 0);
        if (!Blind()) game.u.uconduct = game.u.uconduct || {};
        useup(scroll);
        return ECMD_TIME;
    }
 
    if (scroll.oclass !== SCROLL_CLASS && scroll.oclass !== SPBOOK_CLASS) {
        await pline('That is a silly thing to read.');
        return ECMD_OK;
    }
    if (Blind() && otyp !== SPE_BOOK_OF_THE_DEAD) {
        let what = null;
        if (otyp === SPE_NOVEL) what = 'words';
        else if (scroll.oclass === SPBOOK_CLASS) what = 'mystic runes';
        else if (!scroll.dknown) what = 'formula on the scroll';
        if (what) {
            await pline(`Being blind, you cannot read the ${what}.`);
            return ECMD_OK;
        }
    }
 
    const confused = (!!Confusion());
 
    if (otyp !== SPE_BOOK_OF_THE_DEAD && otyp !== SPE_NOVEL
        && otyp !== SPE_BLANK_PAPER && otyp !== SCR_BLANK_PAPER) {
        livelog_printf();
    }
 
    if (scroll.oclass === SPBOOK_CLASS) {
        return (await study_book(scroll)) ? ECMD_TIME : ECMD_OK;
    }
    scroll.in_use = true;
    let nodisappear = false;
    if (otyp !== SCR_BLANK_PAPER) {
        const silently = !can_chant(game.player);
        nodisappear = (otyp === SCR_FIRE
                       || (otyp === SCR_REMOVE_CURSE && scroll.cursed));
        if (Blind())
            await pline(nodisappear
                ? `You ${silently ? 'cogitate' : 'pronounce'} the formula on the scroll.`
                : `As you ${silently ? 'cogitate' : 'pronounce'} the formula on it, the scroll disappears.`);
        else
            await pline(nodisappear ? 'You read the scroll.'
                                    : 'As you read the scroll, it disappears.');
        if (confused) {
            if (Hallucination())
                await pline('Being so trippy, you screw up...');
            else
                await pline(`Being confused, you ${silently ? 'misunderstand' : 'mispronounce'} the magic words...`);
        }
    }
    if (!(await seffects(scroll))) {
        if (!game.objects[otyp].oc_name_known) {
            if (game.known) learnscroll(scroll);
            else await trycall(scroll);
        }
        scroll.in_use = false;
        if (otyp !== SCR_BLANK_PAPER) useup(scroll);
    }
    return ECMD_TIME;
}
 
// ── drop_boulder_on_player ──
 
export async function drop_boulder_on_player(confused, helmet_protects, byu, skip_uswallow) {
    // C: read.c drop_boulder_on_player
    if (game.u.uswallow && !skip_uswallow) {
        await drop_boulder_on_monster(game.u.ux, game.u.uy, confused, byu);
        return;
    }
    const otmp2 = mksobj(confused ? ROCK : BOULDER, false, false);
    if (!otmp2) return;
    otmp2.quan = confused ? rn1(5, 2) : 1;
    otmp2.owt = weight(otmp2);
    let dmg;
    if (!amorphous(game.player?.data) && !Passes_walls()
        && !noncorporeal(game.player?.data) && !unsolid(game.player?.data)) {
        await You(`are hit by ${doname(otmp2)}!`);
        dmg = dmgval(otmp2, game.player) * otmp2.quan;
        const _uarmh = get_uarmh();
        if (_uarmh && helmet_protects) {
            if (hard_helmet(_uarmh)) {
                await pline('Fortunately, you are wearing a hard helmet.');
                if (dmg > 2) dmg = 2;
            } else if (game.flags?.verbose) {
                await pline(`${Yname2(_uarmh)} does not protect you.`);
            }
        }
    } else {
        dmg = 0;
    }
    wake_nearto(game.u.ux, game.u.uy, 4 * 4);
    if (!await flooreffects(otmp2, game.u.ux, game.u.uy, 'fall')) {
        place_object(otmp2, game.u.ux, game.u.uy);
        stackobj(otmp2);
        newsym(game.u.ux, game.u.uy);
    }
    if (dmg)
        await losehp(Maybe_Half_Phys(dmg), 'scroll of earth', KILLED_BY_AN);
}
 
// ── wand_explode ──
 
export async function wand_explode(obj, chg) {
    let n, k;
    const expl = !chg ? 'suddenly' : 'vibrates violently and';

    if (!chg) chg = 2;
    n = (obj.spe || 0) + chg;
    if (n < 2) n = 2;
    switch (obj.otyp) {
    case WAN_WISHING: k = 12; break;
    case WAN_CANCELLATION: case WAN_DEATH: case WAN_POLYMORPH: case WAN_UNDEAD_TURNING:
        k = 10; break;
    case WAN_COLD: case WAN_FIRE: case WAN_LIGHTNING: case WAN_MAGIC_MISSILE:
        k = 8; break;
    case WAN_NOTHING: k = 4; break;
    default: k = 6; break;
    }
    const dmg = c_d(n, k);
    obj.in_use = true;
    await pline(`${Yname2(obj)} ${expl} explodes!`);
    await losehp(Maybe_Half_Phys(dmg), 'exploding wand', KILLED_BY_AN);
    useup(obj);
    exercise(A_STR, false);
}
 
// ── set_lit and litroom ──
 
// Module-level gremlin list for litroom (C: static gremlins linked list)
 
export function set_lit(x, y, val) {
    const loc = levl(x, y);
    if (!loc) return;
    if (val) {
        loc.lit = 1;
        // Track gremlins hit by light (C: builds linked list)
        const mtmp = m_at(x, y);
        if (mtmp && mtmp.data === mons[PM_GREMLIN]) {
            game.litroom_gremlins = { mon: mtmp, nxt: game.litroom_gremlins };
        }
    } else {
        loc.lit = 0;
        snuff_light_source(x, y);
    }
}
 
export async function litroom(on, obj) {
    const u = game.u;
    if (!u) return;
 
    const blessed_effect = !!(obj && obj.oclass === SCROLL_CLASS && obj.blessed);
    const no_op = (u.uswallow || Underwater());
    const is_lit = {}; // non-null flag for set_lit val parameter
 
    // Update object lights and produce message (C ref: read.c:2503-2567)
    if (!on) {
        let still_lit = 0;
        // The magic douses lamps and might curse artifact lights
        for (let otmp = game.invent; otmp; otmp = otmp.nobj) {
            if (otmp.lamplit) {
                if (!artifact_light(otmp))
                    snuff_lit(otmp);
                else
                    await impact_arti_light(otmp, true, !Blind());
                if (otmp.lamplit)
                    ++still_lit;
            }
        }
        if (!Blind()) {
            if (still_lit)
                await pline_The('ambient light seems dimmer.');
            else if (u.uswallow)
                await pline('It seems even darker in here than before.');
            else
                await You('are surrounded by darkness!');
        }
    } else {
        if (blessed_effect) {
            for (let otmp = game.invent; otmp; otmp = otmp.nobj) {
                if (otmp.lamplit && artifact_light(otmp))
                    await impact_arti_light(otmp, false, !Blind());
            }
        }
        if (u.uswallow) {
            if (!Blind()) {
                if (digests(u.ustuck?.data))
                    await pline(`${s_suffix(Monnam(u.ustuck))} ${mbodypart(u.ustuck, STOMACH)} is lit.`);
                else if (is_whirly(u.ustuck?.data))
                    await pline(`${Monnam(u.ustuck)} shines briefly.`);
                else
                    await pline(`${Monnam(u.ustuck)} glistens.`);
            }
        } else if (!Blind() && !Is_rogue_level(u.uz)) {
            await pline(`A lit field ${no_op ? 'briefly ' : ''}surrounds you!`);
        }
    }
 
    // No-op when swallowed or in water
    if (no_op)
        return;
 
    // If darkening and punished but not blind, pick up ball & chain
    if (Punished() && !on && !Blind())
        move_bc(1, 0, get_uball()?.ox, get_uball()?.oy, get_uchain()?.ox, get_uchain()?.oy);
 
    if (Is_rogue_level(u.uz)) {
        // Rogue level: light entire room (C ref: read.c:2580-2594)
        const loc = levl(u.ux, u.uy);
        const ROOMOFFSET = 3;
        const rnum = (loc?.roomno || 0) - ROOMOFFSET;
        if (rnum >= 0 && game.level.rooms?.[rnum]) {
            const rm = game.level.rooms[rnum];
            for (let rx = rm.lx - 1; rx <= rm.hx + 1; rx++)
                for (let ry = rm.ly - 1; ry <= rm.hy + 1; ry++)
                    set_lit(rx, ry, on ? is_lit : null);
            rm.rlit = on ? 1 : 0;
        }
    } else {
        await do_clear_area(u.ux, u.uy, blessed_effect ? 9 : 5,
            set_lit, on ? is_lit : null);
    }
 
    if (!Blind()) {
        vision_recalc(2);
        // Replace ball & chain after darkening
        if (Punished() && !on)
            move_bc(0, 0, get_uball()?.ox, get_uball()?.oy, get_uchain()?.ox, get_uchain()?.oy);
    }
 
    game.vision_full_recalc = 1; // delayed vision recalculation
    if (game.litroom_gremlins) {
        // Can't delay vision recalc after all
        vision_recalc(0);
        // Gremlins affected when hit by light (C: light_hits_gremlin)
        while (game.litroom_gremlins) {
            const gremlin = game.litroom_gremlins;
            game.litroom_gremlins = gremlin.nxt;
            // light_hits_gremlin not yet fully ported; consume RNG for parity
            rnd(5);
        }
    }
}
 
// ── punish and unpunish ──
 
export async function punish(sobj) {
    const reuse_ball = (sobj && sobj.otyp === HEAVY_IRON_BALL) ? sobj : null;
    const cursed_levy = (sobj && sobj.cursed) ? 1 : 0;
 
    if (!reuse_ball)
        await You('are being punished for your misbehavior!');
    if (Punished()) {
        await Your('iron ball gets heavier.');
        const _uball = get_uball();
        if (_uball) _uball.owt = (_uball.owt || 0) + WT_IRON_BALL_INCR * (1 + cursed_levy);
        return;
    }
    if (amorphous(game.player?.data) || is_whirly(game.player?.data)
        || unsolid(game.player?.data)) {
        if (!reuse_ball) {
            await pline('A ball and chain appears, then falls away.');
            await dropy(mkobj(BALL_CLASS, true));
        } else {
            await dropy(reuse_ball);
        }
        return;
    }
    setworn(mkobj(CHAIN_CLASS, true), W_CHAIN);
    if (!reuse_ball)
        setworn(mkobj(BALL_CLASS, true), W_BALL);
    else
        setworn(reuse_ball, W_BALL);
 
    if (!game.u.uswallow) {
        placebc();
        if (Blind()) set_bc(1);
        newsym(game.u.ux, game.u.uy);
    }
}
 
export function unpunish() {
    const savechain = get_uchain();
    setworn(null, W_CHAIN);
    delobj(savechain);
    setworn(null, W_BALL);
}
 
// ── do_class_genocide ──
 
export async function do_class_genocide() {
    let i, j, immunecnt, gonecnt, goodcnt, mclass, feel_dead = 0;
    let ll_done = 0;
    let gameover = false;

    for (j = 0; ; j++) {
        if (j >= 5) {
            await pline(thats_enough_tries);
            return;
        }
        let promptbuf = 'What class of monsters do you want to genocide?';
        if (j > 0)
            promptbuf += " [enter the symbol or name representing a class, or '?']";
        const buf = mungspaces(await getlin(promptbuf) || '');
        if (!buf) {
            if (j + 1 < 5)
                await pline("Type letter (or punctuation) or name used for a class of monsters or 'none'.");
            else
                await pline('No class of monsters specified.');
            continue;
        }
        if (buf === '\x1b' || buf.toLowerCase() === 'none'
            || buf.toLowerCase() === "'none'" || buf.toLowerCase() === 'nothing') {
            livelog_printf();
            return;
        }
        if (buf === '?' || buf === "'?'") {
            await list_genocided('g', false);
            --j;
            continue;
        }

        mclass = name_to_monclass(buf, 0);
        if (mclass === 0) {
            const mi = name_to_mon(buf, 0);
            if (mi !== NON_PM) mclass = mons[mi].mlet;
        }
        immunecnt = gonecnt = goodcnt = 0;
        for (i = LOW_PM; i < NUMMONS; i++) {
            if (mons[i].mlet === mclass) {
                if (!(mons[i].geno & G_GENO))
                    immunecnt++;
                else if (game.mvitals?.[i]?.mvflags & G_GENOD)
                    gonecnt++;
                else
                    goodcnt++;
            }
        }
        if (!goodcnt && mclass !== mons[game.u?.urole?.mnum]?.mlet
            && mclass !== mons[game.u?.urace?.mnum]?.mlet) {
            if (gonecnt)
                await pline('All such monsters are already nonexistent.');
            else if (immunecnt || mclass === S_invisible)
                await You("aren't permitted to genocide such monsters.");
            else
                await pline(`That ${buf.length === 1 ? 'symbol' : 'response'} does not represent any monster.`);
            continue;
        }

        for (i = LOW_PM; i < NUMMONS; i++) {
            if (mons[i].mlet === mclass) {
                const nam = makeplural(mons[i].mname || 'monster');
                if (Your_Own_Role(i) || Your_Own_Race(i)
                    || ((mons[i].geno & G_GENO)
                        && !(game.mvitals?.[i]?.mvflags & G_GENOD))) {
                    if (!ll_done++) {
                        livelog_printf();
                    }
                    if (!game.mvitals) game.mvitals = {};
                    if (!game.mvitals[i]) game.mvitals[i] = { mvflags: 0 };
                    game.mvitals[i].mvflags |= (G_GENOD | G_NOCORPSE);
                    await kill_genocided_monsters();
                    update_inventory();
                    await pline(`Wiped out all ${nam}.`);
                    if (Upolyd() && i === game.u.umonnum) {
                        game.u.mh = -1;
                        if (Unchanging()) {
                            if (!feel_dead++)
                                await urgent_pline('You die.');
                            gameover = true;
                        } else
                            await rehumanize();
                    }
                    if (i === game.u?.urole?.mnum || i === game.u?.urace?.mnum) {
                        game.u.uhp = -1;
                        if (Upolyd()) {
                            if (!feel_dead++)
                                await You_feel(`${udeadinside()} inside.`);
                        } else {
                            if (!feel_dead++)
                                await urgent_pline('You die.');
                            gameover = true;
                        }
                    }
                } else if (game.mvitals?.[i]?.mvflags & G_GENOD) {
                    if (!gameover)
                        await pline(`${upstart(nam)} are already nonexistent.`);
                } else if (!gameover) {
                    if (i !== PM_NINJA || Role_if(PM_SAMURAI)) {
                        const named = type_is_pname(mons[i]);
                        let uniq = !!(mons[i].geno & G_UNIQ);
                        if (i === PM_HIGH_CLERIC) uniq = false;
                        await You(`aren't permitted to genocide ${(uniq && !named) ? 'the ' : ''}${(uniq || named) ? (mons[i].mname || 'monster') : nam}.`);
                    }
                }
            }
        }
        if (gameover || game.u.uhp === -1) {
            delayed_killer(KILLED_BY_AN, 0, 'scroll of genocide');
            if (gameover)
                await done(GENOCIDED);
        }
        return;
    }
}
 
// ── do_genocide ──
 
export async function do_genocide(how) {
    let buf, mndx, killplayer = 0;
    let ptr;
 
    if (how & PLAYER) {
        mndx = game.u.umonster || game.u?.urole?.mnum || 0;
        ptr = mons[mndx];
        buf = pmname(ptr, Ugender());
        killplayer++;
    } else {
        buf = '';
        for (let i = 0; ; i++) {
            if (i >= 5) {
                // cursed effect => no free pass (unless rndmonst fails)
                if (!(how & REALLY)) {
                    ptr = rndmonst();
                    if (ptr) break;
                }
                await pline(thats_enough_tries);
                return;
            }
            let promptbuf = 'What type of monster do you want to genocide?';
            if (i > 0)
                promptbuf += " [enter the name of a type of monster, or '?']";
            buf = mungspaces(await getlin(promptbuf) || '');
            if (!buf) {
                if (i + 1 < 5)
                    await pline("Type the name of a type of monster or 'none'.");
                else
                    await pline('No type of monster specified.');
                continue;
            }
            if (buf === '\x1b' || buf.toLowerCase() === 'none'
                || buf.toLowerCase() === "'none'" || buf.toLowerCase() === 'nothing') {
                if (!(how & REALLY)) {
                    ptr = rndmonst();
                    if (ptr) break;
                }
                livelog_printf();
                return;
            }
            if (buf === '?' || buf === "'?'") {
                await list_genocided('g', false);
                --i;
                continue;
            }
 
            mndx = name_to_mon(buf, 0);
            if (mndx === NON_PM || (game.mvitals?.[mndx]?.mvflags & G_GENOD)) {
                await pline(`Such creatures ${(mndx === NON_PM) ? 'do not' : 'no longer'} exist in this world.`);
                continue;
            }
            ptr = mons[mndx];
            if (Your_Own_Role(mndx) || Your_Own_Race(mndx)) {
                killplayer++;
                break;
            }
            if (is_human(ptr))
                adjalign(-sgn(game.u?.ualign?.type || 0));
            if (is_demon(ptr))
                adjalign(sgn(game.u?.ualign?.type || 0));
 
            if (!(ptr.geno & G_GENO)) {
                if (!Deaf()) {
                    if (game.flags?.verbose)
                        await pline('A thunderous voice booms through the caverns:');
                    await verbalize('No, mortal!  That will not be done.');
                }
                continue;
            }
            if (Unchanging() && ptr === game.player?.data)
                killplayer++;
            break;
        }
        mndx = monsndx(ptr);
    }
 
    let which = 'all ';
    const realbuf = ptr?.mname || 'monster';
    if (Hallucination()) {
        if (Upolyd()) {
            buf = pmname(game.player?.data, game.flags?.female ? 1 : 0);
        } else {
            buf = (game.flags?.female && game.u?.urole?.name?.f)
                ? game.u.urole.name.f : (game.u?.urole?.name?.m || 'adventurer');
            buf = buf.charAt(0).toLowerCase() + buf.slice(1);
        }
    } else {
        buf = realbuf;
        if ((ptr.geno & G_UNIQ) && ptr !== mons[PM_HIGH_CLERIC])
            which = !type_is_pname(ptr) ? 'the ' : '';
    }
 
    if (how & REALLY) {
        livelog_printf();
 
        if (!game.mvitals) game.mvitals = {};
        if (!game.mvitals[mndx]) game.mvitals[mndx] = { mvflags: 0 };
        game.mvitals[mndx].mvflags |= (G_GENOD | G_NOCORPSE);
        await pline(`Wiped out ${which}${(which !== 'a') ? buf : makeplural(buf)}.`);
 
        if (killplayer) {
            game.u.uhp = -1;
            if (how & PLAYER) {
                delayed_killer(KILLED_BY, 0, 'genocidal confusion');
            } else if (how & ONTHRONE) {
                delayed_killer(KILLED_BY_AN, 0, 'imperious order');
            } else {
                delayed_killer(KILLED_BY_AN, 0, 'scroll of genocide');
            }
            if (Upolyd() && ptr !== game.player?.data) {
                await You_feel(`${udeadinside()} inside.`);
            } else {
                await done(GENOCIDED);
            }
        } else if (ptr === game.player?.data) {
            await rehumanize();
        }
        await kill_genocided_monsters();
        update_inventory();
    } else {
        let cnt = 0;
        const census = monster_census(false);

        if (!(mons[mndx]?.geno & G_UNIQ)
            && !(game.mvitals?.[mndx]?.mvflags & (G_GENOD | G_EXTINCT))) {
            const bound = rn1(3, 4);
            for (let ii = 0; ii < bound; ii++) {
                if (!await makemon(ptr, game.u.ux, game.u.uy, NO_MINVENT | MM_NOMSG))
                    break;
                ++cnt;
                if (game.mvitals?.[mndx]?.mvflags & G_EXTINCT)
                    break;
            }
        }
        if (cnt) {
            const actual_cnt = monster_census(false) - census;
            const display_cnt = actual_cnt > 0 ? actual_cnt : cnt;
            await pline(`Sent in ${(display_cnt > 1) ? 'some ' : ''}${(display_cnt > 1) ? makeplural(buf) : an(buf)}.`);
        } else
            await pline(nothing_happens);
    }
}
 
// ── create_particular (wizard mode) ──
 
const MAXMCLASSES = 20;
 
function create_particular_parse(str) {
    const d = {
        quan: 1,
        monclass: MAXMCLASSES,
        which: game.u?.urole?.mnum || 0,
        fem: -1,
        genderconf: -1,
        randmonst: false,
        maketame: false, makepeaceful: false, makehostile: false,
        sleeping: false, saddled: false, invisible: false, hidden: false,
    };
 
    let bufp = str.trim();
 
    // quantity
    const qmatch = bufp.match(/^(\d+)\s*/);
    if (qmatch) {
        d.quan = parseInt(qmatch[1], 10);
        bufp = bufp.slice(qmatch[0].length);
    }
    const QUAN_LIMIT = ROWNO * (COLNO - 1);
    if (d.quan < 1 || d.quan > QUAN_LIMIT)
        d.quan = Math.max(1, QUAN_LIMIT - monster_census(false));
 
    // state keywords (C: strstri + memset to spaces)
    if (bufp.includes('saddled ')) { d.saddled = true; bufp = bufp.replace('saddled ', ' '); }
    if (bufp.includes('sleeping ')) { d.sleeping = true; bufp = bufp.replace('sleeping ', ' '); }
    if (bufp.includes('invisible ')) { d.invisible = true; bufp = bufp.replace('invisible ', ' '); }
    if (bufp.includes('hidden ')) { d.hidden = true; bufp = bufp.replace('hidden ', ' '); }
    // check "female" before "male" to avoid false hit mid-word
    if (bufp.includes('female ')) { d.fem = 1; bufp = bufp.replace('female ', ' '); }
    if (bufp.includes('male ')) { d.fem = 0; bufp = bufp.replace('male ', ' '); }
    bufp = bufp.replace(/\s+/g, ' ').trim();
 
    // disposition
    if (bufp.startsWith('tame ')) { bufp = bufp.slice(5); d.maketame = true; }
    else if (bufp.startsWith('peaceful ')) { bufp = bufp.slice(9); d.makepeaceful = true; }
    else if (bufp.startsWith('hostile ')) { bufp = bufp.slice(8); d.makehostile = true; }
 
    // random
    if (bufp === '*' || bufp === 'random') {
        d.randmonst = true;
        return d;
    }
 
    d.which = name_to_mon(bufp, 0);
    if (ismnum(d.which))
        return d;

    const which_ref = { value: 0 };
    d.monclass = name_to_monclass(bufp, which_ref);
    d.which = which_ref.value || d.which;
 
    if (ismnum(d.which)) {
        d.monclass = MAXMCLASSES;
        return d;
    } else if (d.monclass === S_invisible) {
        d.which = PM_STALKER;
        d.monclass = MAXMCLASSES;
        return d;
    } else if (d.monclass === S_WORM_TAIL) {
        d.which = PM_LONG_WORM;
        d.monclass = MAXMCLASSES;
        return d;
    } else if (d.monclass > 0) {
        d.which = game.u?.urole?.mnum || 0;
        return d;
    }
    return null;
}
 
async function create_particular_creation(d) {
    let whichpm = null;
    let firstchoice = NON_PM;
    let madeany = false;
 
    if (!d.randmonst) {
        firstchoice = d.which;
        const mtype_ref = { value: d.which };
        if (cant_revive(mtype_ref, false, null)
            && firstchoice !== PM_LONG_WORM_TAIL) {
            d.which = mtype_ref.value;
        }
        whichpm = mons[d.which];
    }
    for (let i = 0; i < d.quan; i++) {
        let mmflags = NO_MM_FLAGS;
 
        if (d.monclass !== MAXMCLASSES)
            whichpm = mkclass(d.monclass, 0);
        else if (d.randmonst)
            whichpm = rndmonst();
 
        if (d.genderconf === -1) {
            if (d.fem !== -1 && (!whichpm || (!is_male(whichpm) && !is_female(whichpm))))
                mmflags |= (d.fem === 1) ? MM_FEMALE : (d.fem === 0) ? MM_MALE : 0;
            mmflags |= MM_NOEXCLAM;
        } else {
            mmflags |= (d.fem === 1) ? MM_FEMALE : (d.fem === 0) ? MM_MALE : 0;
        }
        if (d.invisible)
            mmflags |= MM_MINVIS;
 
        const mtmp = await makemon(whichpm, game.u.ux, game.u.uy, mmflags);
        if (!mtmp) {
            if (d.monclass === MAXMCLASSES && !d.randmonst)
                break;
            continue;
        }
        const mx = mtmp.mx, my = mtmp.my;
        if (d.maketame) {
            await tamedog(mtmp, null, false);
        } else if (d.makepeaceful || d.makehostile) {
            mtmp.mtame = 0;
            mtmp.mpeaceful = d.makepeaceful ? 1 : 0;
            set_malign(mtmp);
        }
        if (d.saddled && can_saddle(mtmp) && !which_armor(mtmp, W_SADDLE))
            await put_saddle_on_mon(null, mtmp);
        if (d.hidden
            && ((is_hider(mtmp.data) && mtmp.data.mlet !== S_MIMIC)
                || (hides_under(mtmp.data) && OBJ_AT(mx, my))
                || (mtmp.data.mlet === S_EEL && is_pool(mx, my))))
            mtmp.mundetected = 1;
        if (d.sleeping)
            mtmp.msleeping = 1;
        if ((d.hidden || d.invisible) && !canspotmon(mtmp))
            flash_mon(mtmp);
 
        madeany = true;
        if (mtmp.cham !== NON_PM && firstchoice !== NON_PM
            && mtmp.cham !== firstchoice)
            await newcham(mtmp, mons[firstchoice], 0);
    }
    return madeany;
}
 
export async function create_particular() {
    const CP_TRYLIM = 5;
    let tryct = CP_TRYLIM, altmsg = 0;
    let prompt = 'Create what kind of monster?';
 
    let d;
    do {
        const buf = mungspaces(await getlin(prompt, null, { logHookedLifecycle: true }) || '');
        if (!buf || buf === '\x1b')
            return false;
 
        d = create_particular_parse(buf);
        if (d) break;

        if (buf || altmsg || tryct < 2) {
            await pline("I\'ve never heard of such monsters.");
        } else {
            await pline('Try again (type * for random, ESC to cancel).');
            ++altmsg;
        }
        if (tryct === CP_TRYLIM)
            prompt += ' [type name or symbol]';
    } while (--tryct > 0);
 
    if (!tryct) {
        await pline(thats_enough_tries);
        return false;
    }
    return await create_particular_creation(d);
}
 
// ── cant_revive ──
 
export function cant_revive(mtype_ref, revival, from_obj) {
    const mtype = mtype_ref.value;
    if (mtype === PM_GUARD || (mtype === PM_SHOPKEEPER && !revival)
        || mtype === PM_HIGH_CLERIC || mtype === PM_ALIGNED_CLERIC
        || mtype === PM_ANGEL) {
        mtype_ref.value = PM_HUMAN_ZOMBIE;
        return true;
    } else if (mtype === PM_LONG_WORM_TAIL) {
        mtype_ref.value = PM_LONG_WORM;
        return true;
    } else if (unique_corpstat(mons[mtype])
               && (!from_obj || !has_omonst(from_obj))) {
        mtype_ref.value = PM_DOPPELGANGER;
        return true;
    }
    return false;
}
 
// ── do_stinking_cloud ──
 
async function do_stinking_cloud(sobj, mention_stinking) {
    // C: read.c do_stinking_cloud
    const cc = { x: game.u.ux, y: game.u.uy };
    await pline(`Where do you want to center the ${mention_stinking ? 'stinking ' : ''}cloud?`);
    getpos_sethilite(display_stinking_cloud_positions, can_center_cloud);
    if (await getpos(cc, true, 'the desired position') < 0) {
        await pline(Never_mind);
        return;
    } else if (!can_center_cloud(cc.x, cc.y)) {
        if (Hallucination())
            await pline('Ugh... someone cut the cheese.');
        else
            await pline(`${sobj.oclass === SCROLL_CLASS ? 'The scroll crumbles with' : 'You smell'} a whiff of rotten eggs.`);
        return;
    }
    await create_gas_cloud(cc.x, cc.y, 15 + 10 * bcsign(sobj),
                     8 + 4 * bcsign(sobj));
}
 
// ── valid_cloud_pos (exported) ──
export { valid_cloud_pos };
 
/*read.c*/
 
export function init_read_globals() {
    game.litroom_gremlins = null;
}