All files / js dothrow.js

55.29% Statements 956/1729
47.54% Branches 203/427
51.56% Functions 33/64
55.29% Lines 956/1729

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 172973x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x     73x 73x 73x 73x     73x 73x 73x     73x 73x 73x 73x 73x           73x 73x 73x 73x         73x 73x 73x 73x 73x 73x 73x 73x 73x 73x   73x 73x   73x     73x 51x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 315x 227x 93x 19x         81x   73x 3x 73x 231x 231x 231x 231x 231x 231x 231x 231x 231x 73x 73x 73x 40x 40x 40x 40x 1x 1x 1x 40x       40x 1x 1x 1x 40x       40x     40x 40x       40x 38x 40x 40x 40x 73x 73x 160x 160x 160x 160x 160x 160x 160x 160x 160x 160x 140x 160x 160x 160x 160x 160x 160x 160x 109x 160x 73x 73x 51x 51x 51x 51x     51x 3x 3x 3x 48x 51x 48x 51x 73x 73x 73x 13x 13x 13x 11x 13x 10x 13x 73x 73x                                                                                           73x 73x                         73x 73x 73x 38x 38x 38x 37x 37x 38x 38x 38x 38x 38x     37x                                         37x         38x 38x 37x     37x 34x 35x 3x 3x 3x 3x 3x                                     37x 38x 38x 38x 73x 73x 73x 2x 2x             2x 73x 73x 44x 44x 44x 44x 44x 44x 44x 44x 2x 2x 2x 2x       2x 2x 42x 44x     42x       44x         44x 44x         44x 1x 1x 1x 1x 41x 41x         41x 41x 41x 41x 44x 44x 44x 44x 40x 44x 34x 34x 34x 34x 34x 34x   34x 34x       34x 34x 34x 34x 34x 3x 3x 1x 1x 1x 3x       3x       3x 2x 3x 3x 3x 3x 3x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 41x 44x 44x 2x 2x 44x 44x 44x 44x 44x 44x 44x 44x 43x 44x 1x 1x 1x 1x 1x 1x 44x 44x 44x 44x 41x 41x 41x 41x 41x 44x       41x 44x 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 73x 73x 73x 10x 10x 10x 10x 10x 10x 10x 5x 10x 4x 10x 10x 10x 7x 14x 14x 14x 14x 14x 14x 14x 10x 3x 4x 4x 4x 4x 4x 4x 4x 3x 10x 3x 3x 3x 10x 73x 73x 73x 9x 9x       9x 9x 9x             9x 9x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 9x 8x 9x 8x 9x 73x 73x 73x 6x 6x 73x 73x 73x 2x       2x                       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 73x 73x 73x 2x 2x 2x 2x 2x 73x 73x                                                       73x 73x 73x                                                         73x 73x                   73x 73x 73x                                               73x 73x                                                                                                                                                                           73x 73x 73x                       73x 73x                               73x 73x 45x 45x 45x 45x 45x 73x 73x                 73x 73x 45x 45x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 45x 45x 73x 73x 73x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x                                 45x 45x 45x 45x 32x 45x 45x           45x 45x 45x 45x         45x                         45x                     45x 45x 45x 45x 45x 45x 45x 45x 45x 45x       45x 45x 38x 36x 36x 36x 36x 38x 1x 1x 1x 1x 38x 45x           45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x       45x 45x       45x 8x 45x     37x 37x 37x                                                                                     37x 37x 37x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 37x       36x 37x                 36x 36x       36x 37x 37x 36x 36x 36x 37x 37x 36x 36x 36x 37x 37x 36x 36x 37x 44x 45x 73x 73x                                   73x 73x 73x 23x 23x 23x 23x             23x 23x     23x     23x 23x 23x 23x 23x 23x 23x 23x 73x 73x 4x 4x 4x 4x 4x 4x 4x 4x 4x 73x 73x 73x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 20x 23x 73x 73x 73x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x                 19x 19x 19x 19x 19x                       19x 19x 19x 19x   19x 19x   19x 19x 19x 19x 19x           19x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 8x 8x 8x 8x 8x 7x 19x 4x 4x 4x 4x 19x                                                                                       11x 19x 73x 73x                                                                                                                                 73x 73x 73x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 1x 39x 37x 39x 39x 73x 73x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 1x 1x 1x 1x 1x 2x 2x     2x     2x 2x 1x 1x 2x 2x 73x 73x 73x             73x 73x 73x 2x 2x 2x 2x   2x 2x     2x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x     2x         2x 2x     2x 1x 2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 73x 73x 73x 1x 1x 1x 1x 1x 1x     1x 73x 73x 73x 1x 1x 1x 1x 1x 73x 73x                                                                                                         73x 73x 73x
// dothrow.js — Throwing items (port of dothrow.c)
// C ref: dothrow.c — 2737 lines
//
// Ported functions:
//   multishot_class_bonus()  — class-based multishot bonus (dothrow.c:38)
//   throw_ok()               — getobj callback (dothrow.c:316)
//   ok_to_throw()            — precondition check (dothrow.c:296)
//   dothrow()                — 't' command entry point (dothrow.c:351)
//   dofire()                 — 'f' command entry point (dothrow.c:468)
//   throw_obj()              — throw a specific object (dothrow.c:87)
//   endmultishot()           — stop multishot early (dothrow.c:589)
//   autoquiver()             — auto-fill quiver (dothrow.c:381)
//   find_launcher()          — find launcher for ammo (dothrow.c:447)
//   hitfloor()               — object hits floor (dothrow.c:605)
//   walk_path()              — Bresenham line walk (dothrow.c:656)
//   hurtle_step()            — hero hurtle single step (dothrow.c:773)
//   hurtle_jump()            — hurtle with jump flag (dothrow.c:742)
//   hurtle()                 — hero knockback (dothrow.c:1078)
//   will_hurtle()            — check if monster can hurtle (dothrow.c:978)
//   mhurtle_step()           — monster hurtle step (dothrow.c:993)
//   mhurtle()                — monster knockback (dothrow.c:1131)
//   check_shop_obj()         — shop accounting (dothrow.c:1182)
//   harmless_missile()       — is missile harmless? (dothrow.c:1221)
//   toss_up()                — throw upward (dothrow.c:1256)
//   throwing_weapon()        — weapon meant to be thrown (dothrow.c:1430)
//   sho_obj_return_to_u()    — display returning weapon (dothrow.c:1442)
//   throwit_return()         — cleanup after throw (dothrow.c:1461)
//   swallowit()              — swallowed throw (dothrow.c:1468)
//   throwit_mon_hit()        — thrown obj hits mon (dothrow.c:1482)
//   throwit()                — main throw execution (dothrow.c:1510)
//   return_throw_to_inv()    — return throw-and-return to inv (dothrow.c:1855)
//   omon_adj()               — monster hit adjustment (dothrow.c:1913)
//   tmiss()                  — thrown object misses (dothrow.c:1951)
//   should_mulch_missile()   — should missile break? (dothrow.c:1977)
//   thitmonst()              — thrown obj hits monster (dothrow.c:2011)
//   gem_accept()             — gem hits unicorn (dothrow.c:2309)
//   hero_breaks()            — hero causes break (dothrow.c:2417)
//   breaks()                 — non-hero break (dothrow.c:2444)
//   release_camera_demon()   — camera break effect (dothrow.c:2458)
//   breakobj()               — object breaks (dothrow.c:2480)
//   breaktest()              — will object break? (dothrow.c:2582)
//   breakmsg()               — break message (dothrow.c:2612)
//   throw_gold()             — throw gold (dothrow.c:2656)
import { game } from './gstate.js';
import { rn2, rnd, rn1, rnl, c_d, pushRngLogEntry } from './rng.js';
import { pline, You, Your, You_feel, You_hear, pline_The, verbalize, impossible } from './pline.js';
import { Blind, BlindedTimeout, Confusion, Fumbling, getLuck, Half_gas_damage, Hallucination, has_ceiling, Is_airlevel, Is_waterlevel, Levitation, Maybe_Half_Phys, maybe_polyd, Passes_walls, Punished, Race_if, Role_if, Role_switch, Stunned, Underwater, Upolyd } from './macros.js';
import { getdir, nomul } from './cmd.js';
import { cmdq_add_ec, cmdq_add_key } from './input.js';
import { addinv, addinv_nomerge, carried, delobj, freeinv, getobj, nxtobj, prinv, stackobj } from './invent.js';
import { xname, doname, Doname2, Tobjnam, otense, an, An, the, The, singular, makeplural, corpse_xname, killer_xname, thesimpleoname, helm_simple_name } from './objnam.js';
import { ACID_VENOM, AKLYS, AMULET_OF_YENDOR, ARMOR_CLASS, AXE, BAG_OF_HOLDING, BAG_OF_TRICKS, BLINDING_VENOM, BOOMERANG, BOULDER, BOW, BROADSWORD, BULLWHIP, CLOTH, CLUB, COIN_CLASS, CORPSE, CREAM_PIE, CROSSBOW, CRYSTAL_BALL, DAGGER, DART, EGG, ELVEN_ARROW, ELVEN_BOW, EUCALYPTUS_LEAF, EXPENSIVE_CAMERA, FAKE_AMULET_OF_YENDOR, FLAIL, FLINT, FORTUNE_COOKIE, GAUNTLETS_OF_DEXTERITY, GAUNTLETS_OF_FUMBLING, GAUNTLETS_OF_POWER, GEM_CLASS, GEMSTONE, GLASS, greatest_erosion, HEAVY_IRON_BALL, is_ammo, is_crackable, KELP_FROND, KNIFE, LANCE, LEATHER_GLOVES, LENSES, LONG_SWORD, MACE, MELON, MINERAL, MIRROR, MORNING_STAR, OILSKIN_SACK, ORCISH_ARROW, ORCISH_BOW, PANCAKE, PICK_AXE, POT_OIL, POT_WATER, POTION_CLASS, QUARTERSTAFF, ROCK, RUBBER_HOSE, SACK, SCROLL_CLASS, SHORT_SWORD, SHURIKEN, SILVER, SLING, SPEAR, SPRIG_OF_WOLFSBANE, stone_missile, STRANGE_OBJECT, TOOL_CLASS, TRIDENT, TWO_HANDED_SWORD, UNICORN_HORN, VENOM_CLASS, WAN_STRIKING, WAND_CLASS, WAR_HAMMER, WEAPON_CLASS, YA, YUMI } from './objects.js';
import { A_CON, A_DEX, A_STR, ARM, BOLT_LIM, BRK_BY_HERO, BRK_FROM_INV, BRK_KNOWN_OUTCOME, BRK_KNOWN2BREAK, BRK_KNOWN2NOTBREAK, CQ_CANNED, ECMD_CANCEL, ECMD_FAIL, ECMD_OK, ECMD_TIME, engulfing_u, EXPL_FIERY, EYE, FACE, FOOT, GETOBJ_ALLOWCNT, GETOBJ_DOWNPLAY, GETOBJ_EXCLUDE, GETOBJ_PROMPT, GETOBJ_SUGGEST, HAND, Has_contents, HEAD, HMON_APPLIED, HMON_KICKED, HMON_MELEE, HMON_THROWN, HOLE as HOLE_TRAP, IS_ALTAR, IS_OBSTRUCTED, IS_SOFT, ismnum, isok, KILLED_BY, KILLED_BY_AN, LARGEST_INT, M_AP_TYPE, P_BASIC, P_BOW, P_CROSSBOW, P_DAGGER, P_DART, P_EXPERT, P_KNIFE, P_NONE, P_SHURIKEN, P_SKILLED, P_SLING, P_SPEAR, PIT as PIT_TRAP, POTHIT_HERO_THROW, SLT_ENCUMBER, SPIKED_PIT as SPIKED_PIT_TRAP, STR19, THROWN_TETHERED_WEAPON, THROWN_WEAPON, TRAPDOOR as TRAPDOOR_TRAP, TT_BURIEDBALL, TT_INFLOOR, TT_LAVA, TT_WEB, W_ARM, W_ARMC, W_ARMOR, W_ARMU, W_QUIVER, W_SWAPWEP, W_WEP, ZAP_POS } from './const.js';
import { ACURR, ACURRSTR } from './attrib.js';
import { exercise } from './attrib.js';
import { m_at } from './map_access.js';
import { t_at } from './map_access.js';
import { bhit, boomhit, hit, miss, obj_resists } from './zap.js';
import { add_to_minv, obfree, splitobj, unsplitobj } from './mkobj.js';
import { place_object } from './mkobj.js';
import { canletgo, Norep } from './do.js';
import { dropy, dropz, flooreffects, obj_no_longer_held } from './do.js';
import { container_impact_dmg, ship_object } from './dokick.js';
import { remove_worn_item } from './steal.js';
import { mpickobj } from './steal.js';
import { doquiver_core, doswapweapon, dowield, set_twoweap, setuqwep, setuswapwep, setuwep, welded, weldmsg } from './wield.js';
import { autoreturn_weapon } from './mthrowu.js';
import { P_SKILL, ammo_and_launcher, matching_launcher, skill_name, uslinging, weapon_descr, weapon_type } from './weapon.js';
import { hitval, weapon_hit_bonus } from './weapon.js';
import { hmon, passive_obj } from './uhitm.js';
import { dmgval } from './weapon.js';
import { canseemon, canspotmon, flush_screen, glyph_is_monster, map_invisible, newsym, seemimic, tmp_at, tmp_obj_glyph } from './display.js';
import { distmin, nh_delay_output, ordin, s_suffix, sgn, surface } from './hacklib.js';
import { calc_capacity } from './pickup.js';
import { encumber_msg } from './pickup.js';
import { NODIAG, change_luck, check_capacity, check_special_room, helpless, losehp, next2u } from './hack.js';
import { DEADMONSTER, Monnam, Some_Monnam, a_monnam, impact_disturbs_zombies, minliquid, mon_nam, noit_mhim, stop_occupation, wake_nearto, wakeup } from './mon.js';
import { goodpos } from './makemon.js';
import { vision_recalc } from './vision.js';
import { cansee } from './vision.js';
import { u_on_newpos } from './stairs.js';
import { dotrap, mintrap, instapetrify, minstapetrify, erode_obj } from './trap.js';
import { is_lava as is_lava_fn, is_pool as is_pool_fn, is_waterwall, is_moat } from './dbridge.js';
import { ceiling } from './dig.js';
import { find_mac, which_armor } from './worn.js';
import { obj_sheds_light } from './light.js';
import { closed_door, set_apparxy } from './monmove.js';
import { rloc, tele_restrict } from './teleport.js';
import { breathless, can_blnd, eyecount, haseyes, hates_silver, is_animal, is_axe, is_blade, is_missile, is_pick, is_pole, is_spear, is_sword, is_unicorn, is_weptool, is_wet_towel, mon_hates_blessings, monsndx, nohands, notake, throws_rocks, touch_petrifies, your_race } from './mondata.js';
import { tamedog } from './dog.js';
import { dogfood } from './dogmove.js';
import { make_blinded, potionbreathe, potionhit } from './potion.js';
import { snuff_candle, could_pole_mon } from './apply.js';
import { explode, explode_oil } from './explode.js';
import { is_quest_artifact } from './artifact.js';
import { body_part } from './polyself.js';
import { ART_MJOLLNIR } from './artifacts.js';
import {
    PM_CAVE_DWELLER, PM_HEALER, PM_MONK, PM_CLERIC, PM_RANGER,
    PM_ROGUE, PM_SAMURAI, PM_TOURIST, PM_VALKYRIE, PM_WIZARD,
    PM_NINJA, PM_ELF, PM_ORC, PM_GNOME, PM_HUMAN, PM_DWARF,
    PM_STONE_GOLEM, PM_SHADE,
    MZ_HUGE, MZ_MEDIUM,
    S_EEL,
    M2_UNDEAD, M2_DEMON,
    mons,
} from './monsters.js';
import { hot_pursuit, inside_shop, is_unpaid, shop_keeper, stolen_value } from './shk.js';
import { drop_ball } from './ball.js';
import { hliquid } from './do_name.js';
import { hard_helmet } from './do_wear.js';
import { u_wipe_engr } from './engrave.js';
import { m_in_out_region } from './region.js';
import { place_monster, remove_monster } from './steed.js';
import { cutworm } from './worm.js';
import { Sokoban } from './mklev.js';
// ── Local stubs for unported/unavailable functions ──
// Some_Monnam: imported from mon.js
// noit_mhim: imported from mon.js
// nh_delay_output: imported from hacklib.js
// tmp_at: imported from display.js
const DISP_FLASH = -1;
const DISP_END = -2;
const DISP_TETHER = -3;
const BACKTRACK = -4;
// Object property helpers (matching C macros)
// is_missile: imported from mondata.js
const P_BOOMERANG = 25; // from const.js if available, else define locally
// ammo_and_launcher: imported from weapon.js
// matching_launcher: imported from weapon.js
// is_sword: imported from mondata.js
// is_pole: imported from mondata.js
// greatest_erosion: imported from objects.js
// C ref: weapon.c:63 P_NAME macro — skill type to name
// skill_name: imported from weapon.js
// weapon_descr: imported from weapon.js
// Status helpers
// ceiling: imported from dig.js
// closed_door imported from monmove.js
// is_pool_fn, is_lava_fn: imported from dbridge.js
// is_waterwall imported from dbridge.js
// is_moat imported from dbridge.js
// add_to_minv: imported from mkobj.js
// Monster property helpers
function canseemon_local(mon) { return canseemon(mon); }
function canspotmon_local(mon) { return canspotmon(mon); }
const M_AP_MONSTER = 2;
// glyph_is_monster: imported from display.js
// stone_missile imported from objects.js
// C ref: youprop.h — Hate_silver = hero is lycanthrope or silver-hating form
function Hate_silver() { return (game.u?.ulycn >= 0) || hates_silver(game.youmonst?.data); }
function breakobj_check(obj) { return false; }
const WT_TO_DMG = 6;
const WT_SPLASH_THRESHOLD = 300;
// uslinging: imported from weapon.js
function dry_a_towel(obj, delta, talk) { }
function canletgo_stub(obj, word) { return true; }
// ACURRSTR: imported from attrib.js
const WT_TOOMUCH_DIAGONAL = 5000;
// Sokoban: imported from mklev.js
// Is_airlevel imported from dbridge.js
// C ref: youprop.h — Wwalking = water walking intrinsic/extrinsic
function Wwalking() {
    const WWALKING = 50; // from const.js
    return !!((game.u?.uprops?.[WWALKING]?.intrinsic || 0)
           || (game.u?.uprops?.[WWALKING]?.extrinsic || 0));
}
import { switch_terrain } from './hack.js';
// check_special_room: imported from hack.js
// which_armor imported from worn.js
// C ref: youprop.h — EWwalking = extrinsic water walking
function EWwalking() {
    const WWALKING = 50;
    return game.u?.uprops?.[WWALKING]?.extrinsic || 0;
}
const I_SPECIAL = 0x10000000;
// boomhit: imported from zap.js
// autoreturn_weapon: imported from mthrowu.js
// impact_disturbs_zombies: imported from mon.js
const NEUTRAL = 0;
// erode_obj imported from trap.js
const ERODE_CRACK = 4;
const ER_DESTROYED = 3;
const EF_DESTROY = 0x02;
const EF_VERBOSE = 0x04;
function armor_simple_name(obj) { return xname(obj); }
// helm_simple_name: imported from objnam.js
// eyecount: imported from mondata.js
function befriend_with_obj(data, obj) { return false; }
// could_pole_mon imported from apply.js
function use_pole(obj, verbose) { return ECMD_OK; }
function use_whip(obj) { return ECMD_OK; }
// LARGEST_INT: imported from const.js (32767, matching C's global.h)
function LIMIT_TO_RANGE_INT(lo, hi, v) { return Math.max(lo, Math.min(hi, v)); }
const RLOC_MSG = 1;
const FORCEBUNGLE = 2;
const HURTLING = 4;
const NO_TRAP_FLAGS = 0;
const MM_IGNOREWATER = 0x40;
const MM_IGNORELAVA = 0x80;
const AT_WEAP = 0;
const A_ORIGINAL = 0;
// your_race imported from mondata.js
// Trap types
const MAGIC_PORTAL = 24;
const VIBRATING_SQUARE = 25;
const FIRE_TRAP = 7;
const PIT = 1;
const SPIKED_PIT = 2;
const TRAPDOOR = 11;
const HOLE = 12;
// TT_WEB, TT_LAVA, TT_INFLOOR, TT_BURIEDBALL imported from const.js
// Body part constants imported from const.js (ARM, EYE, FACE, FOOT, HAND, HEAD)
// Accessor shorthands
function get_uwep() { return game.u.uwep; }
function get_uquiver() { return game.u.uquiver; }
function get_uswapwep() { return game.u.uswapwep; }
function get_uarmg() { return game.u.uarmg; }
function get_uarmh() { return game.u.uarmh; }
function get_uarmu() { return game.u.uarmu; }
function get_uarm() { return game.u.uarm; }
function get_uarmc() { return game.u.uarmc; }
function get_uball() { return game.u.uball; }
function get_uchain() { return game.u.uchain; }
// Role_switch: imported from macros.js
function Race_switch() { return game.urace?.mnum ?? -1; }
// C: AutoReturn(o,wmsk)
function AutoReturn(obj, wmsk) {
    if (!obj) return false;
    if ((wmsk & W_WEP) !== 0
        && (obj.otyp === AKLYS
            || (obj.oartifact === ART_MJOLLNIR && Role_if(PM_VALKYRIE))))
        return true;
    if (obj.otyp === BOOMERANG) return true;
    return false;
}
// ── multishot_class_bonus ──
// C ref: dothrow.c:38
export function multishot_class_bonus(pm, ammo, launcher) {
    let multishot = 0;
    const skill = game.objects[ammo.otyp]?.oc_skill || 0;
    switch (pm) {
    case PM_CAVE_DWELLER:
        if (skill === -P_SLING || skill === P_SPEAR)
            multishot++;
        break;
    case PM_MONK:
        if (skill === -P_SHURIKEN)
            multishot++;
        break;
    case PM_RANGER:
        if (skill !== P_DAGGER)
            multishot++;
        break;
    case PM_ROGUE:
        if (skill === P_DAGGER)
            multishot++;
        break;
    case PM_NINJA:
        if (skill === -P_SHURIKEN || skill === -P_DART)
            multishot++;
        /* FALLTHROUGH */
    case PM_SAMURAI:
        if (ammo.otyp === YA && launcher && launcher.otyp === YUMI)
            multishot++;
        break;
    default:
        break;
    }
    return multishot;
}
// ── throw_ok callback for getobj ──
// C ref: dothrow.c:316
function throw_ok(obj) {
    if (!obj)
        return GETOBJ_EXCLUDE;
    if (obj.bknown && welded(obj))
        return GETOBJ_DOWNPLAY;
    if (AutoReturn(obj, obj.owornmask || 0)
        && (obj.oartifact !== ART_MJOLLNIR || ACURR(A_STR) >= STR19(25)))
        return GETOBJ_SUGGEST;
    if (obj.quan === 1 && (obj === get_uwep() || (obj === get_uswapwep() && game.u.twoweap)))
        return GETOBJ_DOWNPLAY;
    if (obj.oclass === COIN_CLASS)
        return GETOBJ_SUGGEST;
    if (!uslinging() && obj.oclass === WEAPON_CLASS)
        return GETOBJ_SUGGEST;
    if (uslinging() && obj.oclass === GEM_CLASS)
        return GETOBJ_SUGGEST;
    if (throws_rocks(game.youmonst?.data) && obj.otyp === BOULDER)
        return GETOBJ_SUGGEST;
    return GETOBJ_DOWNPLAY;
}
// ── ok_to_throw: common precondition for dothrow/dofire ──
// C ref: dothrow.c:296
async function ok_to_throw(shotlimit_ref) {
    shotlimit_ref.value = LIMIT_TO_RANGE_INT(0, LARGEST_INT, game.command_count || 0);
    game.multi = 0;
    if (notake(game.youmonst?.data)) {
        await You('are physically incapable of throwing or shooting anything.');
        return false;
    } else if (nohands(game.youmonst?.data)) {
        await pline("You can't throw or shoot without hands.");
        return false;
    }
    if (check_capacity(null))
        return false;
    return true;
}
// ── dothrow: the 't' command entry point ──
// C ref: dothrow.c:351
export async function dothrow() {
    const shotlimit_ref = { value: 0 };
    if (!await ok_to_throw(shotlimit_ref))
        return ECMD_OK;
    const obj = await getobj('throw', throw_ok, GETOBJ_PROMPT | GETOBJ_ALLOWCNT);
    if (!obj) return ECMD_CANCEL;
    return await throw_obj(obj, shotlimit_ref.value);
}
// ── autoquiver ──
// C ref: dothrow.c:381
function autoquiver() {
    if (get_uquiver()) return;
    let oammo = null, omissile = null, omisc = null, altammo = null;
    const uwep = get_uwep();
    const uswapwep = get_uswapwep();
    for (let otmp = game.invent; otmp; otmp = otmp.nobj) {
        if (otmp.owornmask || otmp.oartifact || !otmp.dknown) {
            ; // skip
        } else if (otmp.otyp === ROCK
                   || (otmp.otyp === FLINT
                       && game.objects[otmp.otyp]?.oc_name_known)
                   || (otmp.oclass === GEM_CLASS
                       && (game.objects[otmp.otyp]?.oc_material || 0) === GLASS
                       && game.objects[otmp.otyp]?.oc_name_known)) {
            if (uslinging())
                oammo = otmp;
            else if (ammo_and_launcher(otmp, uswapwep))
                altammo = otmp;
            else if (!omisc)
                omisc = otmp;
        } else if (otmp.oclass === GEM_CLASS) {
            ; // skip non-rock gems
        } else if (is_ammo(otmp)) {
            if (ammo_and_launcher(otmp, uwep))
                oammo = otmp;
            else if (ammo_and_launcher(otmp, uswapwep))
                altammo = otmp;
            else
                omisc = otmp;
        } else if (is_missile(otmp)) {
            omissile = otmp;
        } else if (otmp.oclass === WEAPON_CLASS && throwing_weapon(otmp)) {
            if ((game.objects[otmp.otyp]?.oc_skill || 0) === P_DAGGER && !omissile)
                omissile = otmp;
            else if (otmp.otyp === AKLYS)
                continue;
            else
                omisc = otmp;
        }
    }
    if (oammo) setuqwep(oammo);
    else if (omissile) setuqwep(omissile);
    else if (altammo) setuqwep(altammo);
    else if (omisc) setuqwep(omisc);
}
// ── find_launcher ──
// C ref: dothrow.c:447
function find_launcher(ammo) {
    if (!ammo) return null;
    let oX = null;
    for (let otmp = game.invent; otmp; otmp = otmp.nobj) {
        if (otmp.cursed && otmp.bknown) continue;
        if (ammo_and_launcher(ammo, otmp)) {
            if (otmp.bknown) return otmp;
            if (!oX) oX = otmp;
        }
    }
    return oX;
}
// ── dofire: the 'f' command entry point ──
// C ref: dothrow.c:468
export async function dofire() {
    const shotlimit_ref = { value: 0 };
    if (!await ok_to_throw(shotlimit_ref))
        return ECMD_OK;
    const uwep = get_uwep();
    const uwep_Throw_and_Return = (uwep && AutoReturn(uwep, uwep.owornmask || 0)
        && (uwep.oartifact !== ART_MJOLLNIR || ACURR(A_STR) >= STR19(25)));
    let skip_fireassist = false;
    let res = ECMD_OK;
    let obj = get_uquiver();
    if (uwep_Throw_and_Return && (!obj || is_ammo(obj))) {
        obj = uwep;
        skip_fireassist = true;
    } else if (!obj) {
        if (!game.flags?.autoquiver) {
            if (uwep && is_pole(uwep)) {
                return await use_pole(uwep, true);
            } else if (uwep && uwep.otyp === BULLWHIP) {
                return await use_whip(uwep);
            } else {
                await You('have no ammunition readied.');
            }
        } else {
            autoquiver();
            obj = get_uquiver();
            if (obj) {
                obj.owornmask &= ~W_QUIVER;
                await prinv('You ready:', obj, 0);
                obj.owornmask |= W_QUIVER;
            } else {
                await You('have nothing appropriate for your quiver.');
            }
        }
    }
    if (!obj) {
        game.in_doagain = 0;
        // doquiver_core would go here
        obj = get_uquiver();
    }
    if (get_uquiver() && is_ammo(get_uquiver()) && game.iflags?.fireassist
        && !skip_fireassist) {
        if (uwep && is_pole(uwep) && could_pole_mon()) {
            return await use_pole(uwep, true);
        }
        if (ammo_and_launcher(get_uquiver(), uwep)) {
            obj = get_uquiver();
        } else if (ammo_and_launcher(get_uquiver(), get_uswapwep())) {
            // C ref: dothrow.c:567-570 — queue swap+refire and exit current command.
            cmdq_add_ec(CQ_CANNED, doswapweapon);
            cmdq_add_ec(CQ_CANNED, dofire);
            return res;
        } else {
            const olauncher = find_launcher(get_uquiver());
            if (olauncher) {
                // C ref: dothrow.c:573-578 — optional push-weapon swap, then wield
                // launcher, then refire.
                if (uwep && !game.flags?.pushweapon) {
                    cmdq_add_ec(CQ_CANNED, doswapweapon);
                }
                cmdq_add_ec(CQ_CANNED, dowield);
                const invlet = olauncher.invlet;
                if (typeof invlet === 'string' && invlet.length > 0) {
                    cmdq_add_key(CQ_CANNED, invlet.charCodeAt(0));
                } else if (Number.isFinite(invlet)) {
                    cmdq_add_key(CQ_CANNED, invlet | 0);
                }
                cmdq_add_ec(CQ_CANNED, dofire);
                return res;
            }
        }
    }
    const altres = obj ? await throw_obj(obj, shotlimit_ref.value) : ECMD_CANCEL;
    return (res === ECMD_TIME) ? res : altres;
}
// ── endmultishot ──
// C ref: dothrow.c:589
export async function endmultishot(verbose) {
    const ms = game.m_shot;
    if (!ms) return;
    if (ms.i < ms.n) {
        if (verbose && !game.context?.mon_moving) {
            await You(`stop ${ms.s ? 'firing' : 'throwing'} after the ${ms.i}${ordin(ms.i)} ${ms.s ? 'shot' : 'toss'}.`);
        }
        ms.n = ms.i;
    }
}
// ── throw_obj: throw a specific object ──
// C ref: dothrow.c:87
async function throw_obj(obj, shotlimit) {
    const g = game;
    const u = g.u;
    let multishot;
    let res = ECMD_TIME;
    const save_osplit = { ...((g.context?.objsplit) || { parent_oid: 0, child_oid: 0 }) };
    // ask direction
    if (!(await getdir(null))) {
        res = ECMD_CANCEL;
        // unsplit_stack
        if (obj && obj !== get_uquiver()
            && (obj.o_id === save_osplit.parent_oid || obj.o_id === save_osplit.child_oid)) {
            if (g.context) g.context.objsplit = save_osplit;
            unsplitobj(obj);
        }
        return res;
    }
    // Gold special case
    if (obj.oclass === COIN_CLASS && obj !== get_uquiver()) {
        return await throw_gold(obj);
    }
    if (!(await canletgo(obj, 'throw'))) {
        res = ECMD_OK;
        return res;
    }
    if (obj.oartifact === ART_MJOLLNIR && obj !== get_uwep()) {
        await pline(`${The(xname(obj))} must be wielded before it can be thrown.`);
        res = ECMD_OK;
        return res;
    }
    if ((obj.oartifact === ART_MJOLLNIR && ACURR(A_STR) < STR19(25))
        || (obj.otyp === BOULDER && !throws_rocks(game.youmonst?.data))) {
        await pline("It's too heavy.");
        res = ECMD_TIME;
        return res;
    }
    if (!u.dx && !u.dy && !u.dz) {
        await You('cannot throw an object at yourself.');
        res = ECMD_OK;
        return res;
    }
    u_wipe_engr(2);
    if (welded(obj)) {
        await weldmsg(obj);
        res = ECMD_TIME;
        return res;
    }
    if (is_wet_towel(obj))
        dry_a_towel(obj, -1, false);
    // Multishot calculation
    multishot = 1;
    const skill = game.objects[obj.otyp]?.oc_skill || 0;
    const uwep = get_uwep();
    if (obj.quan > 1
        && (is_ammo(obj) ? matching_launcher(obj, uwep)
                         : obj.oclass === WEAPON_CLASS)
        && !(Confusion() || Stunned() || false /* Stunned */)) {
        const weakmultishot = (Role_if(PM_WIZARD) || Role_if(PM_CLERIC)
            || (Role_if(PM_HEALER) && skill !== P_KNIFE)
            || (Role_if(PM_TOURIST) && skill !== -P_DART)
            || Fumbling() || ACURR(A_DEX) <= 6);
        switch (P_SKILL(weapon_type(obj))) {
        case P_EXPERT:
            multishot++;
            /* FALLTHROUGH */
        case P_SKILLED:
            if (!weakmultishot)
                multishot++;
            break;
        default:
            break;
        }
        multishot += multishot_class_bonus(Role_switch(), obj, uwep);
        if (!weakmultishot) {
            switch (Race_switch()) {
            case PM_ELF:
                if (obj.otyp === ELVEN_ARROW && uwep && uwep.otyp === ELVEN_BOW)
                    multishot++;
                break;
            case PM_ORC:
                if (obj.otyp === ORCISH_ARROW && uwep && uwep.otyp === ORCISH_BOW)
                    multishot++;
                break;
            case PM_GNOME:
                if (skill === -P_CROSSBOW)
                    multishot++;
                break;
            default:
                break;
            }
            if (uwep && is_quest_artifact(uwep)
                && ammo_and_launcher(obj, uwep))
                ++multishot;
        }
        // Crossbow slow loading
        if (multishot > 1 && skill === -P_CROSSBOW
            && ammo_and_launcher(obj, uwep)
            && ACURRSTR() < (Race_if(PM_GNOME) ? 16 : 18))
            multishot = rnd(multishot);
        multishot = rnd(multishot);
        if (multishot > obj.quan)
            multishot = Math.trunc(obj.quan);
        if (shotlimit > 0 && multishot > shotlimit)
            multishot = shotlimit;
    }
    if (!g.m_shot) g.m_shot = { s: false, o: STRANGE_OBJECT, n: 0, i: 0 };
    g.m_shot.s = ammo_and_launcher(obj, uwep) ? true : false;
    if (multishot > 1 || shotlimit > 0) {
        await You(`${g.m_shot.s ? 'shoot' : 'throw'} ${multishot} ${multishot === 1 ? singular(obj, xname) : xname(obj)}.`);
    }
    const wep_mask = obj.owornmask || 0;
    let oldslot = null;
    g.m_shot.o = obj.otyp;
    g.m_shot.n = multishot;
    for (g.m_shot.i = 1; g.m_shot.i <= g.m_shot.n; g.m_shot.i++) {
        const twoweap = u.twoweap;
        let otmp;
        if (obj.quan > 1) {
            otmp = splitobj(obj, 1);
        } else {
            otmp = obj;
            if (otmp.owornmask)
                await remove_worn_item(otmp, false);
            oldslot = obj.nobj;
            obj = null;
        }
        freeinv(otmp);
        await throwit(otmp, wep_mask, twoweap, oldslot);
        await encumber_msg();
    }
    g.m_shot.n = g.m_shot.i = 0;
    g.m_shot.o = STRANGE_OBJECT;
    g.m_shot.s = false;
    // unsplit_stack
    if (obj && obj !== get_uquiver()
        && (obj.o_id === save_osplit.parent_oid || obj.o_id === save_osplit.child_oid)) {
        if (g.context) g.context.objsplit = save_osplit;
        unsplitobj(obj);
    }
    return res;
}
// stub for unsplitobj
// unsplitobj: imported from mkobj.js
// C ref: cmd.c:getdir — local copy matching zap.js pattern
// ── hitfloor: object hits floor ──
// C ref: dothrow.c:605
export async function hitfloor(obj, verbosely) {
    if (IS_SOFT(game.level?.locations?.[game.u.ux]?.[game.u.uy]?.typ)
        || game.u.uinwater || game.u.uswallow) {
        await dropy(obj);
        return;
    }
    if (IS_ALTAR(game.level?.locations?.[game.u.ux]?.[game.u.uy]?.typ)) {
        // doaltarobj(obj); // TODO
    } else if (verbosely) {
        const verb = (obj.otyp === WAN_STRIKING) ? 'strike' : 'hit';
        let surf = surface(game.u.ux, game.u.uy);
        const trap = t_at(game.u.ux, game.u.uy);
        if (trap?.tseen) {
            switch (trap.ttyp) {
            case TRAPDOOR_TRAP:
                surf = 'trap door';
                break;
            case HOLE_TRAP:
                surf = 'edge of the hole';
                break;
            case PIT_TRAP:
            case SPIKED_PIT_TRAP:
                surf = 'edge of the pit';
                break;
            default:
                break;
            }
        }
        await pline(`${Doname2(obj)} ${otense(obj, verb)} the ${surf}.`);
    }
    if (await hero_breaks(obj, game.u.ux, game.u.uy, BRK_FROM_INV))
        return;
    if (await ship_object(obj, game.u.ux, game.u.uy, false))
        return;
    await dropz(obj, true);
}
// ── walk_path: Bresenham line walk ──
// C ref: dothrow.c:656
export async function walk_path(src_cc, dest_cc, check_proc, arg) {
    let x, y, dx, dy, x_change, y_change, i, prev_x, prev_y;
    let keep_going = true;
    dx = dest_cc.x - src_cc.x;
    dy = dest_cc.y - src_cc.y;
    prev_x = x = src_cc.x;
    prev_y = y = src_cc.y;
    if (dx < 0) { x_change = -1; dx = -dx; }
    else { x_change = 1; }
    if (dy < 0) { y_change = -1; dy = -dy; }
    else { y_change = 1; }
    i = 0;
    let err = 0;
    if (dx < dy) {
        while (i++ < dy) {
            prev_x = x; prev_y = y;
            y += y_change;
            err += dx << 1;
            if (err > dy) { x += x_change; err -= dy << 1; }
            if (!(keep_going = await check_proc(arg, x, y)))
                break;
        }
    } else {
        while (i++ < dx) {
            prev_x = x; prev_y = y;
            x += x_change;
            err += dy << 1;
            if (err > dx) { y += y_change; err -= dx << 1; }
            if (!(keep_going = await check_proc(arg, x, y)))
                break;
        }
    }
    if (keep_going) return true;
    dest_cc.x = prev_x;
    dest_cc.y = prev_y;
    return false;
}
// ── hurtle_step: hero hurtle single step ──
// C ref: dothrow.c:773
export async function hurtle_step(arg, x, y) {
    const range_ref = arg;
    if (!isok(x, y)) {
        await You_feel('the spirits holding you back.');
        return false;
    }
    if (range_ref.value === 0) return false;
    if (IS_OBSTRUCTED(game.level?.locations?.[x]?.[y]?.typ || 0)
        || closed_door(x, y)) {
        const dmg = rnd(2 + range_ref.value);
        await pline('Ouch!');
        await losehp(Maybe_Half_Phys(dmg), 'bumping into a wall', KILLED_BY);
        wake_nearto(x, y, 10);
        return false;
    }
    const mon = m_at(x, y);
    if (mon) {
        const mnam = a_monnam(mon);
        await You(`bump into ${mnam}.`);
        wakeup(mon, false);
        wake_nearto(x, y, 10);
        return false;
    }
    // Move hero
    const ox = game.u.ux;
    const oy = game.u.uy;
    u_on_newpos(x, y);
    newsym(ox, oy);
    vision_recalc(1);
    await flush_screen(1);
    if (--range_ref.value < 0)
        range_ref.value = 0;
    if (range_ref.value !== 0)
        nh_delay_output();
    return true;
}
// ── hurtle_jump ──
// C ref: dothrow.c:742
export async function hurtle_jump(arg, x, y) {
    return await hurtle_step(arg, x, y);
}
// ── hurtle: hero knockback ──
// C ref: dothrow.c:1078
export async function hurtle(dx, dy, range, verbose) {
    if (Punished() && !carried(get_uball())) {
        await You_feel('a tug from the iron ball.');
        nomul(0);
        return;
    } else if (game.u.utrap) {
        const traptype = game.u.utraptype || 0;
        const trapname_str =
            (traptype === TT_WEB) ? 'web'
            : (traptype === TT_LAVA) ? hliquid('lava')
            : (traptype === TT_INFLOOR) ? surface(game.u.ux, game.u.uy)
            : (traptype === TT_BURIEDBALL) ? 'buried ball'
            : 'trap';
        await You(`are anchored by the ${trapname_str}.`);
        nomul(0);
        return;
    }
    dx = sgn(dx);
    dy = sgn(dy);
    if (!range || (!dx && !dy) || game.u.ustuck) return;
    nomul(-range);
    game.multi_reason = 'moving through the air';
    game.nomovemsg = '';
    if (verbose)
        await You(`${range > 1 ? 'hurtle' : 'float'} in the opposite direction.`);
    await endmultishot(true);
    const uc = { x: game.u.ux, y: game.u.uy };
    const cc = { x: game.u.ux + (dx * range), y: game.u.uy + (dy * range) };
    const range_ref = { value: range };
    await walk_path(uc, cc, async (arg, x, y) => await hurtle_step(range_ref, x, y), range_ref);
}
// ── will_hurtle ──
// C ref: dothrow.c:978
export function will_hurtle(mon, x, y) {
    if (!isok(x, y)) return false;
    if ((mon.data?.msize || 0) >= MZ_HUGE || mon === game.u?.ustuck || mon.mtrapped)
        return false;
    return goodpos(x, y, mon, MM_IGNOREWATER | MM_IGNORELAVA);
}
// ── mhurtle_step ──
// C ref: dothrow.c:993
async function mhurtle_step(arg, x, y) {
    const mon = arg;
    if (!isok(x, y)) return false;
    if (will_hurtle(mon, x, y) && m_in_out_region(mon, x, y)) {
        remove_monster(mon.mx, mon.my);
        newsym(mon.mx, mon.my);
        place_monster(mon, x, y);
        newsym(mon.mx, mon.my);
        await flush_screen(1);
        nh_delay_output();
        set_apparxy(mon);
        const res = await mintrap(mon, HURTLING);
        if (res === 2 /* Trap_Killed_Mon */ || res === 3 /* Trap_Caught_Mon */ || res === 4 /* Trap_Moved_Mon */)
            return false;
        return true;
    }
    const mtmp = m_at(x, y);
    if (mtmp && mtmp !== mon) {
        if (canseemon(mon) || canseemon(mtmp))
            await pline(`${Monnam(mon)} bumps into ${a_monnam(mtmp)}.`);
        wakeup(mtmp, !game.context?.mon_moving);
    } else if (x === game.u.ux && y === game.u.uy) {
        await pline(`${Some_Monnam(mon)} bumps into you.`);
        await stop_occupation();
    }
    return false;
}
// ── mhurtle: monster knockback ──
// C ref: dothrow.c:1131
export async function mhurtle(mon, dx, dy, range) {
    wakeup(mon, !game.context?.mon_moving);
    mon.movement = 0;
    mon.mstun = 1;
    if ((mon.data?.msize || 0) >= MZ_HUGE || mon === game.u?.ustuck || mon.mtrapped) {
        if (canseemon(mon))
            await pline(`${Monnam(mon)} doesn't budge!`);
        return;
    }
    dx = sgn(dx);
    dy = sgn(dy);
    if (!range || (!dx && !dy)) return;
    if (dx && dy && NODIAG(monsndx(mon.data))) return;
    if (mon.mundetected) {
        mon.mundetected = 0;
        newsym(mon.mx, mon.my);
    }
    if (M_AP_TYPE(mon))
        seemimic(mon);
    const mc = { x: mon.mx, y: mon.my };
    const cc = { x: mon.mx + (dx * range), y: mon.my + (dy * range) };
    await walk_path(mc, cc, mhurtle_step, mon);
    if (!DEADMONSTER(mon)) {
        if (t_at(mon.mx, mon.my))
            await mintrap(mon, FORCEBUNGLE);
        else
            await minliquid(mon);
    }
}
// ── check_shop_obj ──
// C ref: dothrow.c:1182
async function check_shop_obj(obj, x, y, broken) {
    const shkp = shop_keeper(game.u?.ushops?.[0] || '');
    if (!shkp) return;
    // Simplified shop accounting
    if (broken && is_unpaid(obj)) {
        await stolen_value(obj, game.u.ux, game.u.uy, !!shkp.mpeaceful, false);
        if (broken) obj.no_charge = 1;
    }
}
// ── harmless_missile ──
// C ref: dothrow.c:1221
export function harmless_missile(obj) {
    const otyp = obj.otyp;
    switch (otyp) {
    case SLING:
    case EUCALYPTUS_LEAF:
    case KELP_FROND:
    case SPRIG_OF_WOLFSBANE:
    case FORTUNE_COOKIE:
    case PANCAKE:
        return true;
    case RUBBER_HOSE:
    case BAG_OF_TRICKS:
        return (obj.spe < 1);
    case SACK:
    case OILSKIN_SACK:
    case BAG_OF_HOLDING:
        return !Has_contents(obj);
    default:
        if (obj.oclass === SCROLL_CLASS) return true;
        if ((game.objects[otyp]?.oc_material || 0) === CLOTH) return true;
        break;
    }
    return false;
}
// ── toss_up: throw upward ──
// C ref: dothrow.c:1256
async function toss_up(obj, hitsroof) {
    let action;
    const otyp = obj.otyp;
    const petrifier = ((otyp === EGG || otyp === CORPSE)
        && ismnum(obj.corpsenm)
        && touch_petrifies(mons?.[obj.corpsenm]));
    if (!has_ceiling(game.u.uz)) {
        action = 'flies up into';
    } else if (hitsroof) {
        if (breaktest(obj)) {
            await pline(`${Doname2(obj)} hits the ${ceiling(game.u.ux, game.u.uy)}.`);
            await breakmsg(obj, !Blind());
            if (!await breakobj(obj, game.u.ux, game.u.uy, true, true)) {
                await hitfloor(obj, false);
                game.thrownobj = null;
                return true;
            }
            return false;
        }
        action = 'hits';
    } else {
        action = 'almost hits';
    }
    await pline(`${Doname2(obj)} ${action} the ${ceiling(game.u.ux, game.u.uy)}, then falls back on top of your ${body_part(HEAD)}.`);
    // Object now hits you
    if (obj.oclass === POTION_CLASS) {
        await potionhit(game.youmonst, obj, POTHIT_HERO_THROW);
    } else if (breaktest(obj)) {
        let blindinc = 0;
        if ((otyp === CREAM_PIE || otyp === BLINDING_VENOM)
            && can_blnd(game.youmonst, game.youmonst, AT_WEAP, obj))
            blindinc = rnd(25);
        await breakmsg(obj, !Blind());
        if (await breakobj(obj, game.u.ux, game.u.uy, true, true))
            obj = null;
        switch (otyp) {
        case EGG:
            // petrification check omitted for brevity
            /* FALLTHROUGH */
        case CREAM_PIE:
        case BLINDING_VENOM:
            await pline(`You've got it all over your ${body_part(FACE)}!`);
            if (blindinc) {
                if (otyp === BLINDING_VENOM && !Blind())
                    await pline('It blinds you!');
                game.u.ucreamed = (game.u.ucreamed || 0) + blindinc;
                await make_blinded(BlindedTimeout() + blindinc, false);
            }
            break;
        default:
            break;
        }
        if (!obj) return false;
        await hitfloor(obj, false);
        game.thrownobj = null;
    } else if (harmless_missile(obj)) {
        await pline("It doesn't hurt.");
        await hitfloor(obj, false);
        game.thrownobj = null;
    } else {
        // Damage from non-breaking non-potion object
        let dmg = dmgval(obj, game.youmonst);
        if (!dmg) {
            dmg = Math.trunc(((obj.owt || 0) + (WT_TO_DMG - 1)) / WT_TO_DMG);
            dmg = (dmg <= 1) ? 1 : rnd(dmg);
            if (dmg > 6) dmg = 6;
        }
        const less_damage = hard_helmet(get_uarmh());
        if (dmg > 1 && less_damage) dmg = 1;
        if (dmg > 0) dmg += (game.u.udaminc || 0);
        if (dmg < 0) dmg = 0;
        dmg = Maybe_Half_Phys(dmg);
        if (get_uarmh()) {
            if (less_damage && dmg < (Upolyd() ? game.u.mh : game.u.uhp))
                await pline('Fortunately, you are wearing a hard helmet.');
            else if (game.flags?.verbose)
                await Your(`${helm_simple_name(get_uarmh())} does not protect you.`);
        }
        await hitfloor(obj, true);
        game.thrownobj = null;
        if (dmg > 0)
            await losehp(dmg, 'falling object', KILLED_BY_AN);
    }
    return true;
}
// ── throwing_weapon ──
// C ref: dothrow.c:1430
export function throwing_weapon(obj) {
    if (!obj) return false;
    if (is_missile(obj) || is_spear(obj)) return true;
    const od = game.objects[obj.otyp];
    if (!od) return false;
    // daggers and knife (not scalpel), i.e. blade but not sword, with pierce
    if (is_blade(obj) && !is_sword(obj)
        && ((od.oc_dir || 0) & 0x04)) // PIERCE = 0x04
        return true;
    if (obj.otyp === WAR_HAMMER || obj.otyp === AKLYS) return true;
    return false;
}
// ── sho_obj_return_to_u ──
// C ref: dothrow.c:1442
async function sho_obj_return_to_u(obj) {
    if ((game.u.dx || game.u.dy) && (game.bhitpos?.x !== game.u.ux || game.bhitpos?.y !== game.u.uy)) {
        // display return flight (tmp_at) — simplified
        let x = (game.bhitpos?.x || game.u.ux) - game.u.dx;
        let y = (game.bhitpos?.y || game.u.uy) - game.u.dy;
        await tmp_at(DISP_FLASH, tmp_obj_glyph(obj));
        while (isok(x, y) && (x !== game.u.ux || y !== game.u.uy)) {
            await tmp_at(x, y);
            nh_delay_output();
            x -= game.u.dx;
            y -= game.u.dy;
        }
        await tmp_at(DISP_END, 0);
    }
}
// ── throwit_return ──
// C ref: dothrow.c:1461
function throwit_return(clear_thrownobj) {
    game.iflags_returning_missile = null;
    if (clear_thrownobj)
        game.thrownobj = null;
}
// ── swallowit ──
// C ref: dothrow.c:1468
async function swallowit(obj) {
    if (obj !== get_uball()) {
        await mpickobj(game.u.ustuck, obj);
        throwit_return(false);
    } else {
        throwit_return(true);
    }
}
// ── throwit_mon_hit ──
// C ref: dothrow.c:1482
async function throwit_mon_hit(obj, mon) {
    if (mon) {
        if (mon.isshk && obj.where === 5 /* OBJ_MINVENT */ && obj.ocarry === mon)
            return true;
        snuff_candle(obj);
        game.notonhead = ((game.bhitpos?.x || 0) !== mon.mx || (game.bhitpos?.y || 0) !== mon.my);
        const obj_gone = await thitmonst(mon, obj);
        mon = m_at(game.bhitpos?.x || 0, game.bhitpos?.y || 0);
        if (mon && mon.isshk
            && (!inside_shop(game.u.ux, game.u.uy)))
            hot_pursuit(mon);
        if (obj_gone)
            game.thrownobj = null;
    }
    return false;
}
// ── throwit: main throw execution ──
// C ref: dothrow.c:1510
export async function throwit(obj, wep_mask, twoweap, oldslot) {
    const g = game;
    const u = g.u;
    let mon;
    let range, urange;
    const arw = autoreturn_weapon(obj);
    let crossbowing;
    let impaired = (Confusion() || Stunned() || Blind()
        || Hallucination() || Fumbling());
    const tethered_weapon = false; // simplified: no tethered weapon support yet
    game.notonhead = false;
    // Cursed/greased slip
    if ((obj.cursed || obj.greased) && (u.dx || u.dy) && !rn2(7)) {
        let slipok = true;
        if (ammo_and_launcher(obj, get_uwep())) {
            await pline(`${Tobjnam(obj, 'misfire')}!`);
        } else {
            if (obj.greased || throwing_weapon(obj))
                await pline(`${Tobjnam(obj, 'slip')} as you throw it!`);
            else
                slipok = false;
        }
        if (slipok) {
            u.dx = rn2(3) - 1;
            u.dy = rn2(3) - 1;
            if (!u.dx && !u.dy) u.dz = 1;
            impaired = true;
        }
    }
    // Low stamina
    if ((u.dx || u.dy || (u.dz < 1))
        && calc_capacity(obj.owt || 0) > SLT_ENCUMBER
        && (Upolyd() ? (u.mh < 5 && u.mh !== u.mhmax)
                     : (u.uhp < 10 && u.uhp !== u.uhpmax))
        && (obj.owt || 0) > ((Upolyd() ? u.mh : u.uhp) * 2)
        && !Is_airlevel(u.uz)) {
        await You(`have so little stamina, ${the(xname(obj))} drops from your grasp.`);
        exercise(A_CON, false);
        u.dx = u.dy = 0;
        u.dz = 1;
    }
    g.thrownobj = obj;
    g.thrownobj.how_lost = 1; // LOST_THROWN
    g.iflags_returning_missile = AutoReturn(obj, wep_mask) ? obj : null;
    if (u.uswallow) {
        mon = u.ustuck;
        if (!g.bhitpos) g.bhitpos = {};
        g.bhitpos.x = mon.mx;
        g.bhitpos.y = mon.my;
    } else if (u.dz) {
        if (u.dz < 0 && g.iflags_returning_missile && !impaired) {
            await pline(`${Tobjnam(obj, 'hit')} the ${ceiling(u.ux, u.uy)} and returns to your hand!`);
            obj = await return_throw_to_inv(obj, wep_mask, twoweap, oldslot);
        } else if (u.dz < 0) {
            await toss_up(obj, rn2(5) && !Underwater());
        } else if (u.dz > 0 && u.usteed && obj.oclass === POTION_CLASS && rn2(6)) {
            await potionhit(u.usteed, obj, POTHIT_HERO_THROW);
        } else {
            await hitfloor(obj, true);
        }
        throwit_return(true);
        return;
    } else if (obj.otyp === BOOMERANG && !Underwater()) {
        if (Is_airlevel(u.uz) || Levitation())
            await hurtle(-u.dx, -u.dy, 1, true);
        mon = await boomhit(obj, u.dx, u.dy);
        g.iflags_returning_missile = null;
        if (mon === game.youmonst) {
            exercise(A_DEX, true);
            obj = await return_throw_to_inv(obj, wep_mask, twoweap, oldslot);
            throwit_return(true);
            return;
        }
    } else {
        // Horizontal throw
        crossbowing = (ammo_and_launcher(obj, get_uwep())
            && weapon_type(get_uwep()) === P_CROSSBOW);
        urange = Math.trunc((crossbowing ? 18 : ACURRSTR()) / 2);
        if (obj.otyp === HEAVY_IRON_BALL)
            range = urange - Math.trunc((obj.owt || 0) / 100);
        else
            range = urange - Math.trunc((obj.owt || 0) / 40);
        if (obj === get_uball()) {
            if (u.ustuck) range = 1;
            else if (range >= 5) range = 5;
        }
        if (range < 1) range = 1;
        if (is_ammo(obj)) {
            if (ammo_and_launcher(obj, get_uwep())) {
                if (crossbowing)
                    range = BOLT_LIM;
                else
                    range++;
            } else if (obj.oclass !== GEM_CLASS) {
                range = Math.trunc(range / 2);
                // C ref: dothrow.c:1643-1646
                await pline(`You aren't wielding ${an(skill_name(weapon_type(obj)))}, so you throw your ${weapon_descr(obj)} by ${body_part(HAND)}.`);
            }
        }
        if (Is_airlevel(u.uz) || Levitation()) {
            urange -= range;
            if (urange < 1) urange = 1;
            range -= urange;
            if (range < 1) range = 1;
        }
        if (obj.otyp === BOULDER)
            range = 20;
        else if (obj.oartifact === ART_MJOLLNIR)
            range = Math.trunc((range + 1) / 2);
        if (Underwater()) range = 1;
        const pobj = { value: obj };
        mon = await bhit(u.dx, u.dy, range, THROWN_WEAPON, null, null, pobj);
        g.thrownobj = obj = pobj.value; // bhit may consume or replace projectile
        if (Is_airlevel(u.uz) || Levitation())
            await hurtle(-u.dx, -u.dy, urange, true);
        if (!obj) {
            throwit_return(false);
            return;
        }
    }
    if (await throwit_mon_hit(obj, mon)) {
        throwit_return(true);
        return;
    }
    if (!g.thrownobj) {
        // missile already handled
    } else if (u.uswallow && !g.iflags_returning_missile) {
        await swallowit(obj);
        return;
    } else {
        // Returning weapons
        if (g.iflags_returning_missile) {
            if (rn2(100)) {
                await sho_obj_return_to_u(obj);
                if (!impaired && rn2(100)) {
                    await pline(`${Tobjnam(obj, 'return')} to your hand!`);
                    obj = addinv(obj);
                    await encumber_msg();
                    if ((obj.owornmask || 0) & W_QUIVER)
                        setuqwep(null);
                    await setuwep(obj);
                    set_twoweap(twoweap);
                    if (cansee(g.bhitpos?.x || 0, g.bhitpos?.y || 0))
                        newsym(g.bhitpos.x, g.bhitpos.y);
                } else {
                    let dmg = rn2(2);
                    if (!dmg) {
                        await pline(Blind()
                            ? `${xname(obj)} lands ${Levitation() ? 'beneath' : 'at'} your ${makeplural(body_part(FOOT))}.`
                            : `${Tobjnam(obj, 'return')} back to you, landing ${Levitation() ? 'beneath' : 'at'} your ${makeplural(body_part(FOOT))}.`);
                    } else {
                        dmg += rnd(3);
                        await pline(Blind()
                            ? `${Tobjnam(obj, 'hit')} your ${body_part(ARM)}!`
                            : `${Tobjnam(obj, 'fly')} back toward you, hitting your ${body_part(ARM)}!`);
                        await losehp(Maybe_Half_Phys(dmg), killer_xname(obj), KILLED_BY);
                    }
                    if (u.uswallow) {
                        await swallowit(obj);
                        return;
                    }
                    if (!await ship_object(obj, u.ux, u.uy, false))
                        await dropy(obj);
                }
                throwit_return(true);
                return;
            } else {
                await pline(`${Tobjnam(obj, 'fail')} to return!`);
                if (u.uswallow) {
                    await swallowit(obj);
                    return;
                }
            }
        }
        // Object lands at bhitpos
        if ((!IS_SOFT(game.level?.locations?.[g.bhitpos?.x]?.[g.bhitpos?.y]?.typ || 0) && breaktest(obj))
            || obj.oclass === VENOM_CLASS) {
            await tmp_at(DISP_FLASH, tmp_obj_glyph(obj));
            await tmp_at(g.bhitpos?.x || 0, g.bhitpos?.y || 0);
            nh_delay_output();
            await tmp_at(DISP_END, 0);
            await breakmsg(obj, cansee(g.bhitpos?.x || 0, g.bhitpos?.y || 0));
            if (await breakobj(obj, g.bhitpos?.x || 0, g.bhitpos?.y || 0, true, true)) {
                throwit_return(true);
                return;
            }
        }
        if (await flooreffects(obj, g.bhitpos?.x || 0, g.bhitpos?.y || 0, 'fall')) {
            throwit_return(true);
            return;
        }
        obj_no_longer_held(obj);
        if (mon && mon.isshk && is_pick(obj)) {
            if (cansee(g.bhitpos?.x || 0, g.bhitpos?.y || 0))
                await pline(`${Monnam(mon)} snatches up ${the(xname(obj))}.`);
            if (game.u.ushops || obj.unpaid)
                await check_shop_obj(obj, g.bhitpos?.x || 0, g.bhitpos?.y || 0, false);
            await mpickobj(mon, obj);
            throwit_return(true);
            return;
        }
        snuff_candle(obj);
        if (!mon && await ship_object(obj, g.bhitpos?.x || 0, g.bhitpos?.y || 0, false)) {
            throwit_return(true);
            return;
        }
        g.thrownobj = null;
        place_object(obj, g.bhitpos?.x || 0, g.bhitpos?.y || 0);
        if (!IS_SOFT(game.level?.locations?.[g.bhitpos?.x]?.[g.bhitpos?.y]?.typ || 0)) {
            await container_impact_dmg(obj, u.ux, u.uy);
            impact_disturbs_zombies(obj, true);
        }
        if ((game.u.ushops || obj.unpaid) && obj !== get_uball())
            await check_shop_obj(obj, g.bhitpos?.x || 0, g.bhitpos?.y || 0, false);
        stackobj(obj);
        if (obj === get_uball())
            await drop_ball(g.bhitpos?.x || 0, g.bhitpos?.y || 0);
        if (cansee(g.bhitpos?.x || 0, g.bhitpos?.y || 0))
            newsym(g.bhitpos.x, g.bhitpos.y);
        if (obj_sheds_light(obj))
            game.vision_full_recalc = 1;
    }
    throwit_return(false);
}
// ── return_throw_to_inv ──
// C ref: dothrow.c:1855
async function return_throw_to_inv(obj, wep_mask, twoweap, oldslot) {
    // Simplified: just add back to inventory
    obj = addinv(obj);
    if ((obj.owornmask & W_QUIVER) !== 0
        && ((obj.owornmask | wep_mask) & (W_WEP | W_SWAPWEP)) !== 0)
        setuqwep(null);
    if ((wep_mask & W_WEP) && !get_uwep())
        await setuwep(obj);
    else if ((wep_mask & W_SWAPWEP) && !get_uswapwep())
        setuswapwep(obj);
    else if ((wep_mask & W_QUIVER) && !get_uquiver())
        setuqwep(obj);
    if (twoweap && !game.u.twoweap)
        set_twoweap(true);
    await encumber_msg();
    return obj;
}
// ── omon_adj: adjust hit chance based on monster ──
// C ref: dothrow.c:1913
export function omon_adj(mon, obj, mon_notices) {
    let tmp = 0;
    tmp += ((mon.data?.msize || MZ_MEDIUM) - MZ_MEDIUM);
    if (mon.msleeping) tmp += 2;
    if (!mon.mcanmove || !mon.data?.mmove) {
        tmp += 4;
        if (mon_notices && mon.data?.mmove && !rn2(10)) {
            mon.mcanmove = 1;
            mon.mfrozen = 0;
        }
    }
    switch (obj.otyp) {
    case HEAVY_IRON_BALL:
        if (obj !== get_uball()) tmp += 2;
        break;
    case BOULDER:
        tmp += 6;
        break;
    default:
        if (obj.oclass === WEAPON_CLASS || is_weptool(obj)
            || obj.oclass === GEM_CLASS)
            tmp += hitval(obj, mon);
        break;
    }
    return tmp;
}
// ── tmiss: thrown object misses ──
// C ref: dothrow.c:1951
async function tmiss(obj, mon, maybe_wakeup) {
    const missile = xname(obj); // simplified from mshot_xname
    if (!canseemon(mon) || (M_AP_TYPE(mon) && M_AP_TYPE(mon) !== M_AP_MONSTER))
        await pline(`${The(missile)} ${otense(obj, 'miss')}.`);
    else
        await miss(missile, mon);
    if (maybe_wakeup && !rn2(3))
        wakeup(mon, true);
}
// ── should_mulch_missile ──
// C ref: dothrow.c:1977
export function should_mulch_missile(obj) {
    if (!obj || !(is_ammo(obj) || is_missile(obj))
        || obj.otyp === BOOMERANG
        || game.objects[obj.otyp]?.oc_magic)
        return false;
    let chance = 3 + greatest_erosion(obj) - (obj.spe || 0);
    let broken = chance > 1 ? rn2(chance) : !rn2(4);
    if (obj.blessed && (game.context?.mon_moving ? !rn2(3) : !rnl(4)))
        broken = false;
    if (((obj.oclass === GEM_CLASS && game.objects[obj.otyp]?.oc_tough)
         || obj.otyp === FLINT)
        && !rn2(2))
        broken = false;
    return broken;
}
// ── thitmonst: thrown object hits a monster ──
// C ref: dothrow.c:2011
export async function thitmonst(mon, obj) {
    let tmp;
    let disttmp;
    const otyp = obj.otyp;
    let hmode;
    const guaranteed_hit = engulfing_u(mon);
    let dieroll;
    const uwep = get_uwep();
    const uarmg = get_uarmg();
    hmode = (obj === uwep) ? HMON_APPLIED
        : (obj === game.kickedobj) ? HMON_KICKED
        : HMON_THROWN;
    // Base to-hit
    tmp = -1 + (getLuck()) + (game.u.uhitinc || 0)
          + maybe_polyd(game.youmonst?.data?.mlevel || 0, game.u.ulevel || 0);
    tmp += find_mac(mon);
    if (ACURR(A_DEX) < 4) tmp -= 3;
    else if (ACURR(A_DEX) < 6) tmp -= 2;
    else if (ACURR(A_DEX) < 8) tmp -= 1;
    else if (ACURR(A_DEX) >= 14) tmp += (ACURR(A_DEX) - 14);
    disttmp = 3 - distmin(game.u.ux, game.u.uy, mon.mx, mon.my);
    if (disttmp < -4) disttmp = -4;
    tmp += disttmp;
    // Gloves hindrance for bows
    if (uarmg && uwep && (game.objects[uwep.otyp]?.oc_skill || 0) === P_BOW) {
        switch (uarmg.otyp) {
        case GAUNTLETS_OF_POWER: tmp -= 2; break;
        case GAUNTLETS_OF_FUMBLING: tmp -= 3; break;
        case LEATHER_GLOVES:
        case GAUNTLETS_OF_DEXTERITY: break;
        default: break;
        }
    }
    tmp += omon_adj(mon, obj, true);
    if (guaranteed_hit) tmp += 1000;
    // Gem + unicorn special handling
    if (obj.oclass === GEM_CLASS && is_unicorn(mon.data)
        && (game.objects[obj.otyp]?.oc_material || 0) !== MINERAL && !uslinging()) {
        if (helpless(mon)) {
            await tmiss(obj, mon, false);
            return 0;
        } else if (mon.mtame) {
            await pline(`${Monnam(mon)} catches and drops ${the(xname(obj))}.`);
            return 0;
        } else {
            await pline(`${Monnam(mon)} catches ${the(xname(obj))}.`);
            return await gem_accept(mon, obj);
        }
    }
    dieroll = rnd(20);
    if (obj.oclass === WEAPON_CLASS || is_weptool(obj)
        || obj.oclass === GEM_CLASS) {
        if (hmode === HMON_KICKED) {
            tmp -= (is_ammo(obj) ? 5 : 3);
        } else if (is_ammo(obj)) {
            if (!ammo_and_launcher(obj, uwep)) {
                tmp -= 4;
            } else {
                tmp += (uwep.spe || 0) - greatest_erosion(uwep);
                tmp += weapon_hit_bonus(uwep);
            }
        } else {
            if (otyp === BOOMERANG) tmp += 4;
            else if (throwing_weapon(obj)) tmp += 2;
            else if (obj === game.thrownobj) tmp -= 2;
            tmp += weapon_hit_bonus(obj);
        }
        if (tmp >= dieroll) {
            const wasthrown = (game.thrownobj !== null);
            const chopper = is_axe(obj);
            if (hmode === HMON_APPLIED)
                game.u.uconduct = (game.u.uconduct || {});
                // u.uconduct.weaphit++; // TODO
            if (await hmon(mon, obj, hmode, dieroll)) {
                if (mon.wormno)
                    await cutworm(mon, game.bhitpos?.x || 0, game.bhitpos?.y || 0, chopper);
            }
            exercise(A_DEX, true);
            if (wasthrown && !game.thrownobj)
                return 1;
            if (should_mulch_missile(obj)) {
                if (game.u.ushops || obj.unpaid)
                    await check_shop_obj(obj, game.bhitpos?.x || 0, game.bhitpos?.y || 0, true);
                obfree(obj, null);
                return 1;
            }
            await passive_obj(mon, obj, null);
        } else {
            await tmiss(obj, mon, true);
            if (hmode === HMON_APPLIED)
                wakeup(mon, true);
        }
    } else if (otyp === HEAVY_IRON_BALL) {
        exercise(A_STR, true);
        if (tmp >= dieroll) {
            const was_swallowed = guaranteed_hit;
            exercise(A_DEX, true);
            if (!(await hmon(mon, obj, hmode, dieroll))) {
                if (was_swallowed && !game.u.uswallow && obj === get_uball())
                    return 1;
            }
        } else {
            await tmiss(obj, mon, true);
        }
    } else if (otyp === BOULDER) {
        exercise(A_STR, true);
        if (tmp >= dieroll) {
            exercise(A_DEX, true);
            await hmon(mon, obj, hmode, dieroll);
        } else {
            await tmiss(obj, mon, true);
        }
    } else if ((otyp === EGG || otyp === CREAM_PIE || otyp === BLINDING_VENOM
                || otyp === ACID_VENOM)
               && (guaranteed_hit || ACURR(A_DEX) > rnd(25))) {
        await hmon(mon, obj, hmode, dieroll);
        return 1;
    } else if (obj.oclass === POTION_CLASS
               && (guaranteed_hit || ACURR(A_DEX) > rnd(25))) {
        await potionhit(mon, obj, POTHIT_HERO_THROW);
        return 1;
    } else if (befriend_with_obj(mon.data, obj)
               || (mon.mtame && dogfood(mon, obj) <= 1 /* ACCFOOD */)) {
        if (await tamedog(mon, obj, true)) {
            return 1;
        } else {
            await tmiss(obj, mon, false);
            mon.msleeping = 0;
            mon.mstrategy = (mon.mstrategy || 0) & ~0xFF; // STRAT_WAITMASK
        }
    } else if (guaranteed_hit) {
        wakeup(mon, true);
        await pline(`${Tobjnam(obj, 'vanish')} into ${mon_nam(mon)}.`);
    } else {
        await tmiss(obj, mon, true);
    }
    return 0;
}
// ── gem_accept: gem hits unicorn ──
// C ref: dothrow.c:2309
async function gem_accept(mon, obj) {
    const nogood = ' is not interested in your junk.';
    const acceptgift = ' accepts your gift.';
    const maybeluck = ' hesitatingly';
    const noluck = ' graciously';
    const addluck_str = ' gratefully';
    let buf = Monnam(mon);
    const is_buddy = sgn(mon.data?.maligntyp || 0) === sgn(game.u.ualign?.type || 0);
    const is_gem = (game.objects[obj.otyp]?.oc_material || 0) === GEMSTONE;
    let ret = 0;
    mon.mpeaceful = 1;
    mon.mavenge = 0;
    if (obj.dknown && game.objects[obj.otyp]?.oc_name_known) {
        if (is_gem) {
            if (is_buddy) {
                buf += addluck_str;
                change_luck(5);
            } else {
                buf += maybeluck;
                change_luck(rn2(7) - 3);
            }
        } else {
            buf += nogood;
            if (!Blind()) await pline(buf);
            if (!tele_restrict(mon)) await rloc(mon, RLOC_MSG);
            return ret;
        }
    } else if (obj.oname || game.objects[obj.otyp]?.oc_uname) {
        if (is_gem) {
            if (is_buddy) {
                buf += addluck_str;
                change_luck(2);
            } else {
                buf += maybeluck;
                change_luck(rn2(3) - 1);
            }
        } else {
            buf += nogood;
            if (!Blind()) await pline(buf);
            if (!tele_restrict(mon)) await rloc(mon, RLOC_MSG);
            return ret;
        }
    } else {
        if (is_gem) {
            if (is_buddy) {
                buf += addluck_str;
                change_luck(1);
            } else {
                buf += maybeluck;
                change_luck(rn2(3) - 1);
            }
        } else {
            buf += noluck;
        }
    }
    buf += acceptgift;
    if (game.u.ushops || obj.unpaid)
        await check_shop_obj(obj, mon.mx, mon.my, true);
    await mpickobj(mon, obj);
    ret = 1;
    if (!Blind()) await pline(buf);
    if (!tele_restrict(mon)) await rloc(mon, RLOC_MSG);
    return ret;
}
// ── breaktest ──
// C ref: dothrow.c:2582
export function breaktest(obj) {
    let nonbreakchance = 1;
    if (obj.oclass === ARMOR_CLASS && (game.objects[obj.otyp]?.oc_material || 0) === GLASS)
        nonbreakchance = 90;
    if (obj_resists(obj, nonbreakchance, 99))
        return false;
    if ((game.objects[obj.otyp]?.oc_material || 0) === GLASS && !obj.oartifact
        && obj.oclass !== GEM_CLASS)
        return true;
    switch (obj.oclass === POTION_CLASS ? POT_WATER : obj.otyp) {
    case EXPENSIVE_CAMERA:
    case POT_WATER:
    case EGG:
    case CREAM_PIE:
    case MELON:
    case ACID_VENOM:
    case BLINDING_VENOM:
        return true;
    default:
        return false;
    }
}
// ── breakmsg ──
// C ref: dothrow.c:2612
async function breakmsg(obj, in_view) {
    if (is_crackable(obj)) return;
    let to_pieces = '';
    switch (obj.oclass === POTION_CLASS ? POT_WATER : obj.otyp) {
    default:
        /* FALLTHROUGH */
    case LENSES:
    case MIRROR:
    case CRYSTAL_BALL:
    case EXPENSIVE_CAMERA:
        to_pieces = ' into a thousand pieces';
        /* FALLTHROUGH */
    case POT_WATER:
        if (!in_view)
            await You_hear('something shatter!');
        else
            await pline(`${Doname2(obj)} shatter${obj.quan === 1 ? 's' : ''}${to_pieces}!`);
        break;
    case EGG:
    case MELON:
        await pline('Splat!');
        break;
    case CREAM_PIE:
        if (in_view) await pline('What a mess!');
        break;
    case ACID_VENOM:
    case BLINDING_VENOM:
        await pline('Splash!');
        break;
    }
}
// ── release_camera_demon ──
// C ref: dothrow.c:2458
export function release_camera_demon(obj, x, y) {
    if (!rn2(3)) {
        // makemon would go here
        // simplified: just the RNG consumption
        const montype = rn2(3); // PM_HOMUNCULUS or PM_IMP
    }
}
// ── breakobj ──
// C ref: dothrow.c:2480
export async function breakobj(obj, x, y, hero_caused, from_invent) {
    let fracture = false;
    let explosion = false;
    if (is_crackable(obj))
        return (await erode_obj(obj, armor_simple_name(obj), ERODE_CRACK,
                          EF_DESTROY | EF_VERBOSE) === ER_DESTROYED);
    switch (obj.oclass === POTION_CLASS ? POT_WATER : obj.otyp) {
    case MIRROR:
        if (hero_caused) change_luck(-2);
        break;
    case POT_WATER:
        obj.in_use = 1;
        if (obj.otyp === POT_OIL && obj.lamplit) {
            await explode_oil(obj, x, y);
        } else if (next2u(x, y)) {
            if (!breathless(game.youmonst?.data) || haseyes(game.youmonst?.data)) {
                if (obj.otyp !== POT_WATER && !Half_gas_damage()) {
                    if (!breathless(game.youmonst?.data)) {
                        await You('smell a peculiar odor...');
                    }
                }
                await potionbreathe(obj);
            }
        }
        break;
    case EXPENSIVE_CAMERA:
        release_camera_demon(obj, x, y);
        break;
    case EGG:
        if (hero_caused && obj.spe && ismnum(obj.corpsenm))
            change_luck(-Math.min(obj.quan || 1, 5));
        // pyrolisk explosion check omitted
        break;
    case BOULDER:
    case 382: // STATUE
        fracture = true;
        break;
    default:
        break;
    }
    if (hero_caused) {
        if (from_invent || obj.unpaid) {
            if (game.u.ushops || obj.unpaid)
                await check_shop_obj(obj, x, y, true);
        }
    }
    if (!fracture)
        delobj(obj);
    if (explosion)
        await explode(x, y, -11, c_d(3, 6), 0, EXPL_FIERY);
    return 1;
}
// ── hero_breaks ──
// C ref: dothrow.c:2417
export async function hero_breaks(obj, x, y, breakflags) {
    const from_invent = (breakflags & BRK_FROM_INV) !== 0;
    const in_view = Blind() ? false : (from_invent || cansee(x, y));
    let brk = breakflags & BRK_KNOWN_OUTCOME;
    if (!brk)
        brk = breaktest(obj) ? BRK_KNOWN2BREAK : BRK_KNOWN2NOTBREAK;
    if (brk === BRK_KNOWN2NOTBREAK) return 0;
    await breakmsg(obj, in_view);
    return await breakobj(obj, x, y, true, from_invent);
}
// ── breaks ──
// C ref: dothrow.c:2444
export async function breaks(obj, x, y) {
    const in_view = Blind() ? false : cansee(x, y);
    if (!breaktest(obj)) return 0;
    await breakmsg(obj, in_view);
    return await breakobj(obj, x, y, false, false);
}
// ── throw_gold ──
// C ref: dothrow.c:2656
async function throw_gold(obj) {
    const u = game.u;
    if (!u.dx && !u.dy && !u.dz) {
        await You('cannot throw gold at yourself.');
        return ECMD_CANCEL;
    }
    freeinv(obj);
    if (u.uswallow) {
        await pline_The(`gold disappears into ${mon_nam(u.ustuck)}.`);
        await add_to_minv(u.ustuck, obj);
        return ECMD_TIME;
    }
    if (!game.bhitpos) game.bhitpos = {};
    if (u.dz) {
        if (u.dz < 0 && !Is_airlevel(u.uz) && !Underwater() && !Is_waterlevel(u.uz)) {
            await pline_The(`gold hits the ${ceiling(u.ux, u.uy)}, then falls back on top of your ${body_part(HEAD)}.`);
            if (get_uarmh())
                await pline(`Fortunately, you are wearing ${an(helm_simple_name(get_uarmh()))}!`);
        }
        game.bhitpos.x = u.ux;
        game.bhitpos.y = u.uy;
    } else {
        const range = Math.trunc(ACURRSTR() / 2 - (obj.owt || 0) / 40);
        const odx = u.ux + u.dx;
        const ody = u.uy + u.dy;
        if (!isok(odx, ody) || !ZAP_POS(game.level?.locations?.[odx]?.[ody]?.typ || 0)
            || closed_door(odx, ody)) {
            game.bhitpos.x = u.ux;
            game.bhitpos.y = u.uy;
        } else {
            const pobj = { value: obj };
            const mon = await bhit(u.dx, u.dy, range, THROWN_WEAPON, null, null, pobj);
            obj = pobj.value;
            if (!obj) return ECMD_TIME;
            if (mon) {
                // ghitm check — simplified
                return ECMD_TIME;
            } else {
                if (await ship_object(obj, game.bhitpos.x, game.bhitpos.y, false))
                    return ECMD_TIME;
            }
        }
    }
    if (await flooreffects(obj, game.bhitpos.x, game.bhitpos.y, 'fall'))
        return ECMD_TIME;
    if (u.dz > 0)
        await pline_The(`gold hits the ${surface(game.bhitpos.x, game.bhitpos.y)}.`);
    place_object(obj, game.bhitpos.x, game.bhitpos.y);
    stackobj(obj);
    newsym(game.bhitpos.x, game.bhitpos.y);
    return ECMD_TIME;
}
// ── Re-export ohitmon and m_throw from mthrowu.js ──
// These were previously exported from this file but live in mthrowu.js
/*dothrow.c*/