All files / js dig.js

42.4% Statements 796/1877
28.71% Branches 87/303
42.59% Functions 23/54
42.4% Lines 796/1877

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 187773x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                                                   73x 73x 73x 73x 73x 13x 13x 13x 13x 73x 73x 73x 21x 21x 21x 21x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x   73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x   73x 73x     73x 73x   73x 2x 73x 73x         73x 73x 73x 73x 73x 73x 73x 73x   73x 73x 73x 73x 73x   73x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 24x 24x 24x 24x 73x 73x                   73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 59x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                                                                                                                                                                                       73x 33x 33x 33x 33x         33x 33x 33x 33x 33x 33x 33x 32x 32x 32x 33x 33x 73x       73x 10x 10x             10x   10x 10x 10x   10x   10x   10x 10x   10x   10x                 10x   10x 10x     10x 10x 73x                                                                         73x 73x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x     16x 8x 8x       8x 8x 8x       8x 8x       8x 16x                                                   16x 16x 16x 16x 8x 8x               8x 8x 6x 8x 2x           2x                             2x                 8x       2x 2x 2x 2x 2x 2x 8x 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 8x 7x 7x 7x 7x 7x       7x       7x 1x 1x 1x 1x 7x 7x 16x 2x 2x 2x       2x   2x 2x       2x 2x 2x   2x 73x 613x 613x 613x 613x 73x 2x 2x 2x 2x 6x 18x 18x 18x 18x 18x 18x 18x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 73x 2x 2x 2x 2x 2x 2x 2x 2x 2x           2x 2x 2x       2x 2x 2x                 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x               2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x               2x                                                                                                     2x 73x                                                     73x 2x 2x 2x 2x 2x 2x         2x 2x 2x 2x 2x 2x 2x 2x 2x   2x       2x     2x 2x                   2x                       2x         2x                       2x   2x   2x 2x 2x 2x               2x 2x 2x       2x 2x 2x 2x     2x 2x 2x 2x     2x                                                                                                               73x 5x 5x 5x 5x 2x 2x 2x 2x 2x     3x 5x 5x       3x 3x 3x 5x 30x 30x 30x   30x 24x 24x 24x 24x 17x 17x 30x 6x 6x 10x 10x 3x 3x 3x 2x 5x 73x 3x 3x 3x 3x 3x 3x 3x   3x   3x         3x                 3x 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 3x   2x   2x   2x 2x       2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x     2x 2x 2x 3x 3x             73x 2x 2x 2x 2x                                         2x 73x 17x 17x 17x 17x 17x 17x                                         17x             17x 16x 16x 8x           1x 1x 1x 1x 1x 1x 1x 1x     1x 1x     1x 1x 1x 1x 8x                     1x 1x 1x 1x 17x 73x                                               73x 2x 2x 2x 2x 2x 2x 2x 2x                         2x                                               2x 2x 2x 2x 2x 2x 2x 2x       2x 2x 2x 8x 8x 8x 8x 8x                                                           8x                           8x                                                                 8x 5x 5x 2x       2x 2x     2x 2x 2x 2x 2x 2x       2x 2x 2x 2x 2x 4x 4x 7x 7x 7x 2x 2x               2x 2x 2x 73x                                                                                                                 73x                                                   73x                     73x                       73x 59x 59x 59x 59x         59x 59x 59x 59x 59x 59x 59x 59x 59x         59x 58x 59x 1x 1x 1x 1x 59x 59x 59x 73x                                       73x                                             73x 14x 14x 14x         14x 14x 14x 73x 14x 14x 14x 14x 14x 14x 7x 7x 7x               7x     7x     14x 14x 7x 7x 7x     7x 7x     14x
// dig.js — Port of dig.c
// Digging functions: pick-axe usage, wand of digging, monster tunneling,
// hole creation, grave robbing, buried objects, town watchman interactions.
//
// Ported functions:
//   rm_waslit()            — check if area was lit
//   mkcavepos()            — change level topology for cave effect
//   mkcavearea()           — create/collapse cave around player
//   pick_can_reach()       — can pick reach target in/out of pit?
//   dig_typ()              — classify what you're digging into
//   is_digging()           — is current occupation digging?
//   dig_check()            — check if digging is allowed at location
//   digcheck_fail_message() — print failure message for dig_check
//   dig()                  — occupation callback for digging
//   furniture_handled()    — handle special furniture during digging
//   holetime()             — estimate time to finish hole
//   fillholetyp()          — determine liquid type for hole filling
//   digactualhole()        — create pit or hole at location
//   liquid_flow()          — fill location with liquid
//   dighole()              — main hole-digging routine
//   dig_up_grave()         — rob a grave
//   use_pick_axe()         — apply pick-axe command (direction query)
//   use_pick_axe2()        — apply pick-axe (uses u.dx/u.dy/u.dz)
//   watchman_canseeu()     — can a watchman see the hero?
//   watch_dig()            — watchman reaction to digging
//   mdig_tunnel()          — monster tunnels through terrain
//   draft_message()        — "you feel a draft" message
//   zap_dig()              — wand/spell of digging effect
//   adj_pit_checks()       — check surface above adjacent pit location
//   pit_flow()             — fill conjoined pits with liquid
//   buried_ball()          — find buried iron ball
//   buried_ball_to_punishment() — convert buried ball to punishment
//   buried_ball_to_freedom()    — free buried ball
//   bury_an_obj()          — bury a single object
//   bury_objs()            — bury all objects at location
//   unearth_objs()         — unearth buried objects
//   rot_organic()          — buried organic material rots away
//   await rot_corpse()           — buried corpse rots away
import { game } from './gstate.js';
import { rn2, rnd, rn1, rnl, c_d } from './rng.js';
import { pline, You, Your, You_feel, You_hear, You_cant, pline_The, verbalize } from './pline.js';
import { impossible } from './pline.js';
import { Blind, Confusion, Deaf, Flying, Fumbling, Hallucination, Inhell, Invocation_lev, Is_airlevel, Is_waterlevel, Levitation, Luck, Maybe_Half_Phys, Race_if, Role_if, Stunned, Teleport_control, Teleportation, Underwater, Upolyd } from './macros.js';
import { Monnam, hideunder, maybe_unhide_at, minliquid, mon_nam, stop_occupation, uhis, update_inventory, wake_nearby, wake_nearto } from './mon.js';
import { amorphous, can_teleport, digests, grounded, hides_under, is_axe, is_floater, is_flyer, is_pick, is_watch, is_whirly, m_canseeu, needspick, noncorporeal, passes_walls, tunnels, unique_corpstat } from './mondata.js';
import { b_trapped, cnv_trap_obj, delfloortrap, deltrap, dotrap, feeltrap, fire_damage, fire_damage_chain, maketrap, mintrap, reset_utrap, seetrap, set_utrap, trapname, uescaped_shaft, undestroyable_trap, uteetering_at_seen_pit, water_damage_chain } from './trap.js';
import { pickup } from './pickup.js';
import { mk_tt_object } from './mkroom.js';
import { levl, m_at, t_at, obj_at } from './map_access.js';
import { ACURR, adjalign, exercise } from './attrib.js';
import { block_point, canseemon, canspotmon, cmap_to_glyph, delay_output, does_block, feel_newsym, flush_screen, newsym, recalc_block_point, setBotl, tmp_at, unblock_point } from './display.js';
import {
    mons,
    PM_DWARF, PM_ELF, PM_ARCHEOLOGIST, PM_SAMURAI, PM_RANGER,
    PM_EARTH_ELEMENTAL, PM_XORN,
    S_ZOMBIE, S_MUMMY,
    MZ_HUGE,
} from './monsters.js';
import { APPLE, BANANA, BEARTRAP, BOULDER, COIN_CLASS, CORPSE, EUCALYPTUS_LEAF, greatest_erosion, HEAVY_IRON_BALL, is_organic, LAND_MINE, LEASH, ORANGE, PEAR, POT_OIL, POTION_CLASS, ROCK, STATUE, TOOL_CLASS, WEAPON_CLASS } from './objects.js';
import { A_CHA, A_CON, A_DEX, A_INT, A_LAWFUL, A_NONE, A_STR, A_WIS, ALTAR, AM_MASK, AM_SANCTUM, Amask2align, BEAR_TRAP, COLNO, CORR, CQ_CANNED, CXN_NO_PFX, D_BROKEN, D_CLOSED, D_LOCKED, D_NODOOR, D_TRAPPED, DB_LAVA, DB_MOAT, DB_UNDER, DBWALL, DIGCHECK_FAIL_AIRLEVEL, DIGCHECK_FAIL_ALTAR, DIGCHECK_FAIL_BOULDER, DIGCHECK_FAIL_CANTDIG, DIGCHECK_FAIL_OBJ_POOL_OR_TRAP, DIGCHECK_FAIL_ONLADDER, DIGCHECK_FAIL_ONSTAIRS, DIGCHECK_FAIL_THRONE, DIGCHECK_FAIL_TOOHARD, DIGCHECK_FAIL_UNDESTROYABLETRAP, DIGCHECK_FAIL_WATERLEVEL, DIGCHECK_FAILED, DIGCHECK_PASSED, DIGCHECK_PASSED_DESTROY_TRAP, DIGCHECK_PASSED_PITONLY, DIGTYP_BOULDER, DIGTYP_DOOR, DIGTYP_ROCK, DIGTYP_STATUE, DIGTYP_TREE, DIGTYP_UNDIGGABLE, DIR_180, DIR_ERR, DISP_BEAM, DISP_END, DOOR, DRAWBRIDGE_DOWN, DRAWBRIDGE_UP, ECMD_CANCEL, ECMD_OK, ECMD_TIME, EXPL_MAGICAL, FOOT, FORCEBUNGLE, FORCETRAP, FOUNTAIN, GRAVE, Has_contents, HEAD, HOLE, IRONBARS, IS_AIR, IS_ALTAR, Is_botlevel, IS_DOOR, Is_earthlevel, IS_FOUNTAIN, IS_FURNITURE, IS_GRAVE, is_hole, is_magical_trap, IS_OBSTRUCTED, is_pit, IS_ROOM, IS_SINK, Is_stronghold, IS_STWALL, IS_THRONE, IS_TREE, IS_WALL, IS_WATERWALL, isok, KILLED_BY, KILLED_BY_AN, LANDMINE, LAVAPOOL, LAVAWALL, MM_NOMSG, MOAT, MV_WALK, N_DIRS, N_DIRS_Z, NO_PART, NO_TRAP, OBJ_AT, OBJ_FLOOR, OBJ_INVENT, OBJ_MIGRATING, OBJ_MINVENT, P_AXE, P_PICK_AXE, PIT, POOL, RIGHT_SIDE, ROOM, ROT_ORGANIC, ROWNO, SCORR, SDOOR, SHOP_DOOR_COST, SHOP_PIT_COST, SHOP_WALL_COST, SHOPBASE, SINK, SPIKED_PIT, STONE, TAINT_AGE, TEMPLE, THRONE, TIMER_OBJECT, TRAP_EXPLODE, TRAPDOOR, TT_BURIEDBALL, TT_INFLOOR, TT_PIT, TT_WEB, u_at, VAULT, W_NONDIGGABLE, WATER, WEB } from './const.js';
import { S_digbeam } from './symbols.js';
import { del_engr_at, u_wipe_engr } from './engrave.js';
import { makemon, mkclass } from './makemon.js';
import { mksobj_at, obfree, obj_extract_self, place_object, sobj_at } from './mkobj.js';
import { The, Yobjnam2, an, doname, simpleonames, the, xname, yname, yobjnam } from './objnam.js';
import { hliquid } from './do_name.js';
import { MON_WEP, Strcat, Strcpy, bimanual, get_iter_mons, nh_delay_output, obj_to_any, on_level, s_suffix, sgn, surface } from './hacklib.js';
import { cansee } from './vision.js';
import { abon } from './weapon.js';
import { On_stairs, On_ladder, stairway_at } from './stairs.js';
import { altarmask_at, altar_wrath, desecrate_altar } from './pray.js';
import { confdir, getdir, nomul, set_occupation } from './cmd.js';
import { count_wsegs } from './worm.js';
import { goto_level } from './allmain.js';
import { assign_level, get_level, ledger_no, valley_level } from './dungeon.js';
import { doapply, next_to_u, o_unleash } from './apply.js';
import { body_part, mbodypart } from './polyself.js';
import { closed_door, mb_trapped } from './monmove.js';
import { hard_helmet } from './do_wear.js';
import { set_wounded_legs } from './do.js';
import { impact_drop } from './dokick.js';
import { dogushforth, dryup, breaksink } from './fountain.js';
import { explode } from './explode.js';
import { align_str } from './insight.js';
import { dbon, do_attack } from './uhitm.js';
import { dmgval } from './weapon.js';
import { cmdq_add_ec, cmdq_add_key } from './input.js';
import { expels } from './mhitu.js';
import { start_timer, stop_timer, start_corpse_timeout } from './timeout.js';
// ── Non-RNG stubs for functions not yet ported ──
// body_part, mbodypart imported from polyself.js
// C ref: dungeon.c:1744 surface()
// C ref: dungeon.c:1708 ceiling()
export function ceiling(x, y) {
    const loc = levl(x, y);
    const u = game.u;
    if (in_rooms(x, y, VAULT).length > 0)
        return "vault's ceiling";
    else if (in_rooms(x, y, TEMPLE).length > 0)
        return "temple's ceiling";
    else if (in_rooms(x, y, SHOPBASE).length > 0)
        return "shop's ceiling";
    else if (Is_waterlevel(u.uz))
        return 'water above';
    else if (loc && IS_AIR(loc.typ))
        return 'sky';
    else if (Underwater)
        return "water's surface";
    else if (loc && ((IS_ROOM(loc.typ) && !Is_earthlevel(u.uz))
             || IS_WALL(loc.typ) || IS_DOOR(loc.typ) || loc.typ === SDOOR))
        return 'ceiling';
    else
        return 'rock cavern';
}
function An_str(s) {
    if (!s) return s;
    const c = s.charAt(0).toLowerCase();
    return ('aeiou'.includes(c) ? 'An' : 'A') + ' ' + s;
}
// canseemon imported from display.js
// canspotmon imported from display.js
// is_pool imported from dbridge.js
// is_lava imported from dbridge.js
// is_pit, is_hole imported from const.js
function may_dig(x, y) {
    const loc = levl(x, y);
    return loc && !(loc.wall_info & W_NONDIGGABLE);
}
// assign_level: imported from dungeon.js
// C ref: dungeon.c:1643 — Can_dig_down: no hardfloor, not bottom, not invocation level
export function Can_dig_down(uz) {
    return !game.level?.flags?.hardfloor
        && !Is_botlevel(uz)
        && !Invocation_lev(uz);
}
// Invocation_lev imported from macros.js
// Is_airlevel imported from dbridge.js
// Fumbling imported from macros.js
// is_pick: imported from mondata.js
// is_axe: imported from mondata.js
// sobj_at imported from mkobj.js
// closed_door imported from monmove.js
// does_block: imported from display.js
// undestroyable_trap imported from trap.js
// greatest_erosion: imported from objects.js
// Maybe_Half_Phys imported from macros.js
// losehp imported from hack.js
// welded imported from wield.js
// hard_helmet imported from do_wear.js
// set_wounded_legs imported from do.js
function conjoined_pits(_t1, _t2, _noisy) { return false; } // TODO
// is_flyer, is_floater imported from mondata.js
// grounded: imported from mondata.js
// passes_walls imported from mondata.js
// digests imported from mondata.js
// unique_corpstat: imported from mondata.js
// is_whirly imported from mondata.js
// is_watch: imported from mondata.js
// m_canseeu: imported from mondata.js
// in_town: imported from mklev.js
// in_rooms imported from shk.js
// add_damage imported from shk.js
// block_point: imported from display.js
// recalc_block_point imported from display.js
// feel_newsym: imported from display.js
// dropx imported from invent.js
// uhis: imported from mon.js
function OBJ_NAME(o) { return o?.oc_name || 'weapon'; }
// wake_nearby imported from mon.js
// wake_nearto imported from mon.js
// shopdig imported from shk.js
// align_str: imported from insight.js
// Amask2align imported from const.js
import { switch_terrain } from './hack.js';
// pickup imported from pickup.js
// mintrap imported from trap.js
// impact_drop imported from dokick.js
// goto_level imported from allmain.js
function teleport_pet(_mtmp, _flag) { return false; } // TODO
function assign_level_to(_dst, _src) { /* TODO */ }
// get_level: imported from dungeon.js
// make_angry_shk imported from shk.js
function obj_ice_effects(_x, _y, _flag) { /* TODO */ }
function unearth_objs_stub(_x, _y) { /* TODO */ }
function pooleffects(_flag) { return 0; } // TODO
// dogushforth imported from fountain.js
function SET_FOUNTAIN_WARNED(x, y) { /* TODO */ }
// dryup, breaksink imported from fountain.js
function spot_checks(_x, _y, _oldtyp) { /* TODO */ }
// del_engr_at imported from engrave.js at top of file
// C ref: mkobj.c:1984 — rnd_treefruit_at: random fruit from tree
function rnd_treefruit_at(x, y) {
    const treefruits = [APPLE, ORANGE, PEAR, BANANA, EUCALYPTUS_LEAF];
    return mksobj_at(treefruits[rn2(treefruits.length)], x, y, true, false);
}
// mk_tt_object: imported from mkroom.js
// explode imported from explode.js
// altar_wrath imported from pray.js
// angry_priest imported from priest.js
// desecrate_altar imported from pray.js
// dotrap imported from trap.js
// b_trapped imported from trap.js
// mb_trapped imported from monmove.js
function draft_message_stub(unexpected) { /* handled by real draft_message */ }
// do_attack imported from uhitm.js
// wield_tool imported from wield.js
// cmdq_add_ec, cmdq_add_key imported from input.js
// CQ_CANNED imported from const.js
// doapply imported from apply.js
function cant_reach_floor(_x, _y, _a, _b, _c) { /* TODO */ }
// confdir imported from cmd.js
function cmd_from_dir(dir, _mode) {
    const dirchars = ['h', 'y', 'k', 'u', 'l', 'n', 'j', 'b', '<', '>'];
    return dirchars[dir] ?? '';
}
function movecmd(ch, _mode) {
    const u = game.u;
    switch (ch) {
    case 'h': u.dx = -1; u.dy = 0; u.dz = 0; return true;
    case 'y': u.dx = -1; u.dy = -1; u.dz = 0; return true;
    case 'k': u.dx = 0; u.dy = -1; u.dz = 0; return true;
    case 'u': u.dx = 1; u.dy = -1; u.dz = 0; return true;
    case 'l': u.dx = 1; u.dy = 0; u.dz = 0; return true;
    case 'n': u.dx = 1; u.dy = 1; u.dz = 0; return true;
    case 'j': u.dx = 0; u.dy = 1; u.dz = 0; return true;
    case 'b': u.dx = -1; u.dy = 1; u.dz = 0; return true;
    case '<': u.dx = 0; u.dy = 0; u.dz = -1; return false;
    case '>': u.dx = 0; u.dy = 0; u.dz = 1; return false;
    default: u.dx = 0; u.dy = 0; u.dz = 0; return false;
    }
}
function dxdy_moveok() {
    const u = game.u;
    return !(NODIAG(u.umonnum ?? -1) && u.dx && u.dy);
}
// get_iter_mons: imported from hacklib.js
// angry_guards: imported from mklev.js
function xytodir(dx, dy) {
    // Convert dx/dy to direction index 0-7
    const xdir = [0, -1, -1, -1, 0, 1, 1, 1];
    const ydir = [-1, -1, 0, 1, 1, 1, 0, -1];
    for (let i = 0; i < 8; i++) {
        if (xdir[i] === dx && ydir[i] === dy) return i;
    }
    return DIR_ERR;
}
const xdir = [0, -1, -1, -1, 0, 1, 1, 1];
const ydir = [-1, -1, 0, 1, 1, 1, 0, -1];
// tmp_at: imported from display.js
// cmap_to_glyph: imported from display.js
// nh_delay_output: imported from hacklib.js
// expels imported from mhitu.js
// count_wsegs — imported from worm.js
// MZ_HUGE imported from monsters.js
// cnv_trap_obj imported from trap.js
import { currency, delobj, dropx, stackobj } from './invent.js';
import { add_damage, costly_spot, in_rooms, make_angry_shk, pay_for_damage, shkname, shop_keeper, shopdig, stolen_value } from './shk.js';
import { end_burn } from './light.js';
import { destroy_drawbridge, find_drawbridge, is_db_wall, is_drawbridge_wall, is_ice, is_lava, is_moat, is_pool, is_pool_or_lava } from './dbridge.js';
import { punish } from './ball.js';
import { remove_worn_item } from './steal.js';
import { angry_priest } from './priest.js';
import { can_reach_floor, losehp, NODIAG, next2u, spoteffects } from './hack.js';
import { setmnotwielded, welded, wield_tool } from './wield.js';
import { SetVoice, Soundeffect } from './sounds.js';
import { migrate_to_level } from './dog.js';
import { break_statue, fracture_rock, obj_resists } from './zap.js';
import { cvt_sdoor_to_door } from './detect.js';
import { angry_guards, in_town } from './mklev.js';
// obj_resists imported from mon.js
// obfree imported from mkobj.js
function add_to_buried(_obj) { /* TODO */ }
// start_timer, stop_timer imported from timeout.js
// TIMER_OBJECT, ROT_ORGANIC imported from const.js
// obj_to_any: imported from hacklib.js
// punish imported from ball.js
// end_burn imported from light.js
// is_ice imported from dbridge.js
// stolen_value imported from shk.js
// costly_spot imported from shk.js
// shop_keeper imported from shk.js
// shkname imported from shk.js
// maybe_unhide_at: imported from mon.js
// stackobj imported from invent.js
// start_corpse_timeout imported from timeout.js
// update_inventory imported from mon.js
// remove_worn_item imported from steal.js
// hideunder: imported from mon.js
// hides_under imported from mondata.js
// setmnotwielded imported from wield.js
// trapname imported from trap.js
// Strcpy imported from hacklib.js
// Strcat: imported from hacklib.js
// amorphous imported from mondata.js
// noncorporeal imported from mondata.js
// Passes_walls: use import from macros.js
// Teleportation imported from macros.js
// can_teleport imported from mondata.js
// Teleport_control imported from macros.js
// Luck imported from macros.js
// ── Sentinel constants matching C ──
// C: BY_YOU = &youmonst, BY_OBJECT = (struct monst *) 0
// Use a unique sentinel object for identity comparison.
const BY_YOU = Symbol('BY_YOU');
const BY_OBJECT = null;
const STRIDENT = 4; // from pray.c
// ── Implementation ──
function rm_waslit() {
    const u = game.u;
    const loc = levl(u.ux, u.uy);
    if (loc.typ === ROOM && loc.waslit) return true;
    for (let x = u.ux - 2; x < u.ux + 3; x++) {
        for (let y = u.uy - 1; y < u.uy + 2; y++) {
            if (isok(x, y) && levl(x, y).waslit) return true;
        }
    }
    return false;
}
function mkcavepos(x, y, dist, waslit, rockit) {
    if (!isok(x, y)) return;
    const lev = levl(x, y);
    if (rockit) {
        if (IS_OBSTRUCTED(lev.typ)) return;
        if (t_at(x, y)) return; // don't cover the portal
        const mtmp = m_at(x, y);
        if (mtmp && !passes_walls(mtmp.data)) {
            // rloc(mtmp, RLOC_NOMSG) — TODO
        }
    } else if (lev.typ === ROOM) {
        return;
    }
    unblock_point(x, y);
    lev.seenv = 0;
    lev.doormask = 0;
    if (dist < 3) lev.lit = rockit ? 0 : 1;
    if (waslit) lev.waslit = rockit ? 0 : 1;
    lev.horizontal = 0;
    // short-circuit vision recalc
    // gv.viz_array[y][x] = ... — TODO: vision tables
    lev.typ = rockit ? STONE : ROOM;
    if (dist >= 3) impossible(`mkcavepos called with dist ${dist}`);
    feel_newsym(x, y);
}
async function mkcavearea(rockit) {
    let xmin = game.u.ux, xmax = game.u.ux;
    let ymin = game.u.uy, ymax = game.u.uy;
    const waslit = rm_waslit();
    if (rockit) {
        Soundeffect('se_crashing_rock', 100);
        await pline('Crash!  The ceiling collapses around you!');
    } else {
        const msg = levl(game.u.ux, game.u.uy).typ === CORR
            ? 'A mysterious force creates a cave around you!'
            : 'A mysterious force extends the cave around you!';
        await pline(msg);
    }
    // display_nhwindow(WIN_MESSAGE, TRUE) — more()
    // TODO: await more() or display_nhwindow equivalent
    for (let dist = 1; dist <= 2; dist++) {
        xmin--;
        xmax++;
        if (dist < 2) {
            ymin--;
            ymax++;
            for (let i = xmin + 1; i < xmax; i++) {
                mkcavepos(i, ymin, dist, waslit, rockit);
                mkcavepos(i, ymax, dist, waslit, rockit);
            }
        }
        for (let i = ymin; i <= ymax; i++) {
            mkcavepos(xmin, i, dist, waslit, rockit);
            mkcavepos(xmax, i, dist, waslit, rockit);
        }
        await flush_screen(1);
        await delay_output();
    }
    if (!rockit && levl(game.u.ux, game.u.uy).typ === CORR) {
        const loc = levl(game.u.ux, game.u.uy);
        loc.typ = ROOM;
        if (waslit) loc.waslit = 1;
        newsym(game.u.ux, game.u.uy);
    }
    game.vision_full_recalc = 1;
}
function pick_can_reach(pick, x, y) {
    const trap = t_at(x, y);
    const target_in_pit = trap && is_pit(trap.ttyp) && trap.tseen;
    if (game.u.utrap && game.u.utraptype === TT_PIT) {
        if (target_in_pit)
            return conjoined_pits(trap, t_at(game.u.ux, game.u.uy), false);
        return bimanual(pick);
    }
    if (bimanual(pick) || Flying())
        return true;
    if (!target_in_pit)
        return true;
    return false;
}
export function dig_typ(otmp, x, y) {
    if (!isok(x, y) || !otmp || (!is_pick(otmp) && !is_axe(otmp)))
        return DIGTYP_UNDIGGABLE;
    const ltyp = levl(x, y).typ;
    if (is_axe(otmp)) {
        return closed_door(x, y) ? DIGTYP_DOOR
            : IS_TREE(ltyp) ? DIGTYP_TREE
            : DIGTYP_UNDIGGABLE;
    }
    // is_pick(otmp)
    return (sobj_at(STATUE, x, y) && pick_can_reach(otmp, x, y))
        ? DIGTYP_STATUE
        : (sobj_at(BOULDER, x, y) && pick_can_reach(otmp, x, y))
            ? DIGTYP_BOULDER
            : closed_door(x, y) ? DIGTYP_DOOR
            : IS_TREE(ltyp) ? DIGTYP_UNDIGGABLE // pick vs tree
            : (IS_OBSTRUCTED(ltyp)
                && (!game.level?.flags?.arboreal || IS_WALL(ltyp)))
                ? DIGTYP_ROCK
                : DIGTYP_UNDIGGABLE;
}
export function is_digging() {
    if (game.occupation === dig_occupation) return true;
    return false;
}
export function dig_check(madeby, x, y) {
    const ttmp = t_at(x, y);
    if (On_stairs(x, y)) {
        const stway = stairway_at(x, y);
        if (stway && stway.isladder) {
            return DIGCHECK_FAIL_ONLADDER;
        } else {
            return DIGCHECK_FAIL_ONSTAIRS;
        }
    } else if (IS_THRONE(levl(x, y).typ) && madeby !== BY_OBJECT) {
        return DIGCHECK_FAIL_THRONE;
    } else if (IS_ALTAR(levl(x, y).typ)
               && (madeby !== BY_OBJECT
                   || (altarmask_at(x, y) & AM_SANCTUM) !== 0)) {
        return DIGCHECK_FAIL_ALTAR;
    } else if (Is_airlevel(game.u.uz)) {
        return DIGCHECK_FAIL_AIRLEVEL;
    } else if (Is_waterlevel(game.u.uz)) {
        return DIGCHECK_FAIL_WATERLEVEL;
    } else if (IS_OBSTRUCTED(levl(x, y).typ) && levl(x, y).typ !== SDOOR
               && (levl(x, y).wall_info & W_NONDIGGABLE) !== 0) {
        return DIGCHECK_FAIL_TOOHARD;
    } else if (ttmp && undestroyable_trap(ttmp.ttyp)) {
        return DIGCHECK_FAIL_UNDESTROYABLETRAP;
    } else if (!Can_dig_down(game.u.uz) && !levl(x, y).candig) {
        if (ttmp) {
            if (!is_hole(ttmp.ttyp) && !is_pit(ttmp.ttyp))
                return DIGCHECK_PASSED_DESTROY_TRAP;
            else
                return DIGCHECK_FAIL_CANTDIG;
        } else {
            return DIGCHECK_PASSED_PITONLY;
        }
    } else if (sobj_at(BOULDER, x, y)) {
        return DIGCHECK_FAIL_BOULDER;
    } else if (madeby === BY_OBJECT
               && (ttmp || is_pool_or_lava(x, y))) {
        return DIGCHECK_FAIL_OBJ_POOL_OR_TRAP;
    }
    return DIGCHECK_PASSED;
}
export async function digcheck_fail_message(digresult, madeby, x, y) {
    const verb = (madeby === BY_YOU && game.u.uwep && is_axe(game.u.uwep)) ? 'chop' : 'dig in';
    if (digresult < DIGCHECK_FAILED) return;
    switch (digresult) {
    case DIGCHECK_FAIL_AIRLEVEL:
        await You(`cannot ${verb} thin air.`);
        break;
    case DIGCHECK_FAIL_ALTAR:
        await pline_The('altar is too hard to break apart.');
        break;
    case DIGCHECK_FAIL_BOULDER:
        await pline(`There isn't enough room to ${verb} here.`);
        break;
    case DIGCHECK_FAIL_ONLADDER:
        await pline_The('ladder resists your effort.');
        break;
    case DIGCHECK_FAIL_ONSTAIRS:
        await pline_The(`stairs are too hard to ${verb}.`);
        break;
    case DIGCHECK_FAIL_THRONE:
        await pline_The('throne is too hard to break apart.');
        break;
    case DIGCHECK_FAIL_CANTDIG:
    case DIGCHECK_FAIL_TOOHARD:
    case DIGCHECK_FAIL_UNDESTROYABLETRAP:
        await pline_The(`${surface(x, y)} here is too hard to ${verb}.`);
        break;
    case DIGCHECK_FAIL_WATERLEVEL:
        await pline_The(`${hliquid('water')} splashes and subsides.`);
        break;
    case DIGCHECK_FAIL_OBJ_POOL_OR_TRAP:
    case DIGCHECK_PASSED:
    case DIGCHECK_PASSED_PITONLY:
    case DIGCHECK_PASSED_DESTROY_TRAP:
        break;
    }
}
// The dig() occupation callback. Named dig_occupation to avoid
// collision with module name; C calls it dig() internally.
async function dig_occupation() {
    const g = game;
    const u = g.u;
    const ctx = g.context.digging;
    const dpx = ctx.pos?.x ?? 0;
    const dpy = ctx.pos?.y ?? 0;
    const ispick = g.u.uwep && is_pick(g.u.uwep);
    const verb = (!g.u.uwep || is_pick(g.u.uwep)) ? 'dig into' : 'chop through';
    let dcresult = DIGCHECK_PASSED;
    const lev = levl(dpx, dpy);
    // perhaps a nymph stole your pick-axe while you were busy digging
    // or perhaps you teleported away
    if (u.uswallow || !g.u.uwep || (!ispick && !is_axe(g.u.uwep))
        || !on_level(ctx.level, u.uz)
        || (ctx.down ? (dpx !== u.ux || dpy !== u.uy)
                     : !next2u(dpx, dpy))) {
        return 0;
    }
    if (ctx.down) {
        dcresult = dig_check(BY_YOU, u.ux, u.uy);
        if (dcresult >= DIGCHECK_FAILED) {
            await digcheck_fail_message(dcresult, BY_YOU, u.ux, u.uy);
            return 0;
        }
    } else {
        if (IS_TREE(lev.typ) && !may_dig(dpx, dpy)
            && dig_typ(g.u.uwep, dpx, dpy) === DIGTYP_TREE) {
            await pline('This tree seems to be petrified.');
            return 0;
        }
        if (IS_OBSTRUCTED(lev.typ) && !may_dig(dpx, dpy)
            && dig_typ(g.u.uwep, dpx, dpy) === DIGTYP_ROCK) {
            await pline(`This ${is_db_wall(dpx, dpy) ? 'drawbridge' : 'wall'} is too hard to ${verb}.`);
            return 0;
        }
    }
    if (Fumbling() && !rn2(3)) {
        switch (rn2(3)) {
        case 0:
            if (!welded(g.u.uwep)) {
                await You(`fumble and drop ${yname(g.u.uwep)}.`);
                await dropx(g.u.uwep);
            } else {
                if (u.usteed) {
                    await pline(`${Yobjnam2(g.u.uwep, 'bounce')} and hits ${mon_nam(u.usteed)}!`);
                } else {
                    await pline(`Ouch!  ${Yobjnam2(g.u.uwep, 'bounce')} and hits you!`);
                }
                await set_wounded_legs(RIGHT_SIDE, 5 + rnd(5));
            }
            break;
        case 1:
            Soundeffect('se_bang_weapon_side', 100);
            await pline(`Bang!  You hit with the broad side of ${the(xname(g.u.uwep))}!`);
            wake_nearby(false);
            break;
        default:
            await Your('swing misses its mark.');
            break;
        }
        return 0;
    }
    ctx.effort += 10 + rn2(5) + abon() + g.u.uwep.spe - greatest_erosion(g.u.uwep) + (u.udaminc || 0);
    if (Race_if(PM_DWARF))
        ctx.effort *= 2;
    if (ctx.down) {
        const ttmp = t_at(dpx, dpy);
        if (ctx.effort > 250 || (ttmp && ttmp.ttyp === HOLE)) {
            await dighole(false, false, null);
            // memset context.digging to 0
            Object.assign(ctx, { pos: { x: 0, y: 0 }, level: { dnum: 0, dlevel: 0 },
                down: false, chew: false, warned: false, quiet: false, effort: 0,
                lastdigtime: 0 });
            return 0;
        }
        if (ctx.effort <= 50
            || (ttmp && (ttmp.ttyp === TRAPDOOR || is_pit(ttmp.ttyp)))) {
            return 1;
        } else if (ttmp && (ttmp.ttyp === LANDMINE
                            || (ttmp.ttyp === BEAR_TRAP && !u.utrap))) {
            await dotrap(ttmp, FORCETRAP);
            Object.assign(ctx, { pos: { x: 0, y: 0 }, level: { dnum: 0, dlevel: 0 },
                down: false, chew: false, warned: false, quiet: false, effort: 0,
                lastdigtime: 0 });
            return 0;
        } else if (ttmp && ttmp.ttyp === BEAR_TRAP && u.utrap) {
            if (rnl(7) > (Fumbling() ? 1 : 4)) {
                let dmg = dmgval(g.u.uwep, game.player) + dbon();
                if (dmg < 1) dmg = 1;
                else if (game.u.uarmf) dmg = Math.trunc((dmg + 1) / 2);
                await You(`hit yourself in the ${body_part(FOOT)}.`);
                const kbuf = `chopping off ${uhis()} own ${body_part(FOOT)}`;
                await losehp(Maybe_Half_Phys(dmg), kbuf, KILLED_BY);
            } else {
                await You(`destroy the bear trap with ${yobjnam(g.u.uwep, null)}.`);
                deltrap(ttmp);
                await reset_utrap(true);
            }
            ctx.effort = 0;
            return 0;
        } else if (ttmp && dcresult === DIGCHECK_PASSED_DESTROY_TRAP) {
            const ttmpname = trapname(ttmp.ttyp, false);
            if (ispick) {
                await You(`destroy ${ttmp.tseen ? the(ttmpname) : an(ttmpname)} with ${yobjnam(g.u.uwep, null)}.`);
            }
            deltrap(ttmp);
            ctx.effort = 0;
            return 0;
        }
        if (IS_ALTAR(lev.typ)) {
            await altar_wrath(dpx, dpy);
            await angry_priest();
        }
        if (await dighole(true, false, null)) {
            ctx.level.dnum = 0;
            ctx.level.dlevel = -1;
        }
        return 0;
    }
    if (ctx.effort > 100) {
        let digtxt = null;
        let dmgtxt = null;
        const shopedge = in_rooms(dpx, dpy, SHOPBASE).length > 0;
        const digtyp = dig_typ(g.u.uwep, dpx, dpy);
        if (digtyp === DIGTYP_STATUE) {
            const obj = sobj_at(STATUE, dpx, dpy);
            if (obj) {
                if (break_statue(obj))
                    digtxt = 'The statue shatters.';
                else
                    digtxt = null;
            }
        } else if (digtyp === DIGTYP_BOULDER) {
            const obj = sobj_at(BOULDER, dpx, dpy);
            if (obj) {
                fracture_rock(obj);
                const bobj = sobj_at(BOULDER, dpx, dpy);
                if (bobj) {
                    obj_extract_self(bobj);
                    place_object(bobj, dpx, dpy);
                }
                digtxt = 'The boulder falls apart.';
            }
        } else if (lev.typ === STONE || lev.typ === SCORR || IS_TREE(lev.typ)) {
            if (Is_earthlevel(u.uz)) {
                if (g.u.uwep.blessed && !rn2(3)) {
                    await mkcavearea(false);
                    // goto cleanup
                    ctx.lastdigtime = game.moves;
                    ctx.quiet = false;
                    ctx.level.dnum = 0;
                    ctx.level.dlevel = -1;
                    return 0;
                } else if ((g.u.uwep.cursed && !rn2(4))
                           || (!g.u.uwep.blessed && !rn2(6))) {
                    await mkcavearea(true);
                    ctx.lastdigtime = game.moves;
                    ctx.quiet = false;
                    ctx.level.dnum = 0;
                    ctx.level.dlevel = -1;
                    return 0;
                }
            }
            if (digtyp === DIGTYP_TREE) {
                digtxt = 'You cut down the tree.';
                lev.typ = ROOM;
                lev.flags = 0;
                if (!rn2(5)) rnd_treefruit_at(dpx, dpy);
                if (Race_if(PM_ELF) || Role_if(PM_RANGER))
                    adjalign(-1);
            } else {
                digtxt = 'You succeed in cutting away some rock.';
                lev.typ = CORR;
                lev.flags = 0;
            }
        } else if (IS_WALL(lev.typ)) {
            if (shopedge) {
                add_damage(dpx, dpy, 10 * ACURR(A_STR)); // SHOP_WALL_DMG
                dmgtxt = 'damage';
            }
            if (game.level?.flags?.is_maze_lev) {
                lev.typ = ROOM;
                lev.flags = 0;
            } else if (game.level?.flags?.is_cavernous_lev
                       && !in_town(dpx, dpy)) {
                lev.typ = CORR;
                lev.flags = 0;
            } else {
                lev.typ = DOOR;
                lev.doormask = D_NODOOR;
            }
            digtxt = 'You make an opening in the wall.';
        } else if (lev.typ === SDOOR) {
            cvt_sdoor_to_door(lev);
            digtxt = 'You break through a secret door!';
            if (!(lev.doormask & D_TRAPPED))
                lev.doormask = D_BROKEN;
        } else if (closed_door(dpx, dpy)) {
            digtxt = `You break through the door with your ${simpleonames(g.u.uwep)}.`;
            if (shopedge) {
                add_damage(dpx, dpy, SHOP_DOOR_COST);
                dmgtxt = 'break';
            }
            if (!(lev.doormask & D_TRAPPED))
                lev.doormask = D_BROKEN;
        } else {
            return 0; // statue or boulder got taken
        }
        if (!does_block(dpx, dpy, lev))
            unblock_point(dpx, dpy);
        feel_newsym(dpx, dpy);
        if (digtxt && !ctx.quiet)
            await pline(digtxt);
        if (dmgtxt)
            await pay_for_damage(dmgtxt, false);
        if (Is_earthlevel(u.uz) && !rn2(3)) {
            const mndx = rn2(2) ? PM_EARTH_ELEMENTAL : PM_XORN;
            if (await makemon(mons[mndx], dpx, dpy, MM_NOMSG))
                await pline_The('debris from your digging comes to life!');
        }
        if (IS_DOOR(lev.typ) && (lev.doormask & D_TRAPPED)) {
            lev.doormask = D_NODOOR;
            await b_trapped('door', NO_PART);
            recalc_block_point(dpx, dpy);
            newsym(dpx, dpy);
        }
        // cleanup:
        ctx.lastdigtime = game.moves;
        ctx.quiet = false;
        ctx.level.dnum = 0;
        ctx.level.dlevel = -1;
        return 0;
    } else {
        // not enough effort yet
        const d_target = ['', 'rock', 'statue', 'boulder', 'door', 'tree'];
        const dig_target = dig_typ(g.u.uwep, dpx, dpy);
        if (IS_WALL(lev.typ) || dig_target === DIGTYP_DOOR) {
            if (in_rooms(dpx, dpy, SHOPBASE).length > 0) {
                await pline(`This ${IS_DOOR(lev.typ) ? 'door' : 'wall'} seems too hard to ${verb}.`);
                return 0;
            }
        } else if (dig_target === DIGTYP_UNDIGGABLE
                   || (dig_target === DIGTYP_ROCK && !IS_OBSTRUCTED(lev.typ))) {
            return 0; // statue or boulder got taken
        }
        if (!game.did_dig_msg) {
            await You(`hit the ${d_target[dig_target]} with all your might.`);
            wake_nearby(false);
            game.did_dig_msg = true;
        }
    }
    return 1;
}
async function furniture_handled(x, y, madeby_u) {
    const lev = levl(x, y);
    if (IS_FOUNTAIN(lev.typ)) {
        await dogushforth(false);
        SET_FOUNTAIN_WARNED(x, y);
        await dryup(x, y, madeby_u);
    } else if (IS_SINK(lev.typ)) {
        await breaksink(x, y);
    } else if (lev.typ === DRAWBRIDGE_DOWN
               || (is_drawbridge_wall(x, y) >= 0)) {
        let bx = x, by = y;
        find_drawbridge(bx, by); // TODO: needs reference semantics
        await destroy_drawbridge(bx, by);
    } else {
        return false;
    }
    return true;
}
export function holetime() {
    if (game.occupation !== dig_occupation || !game.u.ushops)
        return -1;
    return Math.trunc((250 - (game.context?.digging?.effort || 0)) / 20);
}
export function fillholetyp(x, y, fill_if_any) {
    const lo_x = Math.max(1, x - 1), hi_x = Math.min(x + 1, COLNO - 1);
    const lo_y = Math.max(0, y - 1), hi_y = Math.min(y + 1, ROWNO - 1);
    let pool_cnt = 0, moat_cnt = 0, lava_cnt = 0;
    for (let x1 = lo_x; x1 <= hi_x; x1++) {
        for (let y1 = lo_y; y1 <= hi_y; y1++) {
            if (is_moat(x1, y1))
                moat_cnt++;
            else if (is_pool(x1, y1))
                pool_cnt++;
            else if (is_lava(x1, y1))
                lava_cnt++;
        }
    }
    if (!fill_if_any)
        pool_cnt = Math.trunc(pool_cnt / 3);
    if ((lava_cnt > moat_cnt + pool_cnt && rn2(lava_cnt + 1))
        || (lava_cnt && fill_if_any))
        return LAVAPOOL;
    else if ((moat_cnt > 0 && rn2(moat_cnt + 1)) || (moat_cnt && fill_if_any))
        return MOAT;
    else if ((pool_cnt > 0 && rn2(pool_cnt + 1)) || (pool_cnt && fill_if_any))
        return POOL;
    else
        return ROOM;
}
export async function digactualhole(x, y, madeby, ttyp) {
    const u = game.u;
    const lev = levl(x, y);
    const mtmp = m_at(x, y);
    const madeby_u = (madeby === BY_YOU);
    const madeby_obj = (madeby === BY_OBJECT);
    const heros_fault = (madeby_u || madeby_obj);
    let shopdoor, at_u = u_at(x, y), wont_fall = Levitation() || Flying();
    let old_typ, old_aligntyp = A_NONE;
    if (at_u && u.utrap) {
        if (u.utraptype === TT_BURIEDBALL)
            await buried_ball_to_punishment();
        else if (u.utraptype === TT_INFLOOR)
            await reset_utrap(false);
    }
    if (await furniture_handled(x, y, madeby_u))
        return;
    if (ttyp !== PIT && (!Can_dig_down(u.uz) && !lev.candig)) {
        impossible(`digactualhole: can't dig ${trapname(ttyp, true)} on this level.`);
        ttyp = PIT;
    }
    old_typ = lev.typ;
    let furniture = '';
    if (IS_FURNITURE(lev.typ)) {
        const surface_type = (IS_ROOM(lev.typ) && !Is_earthlevel(u.uz))
            ? 'floor' : 'ground';
        if (IS_ALTAR(lev.typ)) {
            old_aligntyp = Amask2align(levl(x, y).altarmask & AM_MASK);
            furniture = align_str(old_aligntyp) + ' ';
        }
        furniture += surface(x, y);
    }
    const surface_type = IS_FURNITURE(old_typ)
        ? ((IS_ROOM(old_typ) && !Is_earthlevel(u.uz)) ? 'floor' : 'ground')
        : surface(x, y);
    shopdoor = IS_DOOR(lev.typ) && in_rooms(x, y, SHOPBASE).length > 0;
    const oldobjs = game.level?.objects?.[x]?.[y] || null;
    const ttmp = await maketrap(x, y, ttyp);
    if (!ttmp) return;
    const newobjs = game.level?.objects?.[x]?.[y] || null;
    ttmp.madeby_u = heros_fault;
    ttmp.tseen = 0;
    if (cansee(x, y))
        seetrap(ttmp);
    else if (madeby_u)
        feeltrap(ttmp);
    const tname = trapname(ttyp, true);
    const in_thru = (ttyp === HOLE ? 'through' : 'in');
    if (madeby_u) {
        if (x !== u.ux || y !== u.uy)
            await You(`dig an adjacent ${tname}.`);
        else
            await You(`dig ${an(tname)} ${in_thru} the ${surface_type}.`);
    } else if (!madeby_obj && canseemon(madeby)) {
        await pline(`${Monnam(madeby)} digs ${an(tname)} ${in_thru} the ${surface_type}.`);
    } else if (cansee(x, y) && game.flags?.verbose) {
        if (IS_STWALL(old_typ))
            await pline_The(`${surface_type} crumbles into ${an(tname)}.`);
        else
            await pline(`${An_str(tname)} appears in the ${surface_type}.`);
    }
    if (IS_FURNITURE(old_typ) && cansee(x, y))
        await pline_The(`${furniture} falls into the ${tname}!`);
    if (heros_fault && old_typ === ALTAR)
        await desecrate_altar(false, old_aligntyp);
    if (ttyp === PIT) {
        if (shopdoor && heros_fault)
            await pay_for_damage('ruin', false);
        else
            add_damage(x, y, heros_fault ? SHOP_PIT_COST : 0);
        if (madeby_u) wake_nearby(false);
        await switch_terrain();
        if (Levitation() || Flying()) wont_fall = true;
        if (at_u) {
            if (!wont_fall) {
                set_utrap(rn1(4, 2), TT_PIT);
                game.vision_full_recalc = 1;
            } else {
                await reset_utrap(true);
            }
            if (oldobjs !== newobjs) await pickup(1);
        } else if (mtmp) {
            if (is_flyer(mtmp.data) || is_floater(mtmp.data)) {
                if (canseemon(mtmp))
                    await pline(`${Monnam(mtmp)} ${is_flyer(mtmp.data) ? 'flies' : 'floats'} over the pit.`);
            } else if (mtmp !== madeby) {
                await mintrap(mtmp, 0 /* NO_TRAP_FLAGS */);
            }
        }
    } else {
        // HOLE / TRAPDOOR
        if (at_u) {
            await switch_terrain();
            if (Levitation() || Flying()) wont_fall = true;
            if (!u.ustuck && !wont_fall && !await next_to_u()) {
                await You('are jerked back by your pet!');
                wont_fall = true;
            }
            if (u.ustuck || wont_fall) {
                if (newobjs) await impact_drop(null, x, y, 0);
                if (oldobjs !== newobjs) await pickup(1);
                if (shopdoor && heros_fault)
                    await pay_for_damage('ruin', false);
            } else {
                if (u.ushops && heros_fault)
                    await shopdig(1);
                else
                    await pay_for_damage('dig into', true);
                await You('fall through...');
                const newlevel = { dnum: u.uz.dnum, dlevel: u.uz.dlevel + 1 };
                await goto_level(newlevel, false, true, false);
                await spoteffects(false);
            }
        } else {
            if (shopdoor && heros_fault)
                await pay_for_damage('ruin', false);
            if (newobjs) await impact_drop(null, x, y, 0);
            if (mtmp) {
                if (!grounded(mtmp.data)
                    || (mtmp.wormno && count_wsegs(mtmp) > 5)
                    || (mtmp.data?.msize || 0) >= MZ_HUGE)
                    return;
                if (mtmp === u.ustuck) return;
                if (teleport_pet(mtmp, false)) {
                    let tolevel;
                    if (Is_stronghold(u.uz)) {
                        tolevel = valley_level();
                    } else if (Is_botlevel(u.uz)) {
                        if (canseemon(mtmp))
                            await pline(`${Monnam(mtmp)} avoids the trap.`);
                        return;
                    } else {
                        tolevel = { dnum: u.uz.dnum, dlevel: u.uz.dlevel + 1 };
                    }
                    if (mtmp.isshk) await make_angry_shk(mtmp, 0, 0);
                    await migrate_to_level(mtmp, ledger_no(tolevel), 0 /* MIGR_RANDOM */, null);
                }
            }
        }
    }
}
export async function liquid_flow(x, y, typ, ttmp, fillmsg) {
    const u_spot = u_at(x, y);
    if (!is_pool_or_lava(x, y)) {
        return;
    }
    if (ttmp) delfloortrap(ttmp);
    obj_ice_effects(x, y, true);
    // unearth_objs(x, y); — use stub to avoid name collision
    unearth_objs_stub(x, y);
    if (fillmsg) {
        const liquid = hliquid(typ === LAVAPOOL ? 'lava' : 'water');
        await pline(fillmsg.replace('%s', liquid));
    }
    const objchain = game.level?.objects?.[x]?.[y] || null;
    if (objchain) {
        if (typ === LAVAPOOL)
            await fire_damage_chain(objchain, true, true, x, y);
        else
            await water_damage_chain(objchain, true);
    }
    if (u_spot) {
        pooleffects(false);
    } else {
        const mon = m_at(x, y);
        if (mon) await minliquid(mon);
    }
}
export async function dighole(pit_only, by_magic, cc) {
    const u = game.u;
    let dig_x, dig_y;
    if (!cc) {
        dig_x = u.ux;
        dig_y = u.uy;
    } else {
        dig_x = cc.x;
        dig_y = cc.y;
        if (!isok(dig_x, dig_y)) return false;
    }
    let ttmp = t_at(dig_x, dig_y);
    const lev = levl(dig_x, dig_y);
    const dig_check_result = dig_check(BY_YOU, dig_x, dig_y);
    const nohole = (dig_check_result === DIGCHECK_FAIL_CANTDIG
                    || dig_check_result === DIGCHECK_FAIL_TOOHARD);
    const old_typ = lev.typ;
    if ((ttmp && (undestroyable_trap(ttmp.ttyp) || nohole))
        || (IS_OBSTRUCTED(old_typ) && old_typ !== SDOOR
            && (lev.wall_info & W_NONDIGGABLE) !== 0)) {
        await pline_The(`${surface(dig_x, dig_y)} ${(dig_x !== u.ux || dig_y !== u.uy) ? 't' : ''}here is too hard to dig in.`);
    } else if (ttmp && is_magical_trap(ttmp.ttyp)) {
        await explode(dig_x, dig_y, 0, 20 + c_d(3, 6), TRAP_EXPLODE, EXPL_MAGICAL);
        deltrap(ttmp);
        newsym(dig_x, dig_y);
    } else if (is_pool_or_lava(dig_x, dig_y)) {
        await pline_The(`${hliquid(is_lava(dig_x, dig_y) ? 'lava' : 'water')} sloshes furiously for a moment, then subsides.`);
        wake_nearby(false);
    } else if (old_typ === DRAWBRIDGE_DOWN
               || (is_drawbridge_wall(dig_x, dig_y) >= 0)) {
        if (pit_only) {
            await pline_The('drawbridge seems too hard to dig through.');
        } else {
            let bx = dig_x, by = dig_y;
            find_drawbridge(bx, by);
            await destroy_drawbridge(bx, by);
            spot_checks(dig_x, dig_y, old_typ);
            return true;
        }
    } else if (sobj_at(BOULDER, dig_x, dig_y)) {
        const boulder_here = sobj_at(BOULDER, dig_x, dig_y);
        if (ttmp && is_pit(ttmp.ttyp) && rn2(2)) {
            await pline_The(`boulder settles into the ${(dig_x !== u.ux || dig_y !== u.uy) ? 'adjacent ' : ''}pit.`);
            ttmp.ttyp = PIT;
        } else {
            Soundeffect('se_kadoom_boulder_falls_in', 60);
            await pline('KADOOM!  The boulder falls in!');
            wake_nearby(false);
            delfloortrap(ttmp);
        }
        delobj(boulder_here);
    } else if (IS_GRAVE(old_typ)) {
        await digactualhole(dig_x, dig_y, BY_YOU, PIT);
        await dig_up_grave(cc);
        spot_checks(dig_x, dig_y, old_typ);
        return true;
    } else if (old_typ === DRAWBRIDGE_UP) {
        const typ = fillholetyp(dig_x, dig_y, false);
        if (typ === ROOM) {
            await pline_The(`${surface(dig_x, dig_y)} ${(dig_x !== u.ux || dig_y !== u.uy) ? 't' : ''}here is too hard to dig in.`);
        } else {
            lev.drawbridgemask &= ~DB_UNDER;
            lev.drawbridgemask |= (typ === LAVAPOOL) ? DB_LAVA : DB_MOAT;
            await liquid_flow(dig_x, dig_y, typ, ttmp,
                'As you dig, the hole fills with %s!');
            spot_checks(dig_x, dig_y, old_typ);
            return true;
        }
    } else if (IS_THRONE(old_typ)) {
        await pline_The('throne is too hard to break apart.');
    } else if (IS_ALTAR(old_typ)) {
        await pline_The('altar is too hard to break apart.');
    } else {
        const typ = fillholetyp(dig_x, dig_y, false);
        lev.flags = 0;
        if (typ !== ROOM) {
            if (!await furniture_handled(dig_x, dig_y, true)) {
                lev.typ = typ;
                await liquid_flow(dig_x, dig_y, typ, ttmp,
                    'As you dig, the hole fills with %s!');
            }
            spot_checks(dig_x, dig_y, old_typ);
            return true;
        } else {
            if (by_magic && ttmp
                && (ttmp.ttyp === LANDMINE || ttmp.ttyp === BEAR_TRAP)) {
                const otyp = (ttmp.ttyp === LANDMINE) ? LAND_MINE : BEARTRAP;
                cnv_trap_obj(otyp, 1, ttmp, true);
            }
            if (nohole || pit_only
                || dig_check_result === DIGCHECK_PASSED_DESTROY_TRAP
                || dig_check_result === DIGCHECK_PASSED_PITONLY)
                await digactualhole(dig_x, dig_y, BY_YOU, PIT);
            else
                await digactualhole(dig_x, dig_y, BY_YOU, HOLE);
            spot_checks(dig_x, dig_y, old_typ);
            return true;
        }
    }
    spot_checks(dig_x, dig_y, old_typ);
    return false;
}
async function dig_up_grave(cc) {
    let dig_x, dig_y;
    if (!cc) {
        dig_x = game.u.ux;
        dig_y = game.u.uy;
    } else {
        dig_x = cc.x;
        dig_y = cc.y;
        if (!isok(dig_x, dig_y)) return;
    }
    exercise(A_WIS, false);
    if (Role_if(PM_ARCHEOLOGIST)) {
        adjalign(-sgn(game.u.ualign?.type || 0) * 3);
        await You_feel('like a despicable grave-robber!');
    } else if (Role_if(PM_SAMURAI)) {
        adjalign(-sgn(game.u.ualign?.type || 0));
        await You('disturb the honorable dead!');
    } else if ((game.u.ualign?.type || 0) === A_LAWFUL) {
        if ((game.u.ualign?.record || 0) > -10)
            adjalign(-1);
        await You('have violated the sanctity of this grave!');
    }
    const what_happens = levl(dig_x, dig_y).emptygrave ? -1 : rn2(5);
    switch (what_happens) {
    case 0:
    case 1:
        await You('unearth a corpse.');
        {
            const otmp = mk_tt_object(CORPSE, dig_x, dig_y);
            if (otmp) otmp.age -= (TAINT_AGE + 1);
        }
        break;
    case 2:
        if (!Blind()) {
            await pline(`${Hallucination() ? 'Dude!  The living dead' : "The grave's owner is very upset"}!`);
        }
        await makemon(mkclass(S_ZOMBIE, 0), dig_x, dig_y, MM_NOMSG);
        break;
    case 3:
        if (!Blind()) {
            await pline(`${Hallucination() ? 'I want my mummy' : "You've disturbed a tomb"}!`);
        }
        await makemon(mkclass(S_MUMMY, 0), dig_x, dig_y, MM_NOMSG);
        break;
    default:
        await pline_The('grave is unoccupied.  Strange...');
        break;
    }
    const grav = levl(dig_x, dig_y);
    grav.typ = ROOM;
    grav.emptygrave = 0;
    grav.disturbed = 0;
    del_engr_at(dig_x, dig_y);
    newsym(dig_x, dig_y);
}
export async function use_pick_axe(obj) {
    const g = game;
    const u = g.u;
    let res = ECMD_OK;
    if (obj !== g.u.uwep) {
        if (await wield_tool(obj, 'swing')) {
            cmdq_add_ec(CQ_CANNED, doapply);
            cmdq_add_key(CQ_CANNED, obj.invlet);
            return ECMD_TIME;
        }
        return ECMD_OK;
    }
    const ispick = is_pick(obj);
    const verb = ispick ? 'dig' : 'chop';
    if (u.utrap && u.utraptype === TT_WEB) {
        await pline(`${!res ? 'Unfortunately,' : 'But'} you can't ${verb} while entangled in a web.`);
        return res;
    }
    // C ref: dig.c use_pick_axe() — build likely direction choices.
    const dirsyms = [];
    const downok = !!can_reach_floor(false);
    for (let dir = 0; dir < N_DIRS_Z; dir++) {
        const dirch = cmd_from_dir(dir, MV_WALK);
        if (!dirch) continue;
        if (u.uswallow) {
            // all directions are viable when swallowed
        } else if (movecmd(dirch, MV_WALK)) {
            if (!dxdy_moveok()) continue;
            const rx = u.ux + u.dx;
            const ry = u.uy + u.dy;
            if (!isok(rx, ry) || dig_typ(obj, rx, ry) === DIGTYP_UNDIGGABLE) {
                continue;
            }
        } else {
            if ((u.dz > 0) ^ downok) continue;
        }
        dirsyms.push(dirch);
    }
    const qbuf = `In what direction do you want to ${verb}? [${dirsyms.join('')}]`;
    if (!await getdir(qbuf))
        return (res | ECMD_CANCEL);
    return await use_pick_axe2(obj);
}
export async function use_pick_axe2(obj) {
    const g = game;
    const u = g.u;
    const ctx = g.context.digging;
    let rx, ry;
    const ispick = is_pick(obj);
    const verbing = ispick ? 'digging' : 'chopping';
    if (u.uswallow && await do_attack(u.ustuck)) {
        ; // return ECMD_TIME below
    } else if (Underwater()) {
        await pline(`Turbulence torpedoes your ${verbing} attempts.`);
    } else if (u.dz < 0) {
        if (Levitation())
            await You("don't have enough leverage.");
        else
            await You_cant(`reach the ${ceiling(u.ux, u.uy)}.`);
    } else if (!u.dx && !u.dy && !u.dz) {
        let dam = rnd(2) + dbon() + obj.spe;
        if (dam <= 0) dam = 1;
        await You(`hit yourself with ${yname(g.u.uwep)}.`);
        const buf = `${uhis()} own ${OBJ_NAME(game.objects[obj.otyp])}`;
        await losehp(Maybe_Half_Phys(dam), buf, KILLED_BY);
        g.disp = g.disp || {};
        setBotl('use_pick_axe2');
        return ECMD_TIME;
    } else if (u.dz === 0) {
        confdir(false);
        rx = u.ux + u.dx;
        ry = u.uy + u.dy;
        if (!isok(rx, ry)) {
            Soundeffect('se_clash', 40);
            await pline('Clash!');
            return ECMD_TIME;
        }
        const lev = levl(rx, ry);
        if (m_at(rx, ry) && await do_attack(m_at(rx, ry)))
            return ECMD_TIME;
        const dig_target = dig_typ(obj, rx, ry);
        if (dig_target === DIGTYP_UNDIGGABLE) {
            const trap = t_at(rx, ry);
            if (trap && trap.ttyp === WEB) {
                if (!trap.tseen) {
                    seetrap(trap);
                    await pline('There is a spider web there!');
                }
                await pline(`${Yobjnam2(obj, 'become')} entangled in the web.`);
                nomul(-c_d(2, 2));
                game.multi_reason = 'stuck in a spider web';
                game.nomovemsg = 'You pull free.';
            } else if (lev.typ === IRONBARS) {
                await pline('Clang!');
                wake_nearby(false);
            } else if (IS_WATERWALL(lev.typ)) {
                await pline('Splash!');
            } else if (lev.typ === LAVAWALL) {
                await pline('Splash!');
                await fire_damage(g.u.uwep, false, rx, ry);
            } else if (IS_TREE(lev.typ)) {
                await You('need an axe to cut down a tree.');
            } else if (IS_OBSTRUCTED(lev.typ)) {
                await You('need a pick to dig rock.');
            } else if (sobj_at(BOULDER, rx, ry) || sobj_at(STATUE, rx, ry)) {
                const boulder = sobj_at(BOULDER, rx, ry);
                const what = boulder ? 'boulder' : 'statue';
                if (!ispick) {
                    const vibrate = !rn2(3);
                    await pline(`Sparks fly as you whack the ${what}.${vibrate ? '  The axe-handle vibrates violently!' : ''}`);
                    if (vibrate)
                        await losehp(Maybe_Half_Phys(2), 'axing a hard object', KILLED_BY);
                    wake_nearby(false);
                } else {
                    await You_cant(`reach the ${what}.`);
                }
            } else if (u.utrap && u.utraptype === TT_PIT && trap
                       && (t_at(u.ux, u.uy))
                       && is_pit(trap.ttyp)
                       && !conjoined_pits(trap, t_at(u.ux, u.uy), false)) {
                const idx = xytodir(u.dx, u.dy);
                if (idx !== DIR_ERR) {
                    const adjidx = DIR_180(idx);
                    const trap_with_u = t_at(u.ux, u.uy);
                    trap_with_u.conjoined |= (1 << idx);
                    trap.conjoined |= (1 << adjidx);
                    await You('clear some debris from between the pits.');
                }
            } else if (u.utrap && u.utraptype === TT_PIT
                       && t_at(u.ux, u.uy)) {
                await You(`swing ${yobjnam(obj, null)}, but the rubble has no place to go.`);
            } else {
                await You(`swing ${yobjnam(obj, null)} through thin air.`);
            }
        } else {
            const d_action = ['swinging', 'digging', 'chipping the statue',
                              'hitting the boulder', 'chopping at the door',
                              'cutting the tree'];
            game.did_dig_msg = false;
            ctx.quiet = false;
            if (ctx.pos.x !== rx || ctx.pos.y !== ry
                || !on_level(ctx.level, u.uz)
                || ctx.down) {
                if (game.flags?.autodig && dig_target === DIGTYP_ROCK
                    && !ctx.down
                    && u_at(ctx.pos.x, ctx.pos.y)
                    && (game.moves <= ctx.lastdigtime + 2
                        && game.moves >= ctx.lastdigtime)) {
                    game.did_dig_msg = true;
                    ctx.quiet = true;
                }
                ctx.down = false;
                ctx.chew = false;
                ctx.warned = false;
                ctx.pos.x = rx;
                ctx.pos.y = ry;
                assign_level(ctx.level, u.uz);
                ctx.effort = 0;
                if (!ctx.quiet)
                    await You(`start ${d_action[dig_target]}.`);
            } else {
                await You(`${ctx.chew ? 'begin' : 'continue'} ${d_action[dig_target]}.`);
                ctx.chew = false;
            }
            set_occupation(dig_occupation, verbing, 0);
        }
    } else if (Is_airlevel(u.uz) || Is_waterlevel(u.uz)) {
        await You(`swing ${yobjnam(obj, null)} through thin air.`);
    } else if (!can_reach_floor(false)) {
        cant_reach_floor(u.ux, u.uy, false, false, false);
    } else if (is_pool_or_lava(u.ux, u.uy)) {
        await You(`cannot stay under${is_pool(u.ux, u.uy) ? 'water' : ' the lava'} long enough.`);
    } else if ((t_at(u.ux, u.uy))
               && (uteetering_at_seen_pit(t_at(u.ux, u.uy)) || uescaped_shaft(t_at(u.ux, u.uy)))) {
        await dotrap(t_at(u.ux, u.uy), FORCEBUNGLE);
        if (!u.utrap)
            cant_reach_floor(u.ux, u.uy, false, true, false);
    } else if (!ispick
               && (!(t_at(u.ux, u.uy)) || (t_at(u.ux, u.uy).ttyp !== LANDMINE
                   && t_at(u.ux, u.uy).ttyp !== BEAR_TRAP))) {
        await pline(`${Yobjnam2(obj, null)} merely scratches the ${surface(u.ux, u.uy)}.`);
        u_wipe_engr(3);
    } else {
        if (ctx.pos.x !== u.ux || ctx.pos.y !== u.uy
            || !on_level(ctx.level, u.uz) || !ctx.down) {
            ctx.chew = false;
            ctx.down = true;
            ctx.warned = false;
            ctx.pos.x = u.ux;
            ctx.pos.y = u.uy;
            assign_level(ctx.level, u.uz);
            ctx.effort = 0;
            await You(`start ${verbing} downward.`);
            if (u.ushops) {
                await shopdig(0);
                add_damage(u.ux, u.uy, SHOP_PIT_COST);
            }
        } else {
            await You(`continue ${verbing} downward.`);
        }
        game.did_dig_msg = false;
        set_occupation(dig_occupation, verbing, 0);
    }
    return ECMD_TIME;
}
function watchman_canseeu(mtmp) {
    if (is_watch(mtmp.data) && mtmp.mcansee && m_canseeu(mtmp)
        && mtmp.mpeaceful)
        return true;
    return false;
}
export async function watch_dig(mtmp, x, y, zap) {
    const lev = levl(x, y);
    if (in_town(x, y)
        && (closed_door(x, y) || lev.typ === SDOOR || IS_WALL(lev.typ)
            || IS_FOUNTAIN(lev.typ) || IS_TREE(lev.typ))) {
        if (!mtmp)
            mtmp = await get_iter_mons(watchman_canseeu);
        if (mtmp) {
            SetVoice(mtmp, 0, 80, 0);
            const ctx = game.context?.digging;
            if (zap || (ctx && ctx.warned)) {
                await verbalize("Halt, vandal!  You're under arrest!");
                angry_guards(!!Deaf());
            } else {
                let str;
                if (IS_DOOR(lev.typ)) str = 'door';
                else if (IS_TREE(lev.typ)) str = 'tree';
                else if (IS_OBSTRUCTED(lev.typ)) str = 'wall';
                else str = 'fountain';
                await verbalize(`Hey, stop damaging that ${str}!`);
                if (ctx) ctx.warned = true;
            }
            if (is_digging()) await stop_occupation();
        }
    }
}
export async function mdig_tunnel(mtmp) {
    const here = levl(mtmp.mx, mtmp.my);
    let sawit, seeit, trapped;
    const pile = rnd(12);
    if (here.typ === SDOOR)
        cvt_sdoor_to_door(here);
    if (closed_door(mtmp.mx, mtmp.my)) {
        if (in_rooms(mtmp.mx, mtmp.my, SHOPBASE).length > 0)
            add_damage(mtmp.mx, mtmp.my, 0);
        sawit = canseemon(mtmp);
        trapped = !!(here.doormask & D_TRAPPED);
        here.doormask = trapped ? D_NODOOR : D_BROKEN;
        recalc_block_point(mtmp.mx, mtmp.my);
        newsym(mtmp.mx, mtmp.my);
        if (trapped) {
            seeit = canseemon(mtmp);
            if (await mb_trapped(mtmp, sawit || seeit)) {
                newsym(mtmp.mx, mtmp.my);
                return true;
            }
        } else {
            if (game.flags?.verbose) {
                if (!rn2(3))
                    await draft_message(true);
            }
        }
        return false;
    } else if (here.typ === SCORR) {
        here.typ = CORR;
        here.flags = 0;
        unblock_point(mtmp.mx, mtmp.my);
        newsym(mtmp.mx, mtmp.my);
        await draft_message(false);
        return false;
    } else if (!IS_OBSTRUCTED(here.typ) && !IS_TREE(here.typ)) {
        return false;
    }
    if ((here.wall_info & W_NONDIGGABLE) !== 0) {
        const what = IS_WALL(here.typ) ? 'wall'
            : IS_TREE(here.typ) ? 'tree' : 'stone';
        impossible(`mdig_tunnel:  ${what} at (${mtmp.mx},${mtmp.my}) is undiggable`);
        return false;
    }
    if (IS_WALL(here.typ)) {
        if (game.flags?.verbose && !rn2(5)) {
            Soundeffect('se_crashing_rock', 75);
            await You_hear('crashing rock.');
        }
        if (in_rooms(mtmp.mx, mtmp.my, SHOPBASE).length > 0)
            add_damage(mtmp.mx, mtmp.my, 0);
        if (game.level?.flags?.is_maze_lev) {
            here.typ = ROOM;
            here.flags = 0;
        } else if (game.level?.flags?.is_cavernous_lev
                   && !in_town(mtmp.mx, mtmp.my)) {
            here.typ = CORR;
            here.flags = 0;
        } else {
            here.typ = DOOR;
            here.doormask = D_NODOOR;
        }
    } else if (IS_TREE(here.typ)) {
        here.typ = ROOM;
        here.flags = 0;
        if (pile && pile < 5)
            rnd_treefruit_at(mtmp.mx, mtmp.my);
    } else {
        here.typ = CORR;
        here.flags = 0;
        if (pile && pile < 5)
            mksobj_at((pile === 1) ? BOULDER : ROCK, mtmp.mx, mtmp.my, true, false);
    }
    newsym(mtmp.mx, mtmp.my);
    if (!sobj_at(BOULDER, mtmp.mx, mtmp.my))
        unblock_point(mtmp.mx, mtmp.my);
    return false;
}
export async function draft_message(unexpected) {
    if (unexpected) {
        if (!Hallucination())
            await You_feel('an unexpected draft.');
        else
            await You_feel(`like you are ${
                (ACURR(A_STR) < 6 || ACURR(A_DEX) < 6
                 || ACURR(A_CON) < 6 || ACURR(A_CHA) < 6
                 || ACURR(A_INT) < 6 || ACURR(A_WIS) < 6) ? '4-F' : '1-A'
            }.`);
    } else {
        if (!Hallucination()) {
            await You_feel('a draft.');
        } else {
            const draft_reaction = ['enlisting', 'marching', 'protesting', 'fleeing'];
            let dridx = rn1(2, 1 - sgn(game.u.ualign?.type || 0));
            if ((game.u.ualign?.record || 0) < STRIDENT)
                dridx += rn1(3, sgn(game.u.ualign?.type || 0) - 1);
            // clamp to valid range
            dridx = Math.max(0, Math.min(3, dridx));
            await You_feel(`like ${draft_reaction[dridx]}.`);
        }
    }
}
export async function zap_dig() {
    const u = game.u;
    const g = game;
    let trap_with_u = null;
    let flow_x = -1, flow_y = -1;
    let diridx = 8;
    let shopdoor = false, shopwall = false;
    let maze_dig, pitdig = false, pitflow = false;
    if (u.uswallow) {
        const mtmp = u.ustuck;
        if (!is_whirly(mtmp.data)) {
            if (digests(mtmp.data))
                await You(`pierce ${s_suffix(mon_nam(mtmp))} ${mbodypart(mtmp, 18 /* STOMACH */)} wall!`);
            if (unique_corpstat(mtmp.data))
                mtmp.mhp = Math.trunc((mtmp.mhp + 1) / 2);
            else
                mtmp.mhp = 1;
            await expels(mtmp, mtmp.data, !digests(mtmp.data));
        }
        return;
    }
    if (u.dz) {
        if (!Is_airlevel(u.uz) && !Is_waterlevel(u.uz) && !Underwater()) {
            if (u.dz < 0 || On_stairs(u.ux, u.uy)) {
                if (On_stairs(u.ux, u.uy)) {
                    const stway = stairway_at(u.ux, u.uy);
                    await pline_The(`beam bounces off the ${stway?.isladder ? 'ladder' : 'stairs'} and hits the ${ceiling(u.ux, u.uy)}.`);
                }
                await You(`loosen a rock from the ${ceiling(u.ux, u.uy)}.`);
                await pline(`It falls on your ${body_part(HEAD)}!`);
                const dmg = rnd(hard_helmet(g.u.uarmh) ? 2 : 6);
                await losehp(Maybe_Half_Phys(dmg), 'falling rock', KILLED_BY_AN);
                const otmp = mksobj_at(ROCK, u.ux, u.uy, false, false);
                if (otmp) {
                    xname(otmp); // set dknown
                    stackobj(otmp);
                }
                newsym(u.ux, u.uy);
            } else {
                await watch_dig(null, u.ux, u.uy, true);
                await dighole(false, true, null);
            }
        }
        return;
    }
    // normal case: digging across the level
    shopdoor = false;
    shopwall = false;
    maze_dig = g.level?.flags?.is_maze_lev && !Is_earthlevel(u.uz);
    let zx = u.ux + u.dx;
    let zy = u.uy + u.dy;
    if (u.utrap && u.utraptype === TT_PIT
        && (trap_with_u = t_at(u.ux, u.uy))) {
        pitdig = true;
        diridx = xytodir(u.dx, u.dy);
    }
    let digdepth = rn1(18, 8);
    await tmp_at(DISP_BEAM, cmap_to_glyph(S_digbeam));
    while (--digdepth >= 0) {
        if (!isok(zx, zy)) break;
        const room = levl(zx, zy);
        await tmp_at(zx, zy);
        await delay_output();
        if (pitdig) {
            const adjpit = t_at(zx, zy);
            if (diridx !== DIR_ERR
                && !conjoined_pits(adjpit, trap_with_u, false)) {
                digdepth = 0;
                if (!(adjpit && is_pit(adjpit.ttyp))) {
                    const cc = { x: zx, y: zy };
                    const buf = adj_pit_checks(cc);
                    if (buf !== true) {
                        if (buf) await pline(buf);
                    } else {
                        await dighole(true, true, { x: zx, y: zy });
                    }
                }
                const adjpit2 = t_at(zx, zy);
                if (adjpit2 && is_pit(adjpit2.ttyp)) {
                    const adjidx2 = DIR_180(diridx);
                    trap_with_u.conjoined |= (1 << diridx);
                    adjpit2.conjoined |= (1 << adjidx2);
                    flow_x = zx;
                    flow_y = zy;
                    pitflow = true;
                }
                if (is_pool(zx, zy) || is_lava(zx, zy)) {
                    flow_x = zx - u.dx;
                    flow_y = zy - u.dy;
                    pitflow = true;
                }
                break;
            }
        } else if (closed_door(zx, zy) || room.typ === SDOOR) {
            if (in_rooms(zx, zy, SHOPBASE).length > 0) {
                add_damage(zx, zy, SHOP_DOOR_COST);
                shopdoor = true;
            }
            if (room.typ === SDOOR)
                room.typ = DOOR;
            else if (cansee(zx, zy))
                await pline_The('door is razed!');
            await watch_dig(null, zx, zy, true);
            room.doormask = D_NODOOR;
            recalc_block_point(zx, zy);
            digdepth -= 2;
            if (maze_dig) break;
        } else if (maze_dig) {
            if (IS_WALL(room.typ)) {
                if (!(room.wall_info & W_NONDIGGABLE)) {
                    if (in_rooms(zx, zy, SHOPBASE).length > 0) {
                        add_damage(zx, zy, SHOP_WALL_COST);
                        shopwall = true;
                    }
                    room.typ = ROOM;
                    room.flags = 0;
                    unblock_point(zx, zy);
                } else if (!Blind()) {
                    await pline_The('wall glows then fades.');
                }
                break;
            } else if (IS_TREE(room.typ)) {
                if (!(room.wall_info & W_NONDIGGABLE)) {
                    room.typ = ROOM;
                    room.flags = 0;
                    unblock_point(zx, zy);
                } else if (!Blind()) {
                    await pline_The('tree shudders but is unharmed.');
                }
                break;
            } else if (room.typ === STONE || room.typ === SCORR) {
                if (!(room.wall_info & W_NONDIGGABLE)) {
                    room.typ = CORR;
                    room.flags = 0;
                    unblock_point(zx, zy);
                } else if (!Blind()) {
                    await pline_The('rock glows then fades.');
                }
                break;
            }
        } else if (IS_OBSTRUCTED(room.typ)) {
            if (!may_dig(zx, zy)) break;
            if (IS_WALL(room.typ) || room.typ === SDOOR) {
                if (in_rooms(zx, zy, SHOPBASE).length > 0) {
                    add_damage(zx, zy, SHOP_WALL_COST);
                    shopwall = true;
                }
                await watch_dig(null, zx, zy, true);
                if (g.level?.flags?.is_cavernous_lev && !in_town(zx, zy)) {
                    room.typ = CORR;
                    room.flags = 0;
                } else {
                    room.typ = DOOR;
                    room.doormask = D_NODOOR;
                }
                digdepth -= 2;
            } else if (IS_TREE(room.typ)) {
                room.typ = ROOM;
                room.flags = 0;
                digdepth -= 2;
            } else {
                room.typ = CORR;
                room.flags = 0;
                digdepth--;
            }
            unblock_point(zx, zy);
        }
        zx += u.dx;
        zy += u.dy;
    }
    await tmp_at(DISP_END, 0);
    if (pitflow && isok(flow_x, flow_y)) {
        const ttmp = t_at(flow_x, flow_y);
        if (ttmp && is_pit(ttmp.ttyp)) {
            const filltyp = fillholetyp(ttmp.tx, ttmp.ty, true);
            if (filltyp !== ROOM)
                await pit_flow(ttmp, filltyp);
        }
    }
    if (shopdoor || shopwall)
        await pay_for_damage(shopdoor ? 'destroy' : 'dig into', false);
}
// adj_pit_checks: returns true if OK to dig, or a string message if not
function adj_pit_checks(cc) {
    if (!cc || !isok(cc.x, cc.y)) return false;
    const room = levl(cc.x, cc.y);
    const ltyp = room.typ;
    const foundation_msg = 'The foundation is too hard to dig through from this angle.';
    if (is_pool(cc.x, cc.y) || is_lava(cc.x, cc.y)) {
        return false;
    } else if (closed_door(cc.x, cc.y) || room.typ === SDOOR) {
        return foundation_msg;
    } else if (IS_WALL(ltyp)) {
        return foundation_msg;
    } else if (IS_TREE(ltyp)) {
        return "The tree's roots glow then fade.";
    } else if (ltyp === STONE || ltyp === SCORR) {
        if (room.wall_info & W_NONDIGGABLE) {
            return 'The rock glows then fades.';
        }
    } else if (ltyp === IRONBARS) {
        return 'The bars go much deeper than your pit.';
    } else if (IS_SINK(ltyp)) {
        return 'A tangled mass of plumbing remains below the sink.';
    } else if (On_ladder(cc.x, cc.y)) {
        return 'The ladder is unaffected.';
    } else {
        let supporting = null;
        if (IS_FOUNTAIN(ltyp)) supporting = 'fountain';
        else if (IS_THRONE(ltyp)) supporting = 'throne';
        else if (IS_ALTAR(ltyp)) supporting = 'altar';
        else if (On_stairs(cc.x, cc.y)) supporting = 'stairs';
        else if (ltyp === DRAWBRIDGE_DOWN || ltyp === DBWALL) supporting = 'drawbridge';
        if (supporting) {
            return `The ${s_suffix(supporting)} supporting structures remain intact.`;
        }
    }
    return true;
}
async function pit_flow(trap, filltyp) {
    if (trap && filltyp !== ROOM && is_pit(trap.ttyp)) {
        const t = { ...trap, tx: trap.tx, ty: trap.ty, conjoined: trap.conjoined };
        const loc = levl(t.tx, t.ty);
        loc.typ = filltyp;
        loc.flags = 0;
        const fillmsg = u_at(t.tx, t.ty)
            ? 'Suddenly %s flows in from the adjacent pit!'
            : null;
        await liquid_flow(t.tx, t.ty, filltyp, trap, fillmsg);
        for (let idx = 0; idx < N_DIRS; ++idx) {
            if (t.conjoined & (1 << idx)) {
                const nx = t.tx + xdir[idx];
                const ny = t.ty + ydir[idx];
                const t2 = t_at(nx, ny);
                await pit_flow(t2, filltyp);
            }
        }
    }
}
export function buried_ball(cc) {
    const u = game.u;
    let bdist = COLNO;
    let ball = null;
    if (!u.utrap || u.utraptype === TT_BURIEDBALL) {
        let otmp = game.level?.buriedobjlist;
        while (otmp) {
            if (otmp.otyp === HEAVY_IRON_BALL) {
                if (otmp.ox === cc.x && otmp.oy === cc.y)
                    return otmp;
                const dx = otmp.ox - cc.x, dy = otmp.oy - cc.y;
                const odist = dx * dx + dy * dy;
                if (odist <= 8 && (!ball || odist < bdist)) {
                    ball = otmp;
                    bdist = odist;
                }
            }
            otmp = otmp.nobj;
        }
    }
    if (ball) {
        cc.x = ball.ox;
        cc.y = ball.oy;
    }
    return ball;
}
export async function buried_ball_to_punishment() {
    const cc = { x: game.u.ux, y: game.u.uy };
    const ball = buried_ball(cc);
    if (ball) {
        obj_extract_self(ball);
        await punish(ball);
        await reset_utrap(false);
        del_engr_at(cc.x, cc.y);
        newsym(cc.x, cc.y);
    }
}
export async function buried_ball_to_freedom() {
    const cc = { x: game.u.ux, y: game.u.uy };
    const ball = buried_ball(cc);
    if (ball) {
        obj_extract_self(ball);
        place_object(ball, cc.x, cc.y);
        stackobj(ball);
        await reset_utrap(true);
        del_engr_at(cc.x, cc.y);
        newsym(cc.x, cc.y);
    }
}
export function bury_an_obj(otmp, dealloced_ref) {
    const u = game.u;
    if (dealloced_ref) dealloced_ref.value = false;
    const otmp2 = otmp.nexthere;
    if (otmp === game.u.uball) {
        // unpunish();
        set_utrap(rn1(50, 20), TT_BURIEDBALL);
        // pline_The('iron ball gets buried!'); — sync context, skip await
    }
    if (otmp === game.u.uchain || obj_resists(otmp, 0, 0))
        return otmp2;
    if (otmp.otyp === LEASH && otmp.leashmon)
        o_unleash(otmp);
    if (otmp.lamplit && otmp.otyp !== POT_OIL)
        end_burn(otmp, true);
    obj_extract_self(otmp);
    const under_ice = is_ice(otmp.ox, otmp.oy);
    if ((otmp.otyp === ROCK && !under_ice) || otmp.otyp === BOULDER) {
        if (dealloced_ref) dealloced_ref.value = true;
        obfree(otmp, null);
        return otmp2;
    }
    if (otmp.otyp === CORPSE) {
        ; // should cancel timer if under_ice
    } else if ((under_ice ? (otmp.oclass === POTION_CLASS) : is_organic(otmp))
               && !obj_resists(otmp, 5, 95)) {
        start_timer((under_ice ? 0 : 250) + rnd(250),
                    TIMER_OBJECT, ROT_ORGANIC, otmp);
    }
    add_to_buried(otmp);
    return otmp2;
}
export async function bury_objs(x, y) {
    const shkp = shop_keeper(in_rooms(x, y, SHOPBASE));
    const costly = shkp && costly_spot(x, y);
    let loss = 0;
    let otmp = game.level?.objects?.[x]?.[y];
    while (otmp) {
        if (costly && !game.context?.mon_moving) {
            loss += await stolen_value(otmp, x, y, !!shkp?.mpeaceful, true);
            if (otmp.oclass !== COIN_CLASS)
                otmp.no_charge = 1;
        }
        otmp = bury_an_obj(otmp, null);
    }
    del_engr_at(x, y);
    newsym(x, y);
    maybe_unhide_at(x, y);
    if (costly && loss) {
        await You(`owe ${shkname(shkp)} ${loss} ${currency(loss)} for burying merchandise.`);
    }
}
export async function unearth_objs(x, y) {
    const cc = { x, y };
    const bball = buried_ball(cc);
    let otmp = game.level?.buriedobjlist;
    while (otmp) {
        const otmp2 = otmp.nobj;
        if (otmp.ox === x && otmp.oy === y) {
            if (bball && otmp === bball
                && game.u.utrap && game.u.utraptype === TT_BURIEDBALL) {
                await buried_ball_to_punishment();
            } else {
                obj_extract_self(otmp);
                if (otmp.timed)
                    stop_timer(ROT_ORGANIC, otmp);
                place_object(otmp, x, y);
                stackobj(otmp);
            }
        }
        otmp = otmp2;
    }
    del_engr_at(x, y);
    newsym(x, y);
}
export function rot_organic(arg, _timeout) {
    // C: arg->a_obj; JS: obj stored directly (no union wrapper)
    const obj = arg;
    while (Has_contents(obj)) {
        obj.cobj.ox = obj.ox;
        obj.cobj.oy = obj.oy;
        bury_an_obj(obj.cobj, null);
    }
    obj_extract_self(obj);
    obfree(obj, null);
}
export async function rot_corpse(arg, timeout) {
    let x = 0, y = 0;
    // C: arg->a_obj; JS: start_corpse_timeout stores obj directly (no union wrapper)
    const obj = arg;
    const on_floor = obj.where === OBJ_FLOOR;
    const in_invent = obj.where === OBJ_INVENT;
    if (on_floor) {
        x = obj.ox;
        y = obj.oy;
    } else if (in_invent) {
        if (game.flags?.verbose) {
            // message about rotting — simplified
        }
        if (obj.owornmask) {
            await remove_worn_item(obj, true);
            await stop_occupation();
        }
    } else if (obj.where === OBJ_MINVENT) {
        if (obj.owornmask && obj === MON_WEP(obj.ocarry))
            setmnotwielded(obj.ocarry, obj);
    } else if (obj.where === OBJ_MIGRATING) {
        obj.owornmask = 0;
    }
    rot_organic(arg, timeout);
    if (on_floor) {
        const mtmp = m_at(x, y);
        if (mtmp && !OBJ_AT(x, y) && mtmp.mundetected
            && hides_under(mtmp.data)) {
            mtmp.mundetected = 0;
        }
        newsym(x, y);
    } else if (in_invent) {
        update_inventory();
    }
}