All files / js monmove.js

75.96% Statements 1400/1843
74.97% Branches 674/899
75.38% Functions 49/65
75.96% Lines 1400/1843

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 184473x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x               73x 8113x 8113x 8113x 8113x 17x 17x 17x 17x       14x 14x 14x 14x 14x 14x 14x 14x 14x       14x                                 14x 73x 15066x 15066x 15066x 4262x 4262x 4262x 73x 296x 296x 296x 91x 296x 201x                   91x 296x 73x 4231x 4231x 4231x 4231x 4231x 73x 39x 39x 39x 39x 39x 39x 39x 39x 1656x 1656x 1656x 73x 8763x 8763x 8763x 8763x 8763x 35903x 35903x 35903x 35903x 35903x       35903x 35903x 20159x 20159x 35903x 35903x 35903x 8763x 8763x 8763x 8763x                                                     73x 73x 73x 73x 73x                         73x 73x 73x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 398x 73x 73x 73x 73x 73x 73x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3626x 3886x 3886x 3886x 3623x 3886x 73x 3167x 3167x 3167x 3167x 3167x 3167x           3167x 3167x 73x 115x 115x 115x 115x 115x 115x 115x 554x 554x 554x 73x                                                         73x 3886x 3886x 3886x 2659x 2659x 2659x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 3886x 14x 3886x 3673x 3872x 199x 199x 3886x 3886x 3886x 3886x 73x 3887x 3887x 3887x 3887x 3887x 3887x 3887x 3887x 73x 73x 73x 73x 73x 73x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 7884x 85292x 877154x 877154x 9162x 873203x 9124x 866519x 7946x 877154x 7658x 7658x 866435x 1032x 877154x 877154x 7257x 866435x 7212x 7212x 877154x 63x       63x 63x 7149x 866435x 3249x 3249x 492270x 3382x 3382x 3292x 3382x 3292x 3382x 3291x 3382x 3382x 3382x 124x 124x 124x 124x 5x 5x 5x 119x 119x 119x 3382x 3244x 85287x 7879x 7884x 21x 12x 12x 13x 9x 9x 21x 7879x 7884x 7654x 7654x 7654x     7654x 7654x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 290x 8817x 8817x 8817x 8817x 8817x         287x 6655x 8817x 8817x 271x 8817x       73x 73x 73x         73x 73x 73x 73x 13963x     13963x 41889x 41889x 13963x 13963x 73x 82x 82x 73x 73x 73x 73x 73x                                       73x 73x 73x 73x 105116x 105116x 105116x 105116x 105116x 1x 1x 105115x 105115x 105116x 14594x 14594x 90521x 105116x 105116x     105116x 105116x 105116x 105116x     105116x 90400x 90400x 6x 6x 105x 105116x 105116x 105116x 105116x 105116x 105116x 6x 6x   105116x 73x 73x 73x 73x                                     73x 73x 73x 73x 3071x 3071x 3071x 3071x 7x 7x 7x 3071x 3071x 3071x 3071x 3071x 7x 7x 3071x   2783x 7x 7x 6x 6x 1x 1x 3071x 73x 73x 73x 73x 1673174x 1673174x 1673174x 1673174x 1673174x 73x 73x 73x 4075x 4075x 3660x 3660x 4075x 4075x 4075x 4075x 73x 73x 73x 73x 49918x 49918x 49918x 49918x 93x 93x 93x 93x 37x 37x 93x 49918x 73x 8762x 8762x 8762x 8762x 8762x   8762x 2x 2x 8762x 73x 292x 292x 292x 292x 292x 47x 47x 292x 2x 2x 2x 245x 292x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x   73x 73x 73x 14376x 14376x 14376x 14376x 14376x 14376x 14303x 14303x 14376x 14376x 14376x 14376x 14376x 14376x 14376x 2x 152x 1x 1x 1x 2x 2x 2x 14376x 73x 73x 73x 73x 30675x 30675x 30675x 30675x 30675x 24719x 24719x 24719x 24719x 30675x 30675x 30675x 30675x 30675x   30675x 5x 5956x 1051x 5951x 4900x 4900x 7215x 4900x 4900x 4900x 4900x 30675x 30675x 801x 801x 1739x         1739x 1739x 801x 801x 801x 1739x 1739x 1656x 1739x 801x 2569x 255x 255x 255x 1056x 1056x 30675x 73x 73x 73x 73x 30830x 30830x 30830x 30830x 30830x 30830x 30830x 30830x 30830x 30830x 30830x 30830x 30830x 14x 14x 30830x 30816x 30816x 30816x 30830x 30830x 30830x 30830x 6x 30830x 30830x 30830x 3986x 30830x           30830x 30830x 30830x 30830x 30830x 30830x 30830x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                                       73x 73x 73x 73x                                                                                                                                                                             73x 73x 73x 73x 15011x 15011x 15011x 15011x 14306x 14306x 14306x 14306x 14306x 14306x 14306x 14306x 7x 7x 7x 14299x 14306x 14306x 629x 629x 629x 629x 629x 19x 19x 19x 19x 19x 19x 19x 629x 629x                     629x 19x 19x 18x   18x 3x 17x 15x 15x 18x 19x 629x 14299x 14306x 14306x     14299x 14299x 14299x 15004x 15011x 15011x 554x 554x       554x 554x 554x 15011x 14376x 14376x 15004x 15011x 14376x 295x 259x 259x 295x 295x 14376x 15004x 15011x 73x 554x 554x 554x 554x 542x 554x 554x 539x 539x 554x 545x 595x 595x 595x 595x 31x 206x 31x 31x 193x 26x 595x 595x 154x 5x 5x 5x 5x 26x 26x 26x 26x 26x 26x 26x 26x 513x 554x 73x 73x 73x 73x 19362x 19362x 19362x 19362x 19362x 19362x 19362x 19362x 19362x 19362x 19362x 168x 19362x 19362x 19362x 19353x 19362x 73x 73x 73x 73x 19353x 19353x 19353x 19353x 19353x 3x 3x 19353x 19353x 791x     791x 791x 791x 791x 4x 4x 791x 791x 18562x 19353x 3071x 3070x     3070x 3070x 3071x 15492x 15492x 15492x 19353x 19353x 15492x 19353x 19353x 15492x 15492x 19353x 19353x       15492x 15492x 15492x 19353x 15490x 15490x 19353x 19353x 19353x 15490x 15490x 19353x 19353x 19353x                 15490x 15490x 19353x 1x 1x 1x 1x 1x 15490x 15490x 15490x 15490x 19353x     19353x 5x 5x 5x 15485x 15485x 15485x 15485x 15485x 19353x 19353x 19353x 19353x                                     15485x 19353x 14x 14x 15485x 15485x 15485x 15485x 15485x 19353x 19353x 19353x 64x 64x 64x 64x 49x 49x 49x 49x 64x 19353x 19353x 19353x 19353x 19353x 19353x 19353x 19353x 19353x 19353x 19353x 15354x 15354x 15354x 15354x 6100x 6100x 6100x 36568x 36568x 36568x 460x 460x 8x 8x 8x 460x 36568x 6100x 6100x 15354x 15346x 15340x 15348x 15348x 15354x 15354x 15343x 15345x 15340x 15340x 15340x 15354x 15466x 15466x 15466x 15466x 19199x 15340x 15340x 15340x 15340x 15466x 15466x 19353x 45x 19353x 19353x 19353x 1185x 1185x 1185x 1185x 19353x 14278x 14278x 14278x 14278x 14278x 14278x 12219x 14278x 14278x 11512x 14278x 11512x 19353x 3x 19353x 3951x 3951x 3951x 19353x 2178x 2178x 933x 933x 933x 2178x 19353x 19353x 73x 73x 73x 73x 73x 73x 73x 73x 73x 26x 26x 26x 26x 26x 25x 25x 25x 25x 26x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 73x 73x 73x 73x 15346x 15346x 15346x 15346x 15340x 15340x 15346x 15346x 15346x 15346x 182x 182x         182x 181x 181x 181x 182x 15165x 15346x 20x 20x 20x 20x 15145x 15145x 15145x 15346x 15346x 79x 79x 79x 15066x 15346x 15346x 15346x 15346x 15346x 15346x 1x 1x 15066x 15346x 5527x 5527x 5527x 5527x 5527x 5523x 5523x 5523x 5523x 5523x 9539x 15346x 722x 722x 722x 108x 722x 722x       722x       721x 721x 721x 721x 721x 722x 8817x 15346x 15346x 15346x 15346x 15346x 15346x 15346x   15262x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8803x 8803x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8817x 8204x 8204x 686x 686x 686x 8204x 8817x 8817x 15346x 8056x 8056x 8056x 8056x 8056x 7884x 7884x 8056x 8817x 15346x 7884x 7884x 5x 5x 5x 5x 5x 5x 5x 5x 7879x 7879x 7879x 7879x 8812x 8812x 8812x 8812x 8812x 8812x 15346x 49x 3x 3x 3x 45x 45x 45x 15262x       8763x 8763x 8763x 8763x 8763x 8763x 9327x 15346x 15346x 8763x 8763x 8763x 15346x               8763x 8763x 15262x 35903x 35903x 35903x 35903x 35903x 35903x 35903x 35903x 35903x 35903x 35903x     35903x 35903x 29958x 29958x 82676x 82676x 8296x 7667x 7667x 7667x 8296x 82676x 29958x 29958x 28236x 28236x 28236x 35903x 5945x 5945x 5945x 5945x 35903x 35903x 35903x 18857x 18857x 35903x 35903x 16628x 16628x 16628x 16628x 16628x 16628x 35903x 15346x 1x 1x 1x 8762x 15346x 8762x 8762x       8762x       8762x         8762x                           8762x 8762x 8762x 8762x       8762x 8762x 8762x 8762x 8762x 8762x 8762x 8762x 8762x 8762x 8762x 8762x 8762x           15346x 73x 73x                                           73x 73x 73x 73x 73x 73x 73x 8x         8x 8x 8x 8x 8x 7x 7x             7x 8x 8x 8x 6x 6x                   6x 6x 6x 8x 8x                 8x 8x 73x 73x 73x 73x 73x 61074x 61074x 61074x 61074x 61074x 61074x 61074x 61074x 61071x 61074x 73x 73x 73x 73x 25168x 25168x 25168x 25168x 25168x 25168x 25168x 25168x 25168x 25168x 25168x 25168x 25168x 25168x 25168x 73x  
// monmove.js -- Monster movement AI (port of monmove.c)
// C ref: monmove.c -- 2415 lines
//
// Functions ported:
//   dochugw, dochug, m_move, mfndpos, distfleeck, monflee,
//   set_apparxy, postmov, mon_track_add, mon_track_clear,
//   mb_trapped, onscary, mon_regen, disturb, m_move_aggress,
//   closed_door, m_everyturn_effect, m_postmove_effect,
//   dochug helpers: watch_on_duty, m_arrival, mind_blast, etc.
import { game } from './gstate.js';
import { Amonnam, DEADMONSTER, check_gear_next_turn, gettrack, has_attacktype, hideunder, hideunder_with_message, m_digweapon_check, m_respond, maybe_unhide_at, mfndpos, mon_allowflags, mon_nam, mon_wield_item, mondead, mondied, monflee, Monnam, monsterSubjectName, set_ustuck, sticks_attack, stop_occupation, wake_nearby, wake_nearto, wakeup, m_in_air } from './mon.js';
import { formatMonsterEventRef, rn2, rnd, rn1, c_d, pushRngLogEntry } from './rng.js';
import { assertNotInModal } from './modal_guard.js';
import { couldsee, cansee, clear_path, vision_recalc } from './vision.js';
import { db_under_typ } from './dbridge.js';
import { Conflict, Deaf, Displaced, Hallucination, In_endgame, Inhell, Invis, Sokoban, Underwater, Upolyd, U_AP_TYPE, is_rogue_level } from './macros.js';
import { attacktype, can_teleport, can_track, hides_under, is_animal, is_covetous, is_demon, is_greedy as likes_gold, is_mercenary, is_mindless, is_pick, is_pole, is_rider, is_undead, is_unicorn, is_vampshifter, is_wanderer, is_watch, likes_gems, likes_magic, likes_objs, m_cansee, m_canseeu, mdistu, mon_hates_silver, mon_knows_traps, mon_learns_traps, needspick, noattacks, passes_walls, perceives, resist_conflict, resists_ston, sticks, throws_rocks, touch_petrifies, tunnels, unique_corpstat, webmaker } from './mondata.js';
import { helpless, money_cnt } from './hack.js';
import { artifact_light } from './light.js';
import { inhistemple, in_your_sanctuary } from './priest.js';
import { quest_talk } from './quest.js';
import { A_STR, ACCFOOD, ACCESSIBLE, ALL_TRAPS, ALLOW_M, ALLOW_MDISP, ALLOW_SANCT, ALLOW_SSM, ALLOW_TRAPS, ALLOW_U, BOLT_LIM, COLNO, CORR, D_BROKEN, D_CLOSED, D_ISOPEN, D_LOCKED, D_NODOOR, D_TRAPPED, D_WARNED, DART_TRAP, DOOR, DRAWBRIDGE_UP, EDOG, engulfing_u, has_edog, IRONBARS, IS_ALTAR, IS_DOOR, IS_LAVA, IS_OBSTRUCTED, IS_POOL, IS_ROOM, IS_WALL, is_pit, isok, LADDER, M_AP_FURNITURE, M_AP_OBJECT, M_AP_TYPE, MAGIC_TRAP, MANFOOD, M_ATTK_AGR_DIED, M_ATTK_DEF_DIED, M_ATTK_HIT, MMOVE_DIED, MMOVE_DONE, MMOVE_MOVED, MMOVE_NOMOVES, MMOVE_NOTHING, MON_FLOOR, MON_POLE_DIST, MTSZ, NEED_HTH_WEAPON, NEED_WEAPON, NOTONL, NO_TRAP, NORMAL_SPEED, OBJ_FLOOR, PIT, RLOC_MSG, ROOM, ROWNO, SHOPBASE, SPIKED_PIT, SQKY_BOARD, STAIRS, STATUE_TRAP, STRAT_CLOSE, STRAT_WAITFORU, STRAT_WAITMASK, u_at, VIBRATING_SQUARE, W_ARMOR, W_ARMG, W_NONDIGGABLE, WEB } from './const.js';
import { AMULET_CLASS, AMULET_OF_STRANGULATION, ARMOR_CLASS, BALL_CLASS, BELL_OF_OPENING, BOULDER, CLOAK_OF_DISPLACEMENT, COIN_CLASS, CORPSE, CREDIT_CARD, DART, FOOD_CLASS, GEM_CLASS, GEMSTONE, GOLD_PIECE, is_metallic, is_rustprone, LOCK_PICK, MINERAL, POTION_CLASS, RING_CLASS, RIN_SLOW_DIGESTION, ROCK, ROCK_CLASS, SCR_SCARE_MONSTER, SCROLL_CLASS, SILVER, SKELETON_KEY, SPBOOK_CLASS, STRANGE_OBJECT, WAND_CLASS, WEAPON_CLASS } from './objects.js';
import { AD_CLRC, AD_DRCO, AD_DRDX, AD_DRST, AD_ELEC, AD_PHYS, AD_SAMU, AD_SPEL, AD_STCK, AT_BITE, AT_BUTT, AT_CLAW, AT_ENGL, AT_HUGS, AT_KICK, AT_MAGC, AT_STNG, AT_TENT, AT_TUCH, AT_WEAP, M1_AMORPHOUS, M1_NOHANDS, M1_NOTAKE, M2_ROCKTHROW, M2_STRONG, M2_UNDEAD, MS_BRIBE, mons, MZ_HUMAN, MZ_TINY, PM_ANGEL, PM_BABY_PURPLE_WORM, PM_DISPLACER_BEAST, PM_ETTIN, PM_FOG_CLOUD, PM_GELATINOUS_CUBE, PM_GHOUL, PM_GIANT_SPIDER, PM_GREMLIN, PM_GRID_BUG, PM_HEZROU, PM_JABBERWOCK, PM_LEPRECHAUN, PM_MINOTAUR, PM_PIRANHA, PM_PURPLE_WORM, PM_RUST_MONSTER, PM_STALKER, PM_STEAM_VORTEX, PM_XORN, S_BAT, S_DOG, S_EEL, S_FUNGUS, S_HUMAN, S_LEPRECHAUN, S_LIGHT, S_NYMPH, S_VAMPIRE } from './monsters.js';
import { bot, canspotmon, canseemon, flush_screen, newsym, recalc_block_point, setBotl } from './display.js';
import { nomul } from './cmd.js';
import { dist2, distmin, distu, MON_WEP, monnear, sgn } from './hacklib.js';
import { m_at as map_m_at, obj_at, t_at } from './map_access.js';
import { count_traps, m_harmless_trap, maketrap, mintrap } from './trap.js';
import { is_digging, mdig_tunnel, watch_dig } from './dig.js';
import { mksobj, mksobj_at, obj_extract_self, place_object, sobj_at, vobj_at, weight } from './mkobj.js';
import { create_gas_cloud, m_in_out_region, visible_region_at } from './region.js';
import { inhishop, in_rooms } from './shk.js';
import { stairway_at, stairway_find_dir } from './stairs.js';
import { find_mac } from './worn.js';
import { an, distant_name, doname } from './objnam.js';
import { ACURR, ACURRSTR } from './attrib.js';
import { autoreturn_weapon, lined_up, m_carrying, m_has_launcher_and_ammo, select_rwep } from './mthrowu.js';
import { can_carry, could_reach_item, dogfood } from './dogmove.js';
import { add_damage, costly_spot } from './shk.js';
import { find_defensive, find_misc, find_offensive, searches_for_item, use_defensive, use_misc, use_offensive } from './muse.js';
import { touch_artifact } from './artifact.js';
import { goodpos, enexto } from './makemon.js';
import { noteleport_level, rloc, rloc_to_flag, tele_restrict } from './teleport.js';
import { tactics } from './wizard.js';
import { expels, mattacku as mattacku_canonical, mdamageu as mdamageu_real, ranged_attk_available } from './mhitu.js';
import { mattackm, mdisplacem } from './mhitm.js';
import { findgold, mpickobj } from './steal.js';
import { fobj_at } from './pickup.js';
import { sengr_at, wipe_engr_at } from './engrave.js';
import { demon_talk, is_lminion } from './minion.js';
import { set_malign } from './dog.js';
import { angry_guards, in_town } from './mklev.js';
import { picking_lock } from './lock.js';
import { place_monster, remove_monster } from './steed.js';
import { remove_worm } from './worm.js';
import { worm_move, worm_nomove } from './worm.js';
import { obj_resists } from './zap.js';
import { delobj } from './invent.js';
// ============================================================================
// Utility predicates (from C's monmove.c and support headers)
// ============================================================================
function nodiag(mtmp) {
    return mtmp?.mnum === PM_GRID_BUG;
}
function monster_can_open_doors(mtmp) {
    const data = mtmp?.data;
    return !!data && !(data.mflags1 & M1_NOHANDS) && data.msize > MZ_TINY;
}
// is_rogue_level: imported from macros.js
function is_shop_square(x, y) {
    const rooms = in_rooms(x, y, SHOPBASE);
    return Array.isArray(rooms) ? rooms.length > 0 : !!rooms;
}
function may_dig_local(x, y) {
    const loc = game.level?.at?.(x, y);
    return !!loc && !(loc.wall_info & W_NONDIGGABLE);
}
async function mon_yells_local(mtmp, msg) {
    await pline(`${Monnam(mtmp)} yells: "${msg}"`);
}
async function watch_on_duty_local(mtmp) {
    const u = game.u;
    if (!mtmp.mpeaceful
        || !in_town((u.ux ?? 0) + (u.dx ?? 0), (u.uy ?? 0) + (u.dy ?? 0))
        || !mtmp.mcansee
        || !m_canseeu(mtmp)
        || rn2(3)) {
        return;
    }
    const pick = { x: 0, y: 0 };
    if (picking_lock(pick)
        && IS_DOOR(game.level?.at(pick.x, pick.y)?.typ ?? 0)
        && ((game.level?.at(pick.x, pick.y)?.doormask ?? 0) & D_LOCKED)) {
        if (couldsee(mtmp.mx, mtmp.my)) {
            const loc = game.level?.at(pick.x, pick.y);
            if ((loc?.looted ?? 0) & D_WARNED) {
                await mon_yells_local(mtmp, "Halt, thief!  You're under arrest!");
                angry_guards(!!Deaf());
            } else {
                await mon_yells_local(mtmp, "Hey, stop picking that lock!");
                if (loc) loc.looted = (loc.looted || 0) | D_WARNED;
            }
            await stop_occupation();
        }
    } else if (is_digging()) {
        const dpos = game.context?.digging?.pos;
        if (dpos)
            await watch_dig(mtmp, dpos.x, dpos.y, false);
    }
}
// is_wanderer — imported from mondata.js
function nohands_fn(ptr) {
    return !!(ptr?.mflags1 & M1_NOHANDS);
}
function verysmall_fn(ptr) {
    return (ptr?.msize ?? 0) <= MZ_TINY;
}
// C ref: monmove.c:2141 can_hide_under_obj()
function can_hide_under_obj_local(obj) {
    if (!obj) return false;
    if (obj.where != null && obj.where !== OBJ_FLOOR) return false;
    const trap = t_at(obj.ox, obj.oy);
    if (trap && !is_pit(trap.ttyp)) return false;
    if (obj.oclass === COIN_CLASS) {
        let coinquan = 0;
        let cur = obj;
        while (cur && cur.oclass === COIN_CLASS) {
            coinquan += Number(cur.quan) || 0;
            if (coinquan >= 10) break;
            cur = cur.nexthere || null;
        }
        if (coinquan < 10) return false;
    }
    return true;
}
// C ref: monmove.c:97 monhaskey — check if monster has a key/lockpick/credit card
function monhaskey_fn(mtmp, for_unlocking = true) {
    if (for_unlocking && m_carrying(mtmp, CREDIT_CARD))
        return true;
    return !!m_carrying(mtmp, SKELETON_KEY) || !!m_carrying(mtmp, LOCK_PICK);
}
// passes_walls: imported from mondata.js
function can_ooze_fn(mtmp) {
    return !!(mtmp?.data?.mflags1 & M1_AMORPHOUS);
}
function can_fog_fn(mtmp) {
    // C ref: monmove.c can_fog() — full inventory gate not ported here yet.
    // Shape-shifted vampires can slip under closed doors.
    return !!mtmp && is_vampshifter(mtmp);
}
function accessible_monmove(x, y) {
    return accessible(x, y);
}
// C ref: monmove.c:1091 should_displace()
function should_displace(mtmp, positions, ggx, ggy) {
    let shortestWithDisplacing = -1;
    let shortestWithoutDisplacing = -1;
    let countWithoutDisplacing = 0;
    for (let i = 0; i < positions.length; i++) {
        const nx = positions[i].x;
        const ny = positions[i].y;
        const info = positions[i].info || 0;
        const ndist = dist2(nx, ny, ggx, ggy);
        if (map_m_at(nx, ny) && (info & ALLOW_MDISP) && !(info & ALLOW_M)) {
            if (shortestWithDisplacing === -1 || ndist < shortestWithDisplacing) {
                shortestWithDisplacing = ndist;
            }
        } else {
            if (shortestWithoutDisplacing === -1 || ndist < shortestWithoutDisplacing) {
                shortestWithoutDisplacing = ndist;
            }
            countWithoutDisplacing++;
        }
    }
    return shortestWithDisplacing > -1
        && (shortestWithDisplacing < shortestWithoutDisplacing
            || !countWithoutDisplacing);
}
function line_clear_between(x1, y1, x2, y2, allowBlockedTarget = false) {
    const level = game.level;
    if (!level) return false;
    if (x1 === x2 && y1 === y2) return true;
    const dx = x2 - x1;
    const dy = y2 - y1;
    const steps = Math.max(Math.abs(dx), Math.abs(dy));
    let prevX = x1;
    let prevY = y1;
    for (let i = 1; i <= steps; i++) {
        const x = Math.round(x1 + (dx * i) / steps);
        const y = Math.round(y1 + (dy * i) / steps);
        if (x === prevX && y === prevY) continue;
        prevX = x;
        prevY = y;
        const loc = level.at(x, y);
        if (!loc) return false;
        if (x === x2 && y === y2) {
            return allowBlockedTarget || ACCESSIBLE(loc.typ);
        }
        if (!ACCESSIBLE(loc.typ)) {
            return false;
        }
    }
    return true;
}
// has_attacktype: imported from mon.js
// sticks_attack: imported from mon.js
// Use canonical Monnam/mon_nam for proper pet naming via mextra.mgivenname
// monsterSubjectName: imported from mon.js
// is_undead — imported from mondata.js
function findgold_invent() {
    for (let obj = game.invent; obj; obj = obj.nobj) {
        if (obj.oclass === COIN_CLASS) return obj; // COIN_CLASS
    }
    return null;
}
function findgold_minvent(mtmp) {
    for (let obj = mtmp?.minvent; obj; obj = obj.nobj) {
        if (obj.oclass === COIN_CLASS) return obj;
    }
    return null;
}
// C ref: monmove.c m_cansee — monster line of sight check
// m_cansee: imported from mondata.js
export async function can_touch_safely(mtmp, otmp) {
    const otyp = otmp.otyp;
    const mdat = mtmp.data;
    if (otyp === CORPSE && otmp.corpsenm !== undefined
        && touch_petrifies(mons[otmp.corpsenm])
        && !(mtmp.misc_worn_check & W_ARMG) && !resists_ston(mtmp))
        return false;
    if (otyp === CORPSE && otmp.corpsenm !== undefined
        && is_rider(mons[otmp.corpsenm]))
        return false;
    if ((game.objects[otyp]?.oc_material ?? 0) === SILVER && mon_hates_silver(mtmp)
        && (otyp !== BELL_OF_OPENING || !is_covetous(mdat)))
        return false;
    if (!(await touch_artifact(otmp, mtmp)))
        return false;
    return true;
}
// C ref: monmove.c practical[] and magical[] item class lists
const practical = [WEAPON_CLASS, ARMOR_CLASS, GEM_CLASS, FOOD_CLASS];
const magical = [AMULET_CLASS, POTION_CLASS, SCROLL_CLASS, WAND_CLASS,
                 RING_CLASS, SPBOOK_CLASS];
// C ref: monmove.c:998 mon_would_take_item
export function mon_would_take_item(mtmp, otmp) {
    const mdat = mtmp.data;
    const maxload = max_mon_load_local(mtmp);
    const pctload = maxload > 0
        ? Math.trunc((curr_mon_load_local(mtmp) * 100) / maxload) : 100;
    if (otmp === game.u.uball || otmp === game.u.uchain) return false;
    if (mtmp.mtame && otmp.cursed) return false;
    if (is_unicorn(mdat) && (game.objects[otmp.otyp]?.oc_material ?? 0) !== GEMSTONE)
        return false;
    if (!is_mindless(mdat) && !is_animal(mdat) && pctload < 75
        && searches_for_item(mtmp, otmp))
        return true;
    if (likes_gold(mdat) && otmp.otyp === GOLD_PIECE && pctload < 95)
        return true;
    if (likes_gems(mdat) && otmp.oclass === GEM_CLASS
        && (game.objects[otmp.otyp]?.oc_material ?? 0) !== MINERAL
        && pctload < 85)
        return true;
    if (likes_objs(mdat) && practical.includes(otmp.oclass) && pctload < 75)
        return true;
    if (likes_magic(mdat) && magical.includes(otmp.oclass) && pctload < 85)
        return true;
    if (throws_rocks(mdat) && otmp.otyp === BOULDER && pctload < 50
        && !Sokoban())
        return true;
    if (mdat === mons[PM_GELATINOUS_CUBE]
        && otmp.oclass !== ROCK_CLASS && otmp.oclass !== BALL_CLASS
        && !(otmp.otyp === CORPSE && touch_petrifies(mons[otmp.corpsenm])))
        return true;
    return false;
}
// C ref: monmove.c:1036 mon_would_consume_item
function mon_would_consume_item(mtmp, otmp) {
    if (otmp.otyp === CORPSE && otmp.corpsenm !== undefined
        && !touch_petrifies(mons[otmp.corpsenm])
        && corpse_eater(mtmp.data))
        return true;
    if (mtmp.mtame && has_edog(mtmp)) {
        const ftyp = dogfood(mtmp, otmp);
        if (ftyp < MANFOOD
            && (ftyp < ACCFOOD || (EDOG(mtmp)?.hungrytime ?? 0) <= game.moves))
            return true;
    }
    return false;
}
// C ref: mondata.h corpse_eater macro
function corpse_eater(ptr) {
    if (!ptr) return false;
    return ptr === mons[PM_PURPLE_WORM]
        || ptr === mons[PM_BABY_PURPLE_WORM]
        || ptr === mons[PM_GHOUL]
        || ptr === mons[PM_PIRANHA];
}
function metallivorous(ptr) {
    return !!(ptr?.mflags1 & 0x80000000); // M1_METALLIVORE
}
// C ref: mon.c:1448 meatmetal()
async function meatmetal_local(mtmp) {
    if (mtmp.mtame) return 0;
    for (let otmp = fobj_at(mtmp.mx, mtmp.my); otmp; otmp = otmp.nexthere) {
        if ((mtmp.data === mons[PM_RUST_MONSTER] && !is_rustprone(otmp))
            || otmp.otyp === AMULET_OF_STRANGULATION
            || otmp.otyp === RIN_SLOW_DIGESTION
            || (otmp.opoisoned && !resists_poison(mtmp))) {
            continue;
        }
        if (!is_metallic(otmp) || obj_resists(otmp, 5, 95)
            || !(await touch_artifact(otmp, mtmp))) {
            continue;
        }
        if (mtmp.data === mons[PM_RUST_MONSTER] && otmp.oerodeproof) {
            otmp.oerodeproof = 0;
            mtmp.mstun = 1;
            continue;
        }
        mtmp.meating = Math.trunc((otmp.owt || 0) / 2) + 1;
        delobj(otmp);
        if (mtmp.dead) return 2;
        if (rnd(25) < 3)
            mksobj_at(ROCK, mtmp.mx, mtmp.my, true, false);
        newsym(mtmp.mx, mtmp.my);
        return 1;
    }
    return 0;
}
// Lightweight load helpers (avoid circular import from dogmove if needed)
function curr_mon_load_local(mtmp) {
    let curload = 0;
    for (let obj = mtmp?.minvent; obj; obj = obj.nobj) {
        if (obj.otyp !== BOULDER || !throws_rocks(mtmp?.data))
            curload += obj.owt || weight(obj);
    }
    return curload;
}
function max_mon_load_local(mtmp) {
    const mdat = mtmp?.data;
    if (!mdat) return 1;
    let maxload;
    const strongmonst_fn = (d) => !!(d?.mflags2 & M2_STRONG);
    if (!mdat.cwt) {
        maxload = (1000 * (mdat.msize || 0)) / MZ_HUMAN;
    } else if (!strongmonst_fn(mdat) || (strongmonst_fn(mdat) && (mdat.cwt > 1450))) {
        maxload = (1000 * mdat.cwt) / 1450;
    } else {
        maxload = 1000;
    }
    if (!strongmonst_fn(mdat)) maxload /= 2;
    maxload = Math.trunc(maxload);
    return maxload < 1 ? 1 : maxload;
}
// C ref: monmove.c obj.h — is_mines_prize / is_soko_prize
function is_mines_prize(o) {
    return !!(game.context?.achieveo?.mines_prize_oid
              && o.o_id === game.context.achieveo.mines_prize_oid);
}
function is_soko_prize(o) {
    return !!(game.context?.achieveo?.soko_prize_oid
              && o.o_id === game.context.achieveo.soko_prize_oid);
}
// fobj_at: imported from pickup.js
// ============================================================================
// m_search_items — C ref: monmove.c:1328-1449
// Monster looks for nearby items it wants and adjusts goal accordingly.
// ============================================================================
const SQSRCHRADIUS = 5;
async function m_search_items(mtmp, result) {
    const g = game;
    let minr = SQSRCHRADIUS;
    const omx = mtmp.mx, omy = mtmp.my;
    const ptr = mtmp.data;
    // cut down search radius if hero seems closer
    if (distmin(mtmp.mux, mtmp.muy, omx, omy) < SQSRCHRADIUS
        && !mtmp.mpeaceful)
        minr--;
    // guards shouldn't get too distracted
    if (!mtmp.mpeaceful && is_mercenary(ptr))
        minr = 1;
    // in shop, usually skip (C: goto finish_search)
    let skipSearch = false;
    if (is_shop_square(omx, omy) && (rn2(25) || mtmp.isshk))
        skipSearch = true;
    const hmx = Math.min(COLNO - 1, omx + minr);
    const hmy = Math.min(ROWNO - 1, omy + minr);
    const lmx = Math.max(1, omx - minr);
    const lmy = Math.max(0, omy - minr);
    if (!skipSearch) for (let xx = lmx; xx <= hmx; xx++) {
        for (let yy = lmy; yy <= hmy; yy++) {
            // no object here
            if (!fobj_at(xx, yy)) continue;
            // found an object closer already
            if (minr < distmin(omx, omy, xx, yy)) continue;
            // can't reach underwater objects if flying
            if (!could_reach_item(mtmp, xx, yy)) continue;
            // hiders avoid hero's line of sight
            if (hides_under(ptr) && cansee(xx, yy)) continue;
            // don't circle around immobile/hidden monster
            const mtoo = map_m_at(xx, yy);
            if (mtoo && (helpless(mtoo) || mtoo.mundetected
                || (mtoo.mappearance && !mtoo.iswiz)
                || !mtoo.data?.mmove))
                continue;
            // Don't circle an Elbereth
            if (onscary(xx, yy, mtmp)) continue;
            // ignore obj if there's a known trap
            const ttmp = t_at(xx, yy);
            if (ttmp && mon_knows_traps(mtmp, ttmp.ttyp)) {
                if (result.ggx === xx && result.ggy === yy) {
                    result.ggx = mtmp.mux;
                    result.ggy = mtmp.muy;
                }
                continue;
            }
            // avoid items monster can't see
            if (!m_cansee(mtmp, xx, yy)) continue;
            const costly = costly_spot(xx, yy);
            // look through items at this location
            for (let otmp = fobj_at(xx, yy); otmp; otmp = otmp.nexthere) {
                // skip rocks
                if (otmp.otyp === ROCK) continue;
                // avoid special items
                if (is_mines_prize(otmp) || is_soko_prize(otmp)) continue;
                // skip shop merchandise
                if (costly && !otmp.no_charge) continue;
                if (((mon_would_take_item(mtmp, otmp)
                      && (can_carry(mtmp, otmp) > 0))
                     || mon_would_consume_item(mtmp, otmp))
                    && await can_touch_safely(mtmp, otmp)) {
                    minr = distmin(omx, omy, xx, yy);
                    result.ggx = otmp.ox;
                    result.ggy = otmp.oy;
                    if (result.ggx === omx && result.ggy === omy) {
                        result.mmoved = MMOVE_DONE;
                        return true;
                    }
                    // found item of interest; skip rest of pile
                    break;
                }
            }
        }
    }
    // finish_search:
    if (minr < SQSRCHRADIUS && result.appr === -1) {
        if (distmin(omx, omy, mtmp.mux, mtmp.muy) <= 3) {
            result.ggx = mtmp.mux;
            result.ggy = mtmp.muy;
        } else {
            result.appr = 1;
        }
    }
    return false;
}
function leppie_avoidance(mtmp) {
    if (mtmp?.data !== mons[PM_LEPRECHAUN])
        return false;
    const lepgold = findgold(mtmp.minvent);
    const ygold = findgold(game.invent);
    return !!(lepgold && (lepgold.quan || 0) > (ygold?.quan || 0));
}
function m_balks_at_approaching(oldappr, mtmp, pdistmin, pdistmax) {
    const mwep = MON_WEP(mtmp);
    const x = mtmp.mx;
    const y = mtmp.my;
    const ux = mtmp.mux;
    const uy = mtmp.muy;
    const edist = dist2(x, y, ux, uy);
    if (pdistmin) pdistmin.value = 0;
    if (pdistmax) pdistmax.value = 0;
    if (mtmp.mpeaceful || edist >= 25 || !m_canseeu(mtmp))
        return oldappr;
    if (m_has_launcher_and_ammo(mtmp))
        return -1;
    if (mwep && is_pole(mwep) && edist <= MON_POLE_DIST)
        return -1;
    const arw = mwep ? autoreturn_weapon(mwep) : null;
    if (arw) {
        if (pdistmin) pdistmin.value = 4;
        if (pdistmax) pdistmax.value = arw.range || 0;
        return -2;
    }
    if (ranged_attk_available(mtmp)
        && ((mtmp.mhp ?? 0) < Math.trunc(((mtmp.mhpmax ?? 0) + 1) / 3)
            || !(mtmp.mspec_used ?? 0)))
        return -1;
    return oldappr;
}
function cansee_fn(x, y) {
    return couldsee(x, y);
}
// Deaf: imported from macros.js
const Deaf_fn = Deaf;
const _tnnames = ['C note','D flat','D note','E flat','E note','F note','F sharp','G note','G sharp','A note','B flat','B note'];
function trapnote_fn(trap) {
    const tn = _tnnames[trap.tnote ?? 0] || 'C note';
    return (/^[AEIOU]/i.test(tn) ? 'an ' : 'a ') + tn;
}
// ============================================================================
// mon_track_add / mon_track_clear — C ref: monmove.c:79-93
// ============================================================================
export function mon_track_add(mtmp, x, y) {
    if (!Array.isArray(mtmp.mtrack) || mtmp.mtrack.length !== MTSZ) {
        mtmp.mtrack = Array.from({ length: MTSZ }, () => ({ x: 0, y: 0 }));
    }
    for (let i = MTSZ - 1; i > 0; i--) {
        mtmp.mtrack[i] = { ...mtmp.mtrack[i - 1] };
    }
    mtmp.mtrack[0] = { x, y };
}
export function mon_track_clear(mtmp) {
    mtmp.mtrack = Array.from({ length: MTSZ }, () => ({ x: 0, y: 0 }));
}
// mon_knows_traps / mon_learns_traps — imported from mondata.js
// ============================================================================
// mb_trapped — C ref: monmove.c:55
// ============================================================================
export async function mb_trapped(mtmp, canseeit) {
    const { flags } = game;
    if (flags?.verbose) {
        if (canseeit /* && !Unaware */)
            await pline("KABOOM!!  You see a door explode.");
        else
            await You(`hear a ${(dist2(mtmp.mx, mtmp.my, game.u?.ux ?? 0, game.u?.uy ?? 0) > 7 * 7) ? 'distant' : 'nearby'} explosion.`);
    }
    wake_nearto(mtmp.mx, mtmp.my, 7 * 7);
    mtmp.mstun = 1;
    mtmp.mhp -= rnd(15);
    if (mtmp.mhp <= 0 || mtmp.dead) {
        await mondied(mtmp);
        if (mtmp.mhp <= 0 || mtmp.dead)
            return true;
        // will get here if lifesaved
    }
    mon_learns_traps(mtmp, D_TRAPPED);
    return false;
}
// ============================================================================
// onscary — C ref: monmove.c:242
// ============================================================================
export function onscary(x, y, mtmp) {
    const auditoryScare = (x === 0 && y === 0);
    const magicalScare = !auditoryScare;
    // C: direct scare resistors: Wizard, lawful minions, Angels, Riders.
    if (mtmp.iswiz || is_lminion(mtmp) || mtmp.data === mons[PM_ANGEL]
        || is_rider(mtmp.data)) {
        return false;
    }
    // C: humans and unique-corpsestat monsters resist magical scaring.
    if (magicalScare
        && (mtmp.data?.mlet === S_HUMAN || unique_corpstat(mtmp.data))) {
        return false;
    }
    // C: shopkeepers in own shop and priests in own temple are fearless.
    if ((mtmp.isshk && inhishop(mtmp))
        || (mtmp.ispriest && inhistemple(mtmp))) {
        return false;
    }
    if (auditoryScare) return true;
    const loc = game.level?.at?.(x, y);
    if (loc && IS_ALTAR(loc.typ)
        && (mtmp.data?.mlet === S_VAMPIRE || is_vampshifter(mtmp))) {
        return true;
    }
    if (sobj_at(SCR_SCARE_MONSTER, x, y)) return true;
    const ep = sengr_at('Elbereth', x, y, true);
    if (!ep) return false;
    const elberethApplies = (
        u_at(x, y)
        || (Displaced() && mtmp.mux === x && mtmp.muy === y)
        || (ep.guardobjects && vobj_at(x, y))
    );
    if (!elberethApplies) return false;
    if (mtmp.isshk || mtmp.isgd || !mtmp.mcansee || mtmp.mpeaceful
        || mtmp.data === mons[PM_MINOTAUR]
        || Inhell() || In_endgame(game.u?.uz)) {
        return false;
    }
    return true;
}
// ============================================================================
// mon_regen — C ref: monmove.c:308
// ============================================================================
export function mon_regen(mon, digest_meal) {
    if ((game.moves || 0) % 20 === 0 /* || regenerates(mon.data) */) {
        // healmon(mon, 1, 0)
        if (mon.mhp < mon.mhpmax) {
            mon.mhp += 1;
            if (mon.mhp > mon.mhpmax)
                mon.mhp = mon.mhpmax;
        }
    }
    if (mon.mspec_used)
        mon.mspec_used--;
    if (digest_meal) {
        if (mon.meating) {
            mon.meating--;
            if (mon.meating <= 0)
                mon.meating = 0; // finish_meating simplified
        }
    }
}
// ============================================================================
// disturb — C ref: monmove.c:328
// ============================================================================
// C ref: monmove.c:330-358 — full disturb logic
function disturb(mtmp) {
    if (!couldsee(mtmp.mx, mtmp.my)
        || dist2(mtmp.mx, mtmp.my, game.u?.ux ?? 0, game.u?.uy ?? 0) > 100)
        return 0;
    // C: (!Stealth || (PM_ETTIN && rn2(10))) — Stealth not yet implemented,
    // treat as !Stealth (always true), so no rn2(10) consumed
    // C: !(nymph || jabberwock || leprechaun) || !rn2(50)
    if ((mtmp.data?.mlet === S_NYMPH
        || mtmp.data === mons[PM_JABBERWOCK]
        || mtmp.data?.mlet === S_LEPRECHAUN)
        && rn2(50))
        return 0;
    // C: Aggravate || (dog/human) || (!rn2(7) && not mimic)
    // Aggravate_monster not yet implemented, treat as false
    if (mtmp.data?.mlet === S_DOG || mtmp.data?.mlet === S_HUMAN) {
        // dogs and humans always wake
    } else if (rn2(7)
        || M_AP_TYPE(mtmp) === M_AP_FURNITURE
        || M_AP_TYPE(mtmp) === M_AP_OBJECT) {
        return 0;
    }
    mtmp.msleeping = 0;
    return 1;
}
// ============================================================================
// closed_door — C ref: monmove.c:2200
// ============================================================================
export function closed_door(x, y) {
    const loc = game.level?.at(x, y);
    if (!loc || loc.typ !== DOOR) return false;
    const mask = loc.doormask ?? loc.flags ?? 0;
    return !!(mask & (D_CLOSED | D_LOCKED));
}
// C ref: monmove.c:2186 accessible()
// Returns true if position (x,y) has accessible terrain and no closed door.
export function accessible(x, y) {
    const loc = game.level?.at(x, y);
    if (!loc) return false;
    // C ref: monmove.c:2186 — uses SURFACE_AT to handle drawbridge_up
    const surfaceTyp = (loc.typ === DRAWBRIDGE_UP)
        ? db_under_typ(loc.drawbridgemask ?? 0)
        : loc.typ;
    return ACCESSIBLE(surfaceTyp) && !closed_door(x, y);
}
// ============================================================================
// m_everyturn_effect — C ref: monmove.c:663
// ============================================================================
export async function m_everyturn_effect(mtmp) {
    const is_u = mtmp === game.youmonst;
    const x = is_u ? game.u.ux : mtmp.mx;
    const y = is_u ? game.u.uy : mtmp.my;
    if (mtmp.data === mons[PM_FOG_CLOUD]) {
        const cd = closed_door(x, y) ? 1 : 0;
        const vr = visible_region_at(x, y) ? 1 : 0;
        pushRngLogEntry(`^fog_everyturn[${PM_FOG_CLOUD}@${x},${y} cd=${cd} vr=${vr}]`);
        if (!cd && !vr) {
            await create_gas_cloud(x, y, 1, 0); /* harmless vapor */
        }
    }
}
// C ref: monmove.c:672 m_postmove_effect()
async function m_postmove_effect(mtmp) {
    // For monsters this is called before relocation, so use current location.
    const x = mtmp.mx;
    const y = mtmp.my;
    if (mtmp.data === mons[PM_HEZROU]) {
        await create_gas_cloud(x, y, 1, 8);
    } else if (mtmp.data === mons[PM_STEAM_VORTEX] && !mtmp.mcan) {
        await create_gas_cloud(x, y, 1, 0);
    }
}
// C ref: monmove.c:1227 holds_up_web()
function holds_up_web(x, y) {
    if (!isok(x, y)) return true;
    const loc = game.level?.at?.(x, y);
    if (!loc) return true;
    if (IS_OBSTRUCTED(loc.typ) || loc.typ === IRONBARS) {
        return true;
    }
    if ((loc.typ === STAIRS || loc.typ === LADDER)) {
        const stway = stairway_at(x, y);
        if (stway?.up) return true;
    }
    return false;
}
// C ref: monmove.c:1244 count_webbing_walls()
function count_webbing_walls(x, y) {
    return (holds_up_web(x, y - 1) ? 1 : 0)
        + (holds_up_web(x + 1, y) ? 1 : 0)
        + (holds_up_web(x, y + 1) ? 1 : 0)
        + (holds_up_web(x - 1, y) ? 1 : 0);
}
// C ref: monmove.c:1252 soko_allow_web()
function soko_allow_web(mon) {
    if (!Sokoban()) return true;
    const stway = stairway_find_dir(true);
    return !!(stway && m_cansee(mon, stway.sx, stway.sy));
}
// C ref: monmove.c:1269 maybe_spin_web()
async function maybe_spin_web(mtmp) {
    if (!webmaker(mtmp.data)
        || helpless(mtmp)
        || mtmp.mspec_used
        || t_at(mtmp.mx, mtmp.my)
        || !soko_allow_web(mtmp)) {
        return;
    }
    const prob = (((mtmp.data === mons[PM_GIANT_SPIDER]) ? 15 : 5)
        * (count_webbing_walls(mtmp.mx, mtmp.my) + 1))
        - (3 * count_traps(WEB));
    const trap = (rn2(1000) < prob)
        ? await maketrap(mtmp.mx, mtmp.my, WEB)
        : null;
    if (!trap) return;
    mtmp.mspec_used = c_d(4, 4); // C: d(4, 4) = 4..16
    if (cansee(mtmp.mx, mtmp.my)) {
        await pline(`${Monnam(mtmp)} spins a web.`);
        trap.tseen = true;
    }
    if (in_rooms(mtmp.mx, mtmp.my, SHOPBASE)) {
        add_damage(mtmp.mx, mtmp.my, 0);
    }
}
// ============================================================================
// set_apparxy — C ref: monmove.c:2217
// ============================================================================
export function set_apparxy(mtmp) {
    const g = game;
    const u = g.u;
    let mx = mtmp.mux;
    let my = mtmp.muy;
    if (mtmp.mtame || mtmp === u.ustuck || u_at(mx, my)) {
        mtmp.mux = u.ux;
        mtmp.muy = u.uy;
        return;
    }
    const notseen = !mtmp.mcansee || (Invis() && !perceives(mtmp.data));
    const notthere = Displaced() && (mtmp.data !== mons[PM_DISPLACER_BEAST]);
    const umoney = money_cnt(g.invent);
    let displ;
    if (Underwater()) {
        displ = 1;
    } else if (notseen) {
        displ = (mtmp.data === mons[PM_XORN] && umoney) ? 0 : 1;
    } else if (notthere) {
        displ = couldsee(mx, my) ? 2 : 1;
    } else {
        displ = 0;
    }
    if (!displ) {
        mtmp.mux = u.ux;
        mtmp.muy = u.uy;
        return;
    }
    const gotu = notseen ? !rn2(3) : notthere ? !rn2(4) : false;
    if (!gotu) {
        let tryCnt = 0;
        do {
            if (++tryCnt > 200) {
                mx = u.ux;
                my = u.uy;
                break;
            }
            mx = u.ux - displ + rn2(2 * displ + 1);
            my = u.uy - displ + rn2(2 * displ + 1);
        } while (!isok(mx, my)
                 || (displ !== 2 && mx === mtmp.mx && my === mtmp.my)
                 || ((mx !== u.ux || my !== u.uy)
                     && !passes_walls(mtmp.data)
                     && !(accessible_monmove(mx, my)
                          || (closed_door(mx, my)
                              && (can_ooze_fn(mtmp) || can_fog_fn(mtmp)))))
                 || !couldsee(mx, my));
    } else {
        mx = u.ux;
        my = u.uy;
    }
    mtmp.mux = mx;
    mtmp.muy = my;
}
// ============================================================================
// distfleeck — C ref: monmove.c:533
// ============================================================================
export async function distfleeck(mtmp, result) {
    const ux = mtmp.mux ?? game.u?.ux ?? 0;
    const uy = mtmp.muy ?? game.u?.uy ?? 0;
    // C: bravegremlin = (rn2(5) == 0) — always consumed
    const bravegremlin = (rn2(5) === 0);
    // Distance checks
    const dx = mtmp.mx - ux, dy = mtmp.my - uy;
    const d2 = dx * dx + dy * dy;
    const inRange = (d2 <= BOLT_LIM * BOLT_LIM) ? 1 : 0;
    // C ref: *nearby = *inrange && monnear(mtmp, mtmp->mux, mtmp->muy)
    const nearby = (inRange && monnear(mtmp, ux, uy)) ? 1 : 0;
    // C ref: monmove.c distfleeck — check seescaryx/seescaryy based on visibility
    let seescaryx, seescaryy;
    if (!mtmp.mcansee || (Invis() && !perceives(mtmp.data))) {
        seescaryx = mtmp.mux ?? game.u?.ux ?? 0;
        seescaryy = mtmp.muy ?? game.u?.uy ?? 0;
    } else {
        seescaryx = game.u?.ux ?? 0;
        seescaryy = game.u?.uy ?? 0;
    }
    const sawscary = onscary(seescaryx, seescaryy, mtmp);
    // C ref: flees_light(mon) — gremlins flee from lit artifacts
    const fleesLight = mtmp.data === mons[PM_GREMLIN]
        && ((game.u?.uwep?.lamplit && artifact_light(game.u.uwep))
            || (game.u?.uarm?.lamplit && artifact_light(game.u.uarm)))
        && mtmp.mcansee && couldsee(mtmp.mx, mtmp.my);
    let scared = 0;
    if (nearby && (sawscary
                   || (fleesLight && !bravegremlin)
                   || (!mtmp.mpeaceful && in_your_sanctuary(mtmp, 0, 0)))) {
        scared = 1;
        const fleeDur = rn2(7) ? 10 : 100;
        const fleeTime = rnd(fleeDur);
        await monflee(mtmp, fleeTime, true, true);
    }
    if (result) {
        result.inrange = inRange;
        result.nearby = nearby;
        result.scared = scared;
    }
    pushRngLogEntry(`^distfleeck[${formatMonsterEventRef(mtmp)} in=${inRange} near=${nearby} scare=${scared} brave=${bravegremlin ? 1 : 0} saw=${sawscary ? 1 : 0} light=0 sanct=0 mux=${mtmp.mux ?? 0} muy=${mtmp.muy ?? 0} ux=${game.u.ux} uy=${game.u.uy} see=${mtmp.mcansee ? 1 : 0} tame=${mtmp.mtame || 0} conf=${mtmp.mconf ? 1 : 0} stun=${mtmp.mstun ? 1 : 0} inv=${mtmp.minvis ? 1 : 0}]`);
}
// monflee — use canonical version from mon.js (which now includes mon_track_clear)
// ============================================================================
// mfndpos — C ref: monmove.c (mfndpos.h) via mon.c:2125
// ============================================================================
// mfndpos — canonical version is in mon.js (supports ALLOW_DIG flag).
// Re-exported here for dogmove.js and other importers.
// Do NOT duplicate the implementation — import from mon.js.
export { mfndpos };
// Removed duplicate mfndpos (was 74 lines). The mon.js version handles
// ALLOW_DIG terrain for digging monsters, which this copy lacked.
/* removed: export function mfndpos(mtmp) {
    pushRngLogEntry('>mfndpos');
    const map = game.level;
    const positions = [];
    const x = mtmp.mx, y = mtmp.my;
    const nowtyp = map?.at(x, y)?.typ ?? 0;
    const forbidDiag = nodiag(mtmp);
    const allowM = !!mtmp?.mtame;
    const maxx = Math.min(x + 1, COLNO - 1);
    const maxy = Math.min(y + 1, ROWNO - 1);
    for (let nx = Math.max(1, x - 1); nx <= maxx; nx++) {
        for (let ny = Math.max(0, y - 1); ny <= maxy; ny++) {
            if (nx === x && ny === y) continue;
            const loc = map?.at(nx, ny);
            if (!loc) continue;
            const ntyp = loc.typ;
            if (!ACCESSIBLE(ntyp)) continue;
            // Diagonal restriction near doors
            if (nx !== x && ny !== y) {
                if (forbidDiag) continue;
                if (nowtyp === DOOR) {
                    const mask = (map?.at(x, y)?.doormask ?? map?.at(x, y)?.flags ?? 0);
                    if (mask & ~D_BROKEN) continue;
                }
                if (ntyp === DOOR) {
                    const mask = (loc.doormask ?? loc.flags ?? 0);
                    if (mask & ~D_BROKEN) continue;
                }
            }
            // Closed/locked door handling
            if (ntyp === DOOR) {
                const mask = loc.doormask ?? loc.flags ?? 0;
                const blockedByClosed = !!(mask & D_CLOSED) && !monster_can_open_doors(mtmp);
                const blockedByLocked = !!(mask & D_LOCKED);
                if (blockedByClosed || blockedByLocked) continue;
            }
            // Skip hero position
            if (u_at(nx, ny)) continue;
            const trap = map?.trapAt?.(nx, ny) || null;
            if (trap && !mtmp.mtame && !m_harmless_trap(mtmp, trap)
                && mon_knows_traps(mtmp, trap.ttyp)) {
                continue;
            }
            const occupant = map.monsters?.find(m => !m.dead && m.mx === nx && m.my === ny) || null;
            if (occupant && !allowM) continue;
            let info = 0;
            if (u_at(nx, ny)) {
                info |= ALLOW_U;
            }
            if (mtmp.mtame) {
                info |= ALLOW_M;
                info |= ALLOW_TRAPS;
                info |= ALLOW_SANCT;
                info |= ALLOW_SSM;
            }
            if (occupant && mtmp.mtame && occupant.mpeaceful) {
                info |= ALLOW_MDISP;
            }
            positions.push({ x: nx, y: ny, occupant, info,
                allowM: !!occupant && !!(info & ALLOW_M) });
        }
    }
    pushRngLogEntry(\`<mfndpos=\${positions.length}\`);
    return positions;
} */
// ============================================================================
// mon_note_trap_at — squeaky board notifications etc.
// ============================================================================
async function mon_note_trap_at(mtmp, x, y) {
    const trap = game.level?.trapAt?.(x, y) || null;
    if (trap && !m_harmless_trap(mtmp, trap)) {
        mon_learns_traps(mtmp, trap.ttyp);
        if (trap.ttyp === SQKY_BOARD) {
            const noteNames = [
                'C note', 'D flat', 'D note', 'E flat',
                'E note', 'F note', 'F sharp', 'G note',
                'G sharp', 'A note', 'B flat', 'B note',
            ];
            const note = noteNames[(trap.tnote ?? 0) % 12] || 'C note';
            const range = couldsee(mtmp.mx, mtmp.my)
                ? (BOLT_LIM + 1) : (BOLT_LIM - 3);
            const nearby = dist2(game.u?.ux ?? 0, game.u?.uy ?? 0, mtmp.mx, mtmp.my)
                <= range * range;
            await pline(`You hear ${an(note)} squeak ${nearby ? 'nearby' : 'in the distance'}.`);
        }
    }
}
// ============================================================================
// mintrap_monster — C ref: trap.c mintrap() monster path
// ============================================================================
export async function mintrap_monster(mtmp) {
    if (!mtmp || mtmp.dead) return;
    const trap = game.level?.traps?.find(t => t.tx === mtmp.mx && t.ty === mtmp.my);
    if (!trap) return 0;
    await mon_note_trap_at(mtmp, mtmp.mx, mtmp.my);
    if (trap.ttyp === SQKY_BOARD) {
        return mtmp.mtrapped ? 2 : 0;
    }
    if (trap.ttyp === DART_TRAP) {
        if (trap.once && trap.tseen && !rn2(15)) {
            return 0;
        }
        trap.once = 1;
        const otmp = mksobj(DART, true, false);
        otmp.quan = 1;
        otmp.owt = weight(otmp);
        otmp.opoisoned = 0;
        otmp.ox = trap.tx;
        otmp.oy = trap.ty;
        if (!rn2(6)) {
            otmp.opoisoned = 1;
        }
        const strike = (find_mac(mtmp) + 7 + (otmp.spe || 0) <= rnd(20));
        if (!strike) {
            place_object(otmp, mtmp.mx, mtmp.my);
            const objects = game.level?.objects || [];
            for (const other of objects) {
                if (!other || other === otmp) continue;
                if (other.ox !== otmp.ox || other.oy !== otmp.oy) continue;
                if (other.otyp !== otmp.otyp) continue;
                if ((other.opoisoned || 0) !== (otmp.opoisoned || 0)) continue;
                other.quan = (other.quan || 1) + (otmp.quan || 1);
                obj_extract_self(otmp);
                break;
            }
        } else {
            mtmp.mhp -= 1;
            if (mtmp.mhp <= 0) {
                await mondied(mtmp);
                return 1;
            }
        }
        return mtmp.mtrapped ? 2 : 0;
    }
    // C ref: trap.c SQKY_BOARD monster path — squeaky board message
    if (trap.ttyp === SQKY_BOARD) {
        if (m_in_air(mtmp)) return 0;
        const in_sight = cansee_fn(mtmp.mx, mtmp.my);
        if (in_sight) {
            if (!Deaf_fn()) {
                const tn = trapnote_fn(trap);
                await pline(`A board beneath ${mon_nam(mtmp)} squeaks ${tn} loudly.`);
            }
        } else {
            const tn = trapnote_fn(trap);
            const ux = game.u?.ux ?? 0, uy = game.u?.uy ?? 0;
            const dx = ux - mtmp.mx, dy = uy - mtmp.my;
            const dist = dx*dx + dy*dy;
            const range = 10; // BOLT_LIM + 1
            await You_hear(`${tn} squeak ${dist <= range * range ? 'nearby' : 'in the distance'}.`);
        }
        wake_nearto(mtmp.mx, mtmp.my, 40);
        return 0;
    }
    if (trap.ttyp === PIT || trap.ttyp === SPIKED_PIT) {
        const spiked = trap.ttyp === SPIKED_PIT;
        if (!passes_walls(mtmp.data))
            mtmp.mtrapped = 1;
        const in_sight = cansee_fn(mtmp.mx, mtmp.my);
        if (in_sight) {
            const mname = monsterSubjectName(mtmp);
            const whose = trap.madeby_u ? 'your' : 'a';
            await pline(`${mname} falls into ${whose} pit!`);
        }
        const damage = rnd(spiked ? 10 : 6);
        mtmp.mhp -= damage;
        if (mtmp.mhp <= 0) {
            if (in_sight) {
                const mname = monsterSubjectName(mtmp);
                await pline(`${mname} is killed!`);
            }
            await mondied(mtmp);
            return 1;
        }
    }
    return 0;
}
// ============================================================================
// postmov — C ref: monmove.c:1475
// ============================================================================
export async function postmov(mtmp, omx, omy, mmoved, can_open, can_unlock, can_tunnel = false) {
    const g = game;
    const map = g.level;
    const ptr = mtmp.data;
    if (mmoved === 1) { // MMOVE_MOVED
        newsym(omx, omy);
        // C ref: monmove.c:1509 — real mintrap, not simplified stub
        const trapret = await mintrap(mtmp, 0);
        // C ref: monmove.c:1532 — Trap_Killed_Mon OR Trap_Moved_Mon
        // both terminate this monster turn as MMOVE_DIED.
        if (mtmp.dead
            || trapret === 1 /* Trap_Killed_Mon */
            || trapret === 4 /* Trap_Moved_Mon */) {
            if (mtmp.mx) newsym(mtmp.mx, mtmp.my);
            return 2; // MMOVE_DIED
        }
        // C ref: postmov — open doors (or unlock+open) after movement.
        const loc = map?.at(mtmp.mx, mtmp.my);
        if (loc && loc.typ === DOOR && !passes_walls(ptr) && !can_tunnel) {
            const mask = loc.doormask ?? loc.flags ?? 0;
            const btrapped = !!(mask & D_TRAPPED);
            let canSeeDoor = couldsee(mtmp.mx, mtmp.my);
            const verbose = game.flags?.verbose !== false;
            const unblockDoor = (newMask) => {
                // C ref: monmove.c UnblockDoor macro in postmov():
                // update door state, refresh map + blocking, then recalc vision.
                loc.doormask = newMask;
                newsym(mtmp.mx, mtmp.my);
                recalc_block_point(mtmp.mx, mtmp.my);
                vision_recalc(0);
                canSeeDoor = canSeeDoor || cansee(mtmp.mx, mtmp.my);
            };
            if ((mask & D_LOCKED) && can_unlock) {
                unblockDoor(btrapped ? D_NODOOR : D_ISOPEN);
                if (verbose) {
                    if (canSeeDoor && canseemon(mtmp)) {
                        await pline(`${Monnam(mtmp)} unlocks and opens a door.`);
                    } else if (canSeeDoor) {
                        await You_see('a door unlock and open.');
                    } else {
                        await You_hear('a door unlock and open.');
                    }
                }
            } else if (mask === D_CLOSED && can_open) {
                unblockDoor(btrapped ? D_NODOOR : D_ISOPEN);
                if (verbose) {
                    if (canSeeDoor && canseemon(mtmp)) {
                        await pline(`${Monnam(mtmp)} opens a door.`);
                    } else if (canSeeDoor) {
                        await You_see('a door open.');
                    } else {
                        await You_hear('a door open.');
                    }
                }
            }
        }
        // C ref: monmove.c postmov -- tunnel/dig after door handling.
        if (can_tunnel && may_dig_local(mtmp.mx, mtmp.my)
            && await mdig_tunnel(mtmp)) {
            return 2; // MMOVE_DIED
        }
        // C ref: postmov newsym at new position
        newsym(mtmp.mx, mtmp.my);
    }
    // C ref: monmove.c:1679 — pickup phase runs for MMOVE_MOVED and MMOVE_DONE.
    if ((mmoved === 1 || mmoved === MMOVE_DONE)
        && obj_at(mtmp.mx, mtmp.my) && mtmp.mcanmove) {
        // C ref: monmove.c:1683 -> mon.c:1448
        if (metallivorous(ptr)) {
            if (await meatmetal_local(mtmp) === 2)
                return 2; // MMOVE_DIED
        }
        if (await mpickstuff_local(mtmp))
            mmoved = MMOVE_DONE;
    }
    if (mmoved === 1 || mmoved === MMOVE_DONE) {
        await maybe_spin_web(mtmp);
    }
    // C ref: monmove.c postmov() — hide-under / eel concealment upkeep.
    if (mmoved === 1 || mmoved === MMOVE_DONE) {
        if (hides_under(ptr) || ptr?.mlet === S_EEL) {
            if (mtmp.mundetected || (!helpless(mtmp) && rn2(5))) {
                await hideunder_with_message(mtmp);
            }
            newsym(mtmp.mx, mtmp.my);
        }
    }
    return mmoved;
}
// C ref: mon.c:1832 mpickstuff() — pick one floor object stack for this monster.
async function mpickstuff_local(mtmp) {
    // Prevent shopkeepers from leaving their shop door to shop around.
    if (mtmp.isshk && is_shop_square(mtmp.mx, mtmp.my))
        return false;
    // Non-tame monsters normally don't go shopping.
    if (!mtmp.mtame && is_shop_square(mtmp.mx, mtmp.my) && rn2(25))
        return false;
    // Item in water/lava but monster cannot reach it.
    if (!could_reach_item(mtmp, mtmp.mx, mtmp.my))
        return false;
    for (let otmp = fobj_at(mtmp.mx, mtmp.my); otmp; otmp = otmp.nexthere) {
        if (is_mines_prize(otmp) || is_soko_prize(otmp))
            continue;
        if (!mon_would_take_item(mtmp, otmp))
            continue;
        if (!(await can_touch_safely(mtmp, otmp)))
            continue;
        const carryamt = can_carry(mtmp, otmp);
        if (!carryamt)
            continue;
        // Keep behavior conservative until splitobj path is ported here.
        if ((otmp.quan ?? 1) !== carryamt)
            continue;
        if (cansee(mtmp.mx, mtmp.my)) {
            const otmpname = distant_name(otmp, doname);
            if (game.flags?.verbose !== false)
                await pline(`${Monnam(mtmp)} picks up ${otmpname}.`);
        }
        obj_extract_self(otmp);
        await mpickobj(mtmp, otmp);
        // C ref: mon.c:1888-1890 — after any pickup, flag deferred
        // gear reevaluation for next monster turn.
        check_gear_next_turn(mtmp);
        newsym(mtmp.mx, mtmp.my);
        return true;
    }
    return false;
}
// ============================================================================
// dochugw — C ref: monmove.c:205
// ============================================================================
export async function dochugw(mtmp, chug) {
    const g = game;
    const x = mtmp.mx, y = mtmp.my;
    // C ref: monmove.c:214 — track if hero could already see this monster
    const already_saw_mon = (chug && g.occupation) ? canspotmon(mtmp) : false;
    const rd = chug ? await dochug(mtmp) : 0;
    // C ref: monmove.c:224-236 — if monster moved close enough to threaten
    // the hero during an occupation, interrupt the occupation.
    if (g.occupation && !rd
        && (Hallucination() || (!mtmp.mpeaceful && !noattacks(mtmp.data)))
        && mdistu(mtmp) <= (BOLT_LIM + 1) * (BOLT_LIM + 1)
        && (!already_saw_mon || !couldsee(x, y)
            || distu(x, y) > (BOLT_LIM + 1) * (BOLT_LIM + 1))
        && canspotmon(mtmp) && couldsee(mtmp.mx, mtmp.my)
        && mtmp.mcanmove && !onscary(g.u.ux, g.u.uy, mtmp))
        await stop_occupation();
    return rd;
}
// ============================================================================
// dochug — C ref: monmove.c:707
// ============================================================================
export async function dochug(mtmp) {
    assertNotInModal('dochug');
    const mdat = mtmp.data;
    // C ref: monmove.c:710-714 — check for wait status change.
    if ((mtmp.mstrategy & STRAT_WAITFORU)
        && (m_canseeu(mtmp) || mtmp.mhp < mtmp.mhpmax)) {
        mtmp.mstrategy &= ~STRAT_WAITFORU;
    }
    // C ref: monmove.c:720-728 — frozen/waiting monsters can't act.
    if (!mtmp.mcanmove || (mtmp.mstrategy & STRAT_WAITMASK)) {
        if (Hallucination()) {
            newsym(mtmp.mx, mtmp.my);
        }
        if (mtmp.mcanmove
            && (mtmp.mstrategy & STRAT_CLOSE)
            && !mtmp.msleeping
            && monnear(mtmp, game.u.ux, game.u.uy)) {
            await quest_talk(mtmp);
        }
        return 0;
    }
    // C: sleeping monsters — wake check
    if (mtmp.msleeping) {
        if (!disturb(mtmp)) {
            if (Hallucination()) {
                newsym(mtmp.mx, mtmp.my);
            }
            return 0;
        }
    }
    // C ref: monmove.c:751-752 — active monsters wipe floor engravings.
    wipe_engr_at(mtmp.mx, mtmp.my, 1, false);
    // C: confused recovery (1/50 chance)
    if (mtmp.mconf && !rn2(50))
        mtmp.mconf = 0;
    // C: stunned recovery (1/10 chance)
    if (mtmp.mstun && !rn2(10))
        mtmp.mstun = 0;
    // C ref: monmove.c:766-772 — fleeing teleporting monsters may teleport
    // Teleportation costs a turn (return 0).
    if (mtmp.mflee && !rn2(40) && can_teleport(mdat)
        && !mtmp.iswiz && !noteleport_level(mtmp)) {
        await rloc(mtmp, RLOC_MSG);
        return 0;
    }
    // C ref: monmove.c:775 — monster special responses (shrieker/medusa/erinys).
    await m_respond(mtmp);
    if (DEADMONSTER(mtmp))
        return 1;
    // C ref: monmove.c:779-782 — fleeing monsters might regain courage
    // NOTE: must be AFTER m_respond, matching C ordering
    if (mtmp.mflee && !mtmp.mfleetim && mtmp.mhp === mtmp.mhpmax
        && !rn2(25))
        mtmp.mflee = 0;
    // C ref: monmove.c:765-768 — cease conflict-induced grab/swallow.
    if (mtmp === game.u?.ustuck
        && mtmp.mpeaceful
        && !mtmp.mconf
        && !Conflict()) {
        if (game.u?.uswallow) {
            await expels(mtmp, mtmp.data, true);
        } else if (!sticks(game.youmonst?.data)) {
            set_ustuck(null);
            await You('get released!');
        }
        return 0;
    }
    set_apparxy(mtmp);
    // C ref: monmove.c:799 — covetous monsters may teleport via tactics
    if (is_covetous(mdat)) {
        await tactics(mtmp);
        if (mtmp.mstate)
            return 0;
        set_apparxy(mtmp);
    }
    // C: distfleeck
    const fleeResult = { inrange: 0, nearby: 0, scared: 0 };
    await distfleeck(mtmp, fleeResult);
    // C ref: monmove.c:815-822 — search for and use defensive/misc items
    if (find_defensive(mtmp, false)) {
        if ((await use_defensive(mtmp)) !== 0)
            return 1;
    } else if (await find_misc(mtmp)) {
        if ((await use_misc(mtmp)) !== 0)
            return 1;
    }
    let inrange = fleeResult.inrange;
    let nearby = fleeResult.nearby;
    let scared = fleeResult.scared;
    // C ref: monmove.c:813-827 — Demonic blackmail.
    if (nearby
        && mdat?.msound === MS_BRIBE
        && mtmp.mpeaceful
        && !mtmp.mtame
        && !game.u?.uswallow) {
        if (mtmp.mux !== game.u?.ux || mtmp.muy !== game.u?.uy) {
            await pline(`${cansee(mtmp.mux, mtmp.muy) ? Monnam(mtmp) : 'It'} whispers at thin air.`);
            if (is_demon(game.youmonst?.data)) {
                if (!tele_restrict(mtmp))
                    await rloc(mtmp, RLOC_MSG);
            } else {
                mtmp.minvis = 0;
                mtmp.perminvis = 0;
                if (canseemon(mtmp))
                    set_msg_xy(mtmp.mx, mtmp.my);
                await pline(`${Amonnam(mtmp)} gets angry!`);
                mtmp.mpeaceful = 0;
                set_malign(mtmp);
            }
        } else if (await demon_talk(mtmp)) {
            return 1;
        }
    }
    // C ref: monmove.c:828-830 — watch duty special branch.
    if (is_watch(mdat)) {
        await watch_on_duty_local(mtmp);
    }
    // Phase 2: movement decision (C monmove.c:882-904)
    let panicattk = false;
    // C ref: monmove.c:847-860
    // If monster is in range and should (re)wield a melee weapon,
    // that can consume its turn before m_move().
    if ((!mtmp.mpeaceful || Conflict()) && inrange
        && dist2(mtmp.mx, mtmp.my, mtmp.mux, mtmp.muy) <= 8
        && attacktype(mdat, AT_WEAP)) {
        const mw_tmp = MON_WEP(mtmp);
        if (!(scared && mw_tmp && is_pick(mw_tmp))
            && mtmp.weapon_check === NEED_WEAPON
            && !(mtmp.mtrapped && !nearby && await select_rwep(mtmp))) {
            mtmp.weapon_check = NEED_HTH_WEAPON;
            if ((await mon_wield_item(mtmp)) !== 0)
                return 0;
        }
    }
    let skipMove = (!nearby || mtmp.mflee || scared || mtmp.mconf || mtmp.mstun
        || (mtmp.minvis && !rn2(3))
        || (mdat?.mlet === S_LEPRECHAUN && !findgold_invent() && (findgold_minvent(mtmp) || rn2(2)))
        || (is_wanderer(mdat) && !rn2(4))
        || (Conflict() && !mtmp.iswiz)
        || (!mtmp.mcansee && !rn2(4))
        || mtmp.mpeaceful);
    // Phase 3: movement
    let status = 0;
    let postFleeResult = null;
    if (skipMove) {
        // C ref: monmove.c:906-924 — undirected spellcasting
        const NATTK = 6;
        if (!mtmp.mspec_used
            && dist2(mtmp.mx, mtmp.my, game.u.ux, game.u.uy) <= 49) {
            const mattk = mdat?.mattk;
            if (mattk) {
                for (let ai = 0; ai < Math.min(mattk.length, NATTK); ai++) {
                    const a = mattk[ai];
                    if (a && a.aatyp === AT_MAGC
                        && (a.adtyp === AD_SPEL || a.adtyp === AD_CLRC)) {
                        const castResult = await castmu(mtmp, a, false, false);
                        if (castResult & 1 /* M_ATTK_HIT */) {
                            status = 3; // MMOVE_DONE
                            break;
                        }
                    }
                }
            }
        }
        if (!status) {
            status = await m_move(mtmp);
        }
        // C ref: monmove.c:912 — if monster moved off-map in m_move(),
        // dochug returns immediately and skips distfleeck() recalculation.
        if ((mtmp.mstate ?? MON_FLOOR) !== MON_FLOOR)
            return 1;
        // C ref: recalculate distfleeck AFTER m_move
        if (!mtmp.dead) {
            postFleeResult = { inrange: 0, nearby: 0, scared: 0 };
            await distfleeck(mtmp, postFleeResult);
        }
    }
    // Local helpers matching C behavior
    function m_next2u(mon) { return monnear(mon, game.u?.ux, game.u?.uy); }
    function unstuck(mon) { if (game.u.ustuck === mon) game.u.ustuck = null; }
    // C ref: monmove.c:936 — recalculate after m_move
    if (postFleeResult) {
        inrange = postFleeResult.inrange;
        nearby = postFleeResult.nearby;
        scared = postFleeResult.scared;
    }
    // C ref: monmove.c:938-979 — switch on m_move result
    switch (status) {
    case MMOVE_NOMOVES:
        if (scared) panicattk = true;
        // FALLTHROUGH
    case MMOVE_NOTHING: // no movement, can still attack
    case MMOVE_DONE: // absolutely no movement
        if (mtmp.isgd && (DEADMONSTER(mtmp) || mtmp.mx === 0))
            return 1;
        if (Hallucination()) newsym(mtmp.mx, mtmp.my);
        break;
    case MMOVE_MOVED: // monster moved
        if (mtmp === game.u.ustuck && !m_next2u(mtmp))
            unstuck(mtmp);
        if (helpless(mtmp)) return 0;
        // C ref: monmove.c:966-970 — monsters can move and shoot on same turn
        if (!nearby
            && (ranged_attk_available(mtmp)
                || attacktype(mdat, AT_WEAP)
                || find_offensive(mtmp)))
            break; // fall through to Phase 4
        if (engulfing_u(mtmp))
            return await mattacku_canonical(mtmp);
        return 0;
    case MMOVE_DIED:
        return 1;
    }
    // Phase 4: Standard Attacks
    // C ref: monmove.c:986-997 — uses post-m_move inrange/scared
    if (status !== MMOVE_DONE
        && (!mtmp.mpeaceful || (Conflict() && !resist_conflict(mtmp)))) {
        if (((inrange && !scared) || panicattk) && !noattacks(mdat)
            && (Upolyd() ? game.u.mh : game.u.uhp) > 0) {
            if (await mattacku_canonical(mtmp))
                return 1;
        }
    }
    return (status === MMOVE_DIED) ? 1 : 0;
}
// Old local mattacku/hitmu/mhitm_mgc_atk_negated removed —
// dochug now uses canonical mattacku from mhitu.js.
import { You, You_hear, You_see, pline, set_msg_xy } from './pline.js';
import { castmu } from './mcastu.js';
import { dog_move } from './dogmove.js';
// ============================================================================
// grow_up — C ref: makemon.c:2059
// ============================================================================
export function grow_up(mtmp, victim) {
    if (!mtmp || DEADMONSTER(mtmp))
        return null;
    const ptr = mtmp.data;
    let max_increase, cur_increase;
    if (victim) {
        // C ref: makemon.c:2092-2095 — killed another monster
        const victimLevel = victim.m_lev ?? victim.data?.mlevel ?? 0;
        max_increase = rnd(victimLevel + 1);
        cur_increase = (max_increase > 1) ? rn2(max_increase) : 0;
    } else {
        // C ref: makemon.c:2100 — gain level potion or wraith corpse
        max_increase = cur_increase = rnd(8);
    }
    mtmp.mhpmax = (mtmp.mhpmax || 0) + max_increase;
    mtmp.mhp = (mtmp.mhp || 0) + cur_increase;
    // C ref: makemon.c:2107-2108 — threshold check and level-up logic
    // not fully ported. The RNG calls (rnd/rn2) above are the critical
    // part for parity; the actual level-up mechanics are deferred.
    return ptr || null;
}
// ============================================================================
// m_move — C ref: monmove.c:1733
// ============================================================================
export async function m_move(mtmp) {
    assertNotInModal('m_move');
    pushRngLogEntry('>m_move');
    const g = game;
    const log_m_move_exit = (code) => {
        if (!g.program_state?.gameover)
            pushRngLogEntry(`<m_move=${code}`);
    };
    const omx = mtmp.mx, omy = mtmp.my;
    // C ref: monmove.c:1731 — trapped monster tries to escape before moving
    if (mtmp.mtrapped) {
        const i = await mintrap(mtmp, 0);
        if (i === 1 /* Trap_Killed_Mon */) {
            newsym(mtmp.mx, mtmp.my);
            log_m_move_exit(2);
            return 2; // MMOVE_DIED
        }
        if (i === 2 /* Trap_Caught_Mon */) {
            log_m_move_exit(0);
            return 0; // MMOVE_NOTHING
        }
    }
    // C: mtmp->meating check
    if (mtmp.meating) {
        mtmp.meating--;
        log_m_move_exit(3);
        return 3; // MMOVE_DONE
    }
    const ptr = mtmp.data;
    const floorObj = fobj_at(mtmp.mx, mtmp.my);
    if (hides_under(ptr)
        && can_hide_under_obj_local(floorObj)
        && rn2(10)) {
        log_m_move_exit(0);
        return 0; // MMOVE_NOTHING
    }
    set_apparxy(mtmp);
    const can_open = !(nohands_fn(ptr) || verysmall_fn(ptr));
    const can_unlock = can_open && monhaskey_fn(mtmp);
    let can_tunnel = tunnels(ptr) && !is_rogue_level(g.u?.uz);
    if (can_tunnel && needspick(ptr)
        && ((!mtmp.mpeaceful || Conflict())
            && dist2(mtmp.mx, mtmp.my, mtmp.mux, mtmp.muy) <= 8)) {
        can_tunnel = false;
    }
    // C: if tame, call dog_move
    if (mtmp.mtame) {
        // C ref: monmove.c:1771-1772 — tame movement always returns through
        // postmov(), with dog_move() as mmoved.
        const ret = await postmov(
            mtmp, omx, omy,
            await dog_move(mtmp),
            can_open, can_unlock, can_tunnel
        );
        log_m_move_exit(ret);
        return ret;
    }
    // C ref: monmove.c:1824-1845 — shopkeeper/guard/priest special movement.
    if (mtmp.isshk || mtmp.isgd || mtmp.ispriest) {
        const xm = mtmp.isshk
            ? await (await import('./shknam.js')).shk_move(mtmp)
            : (mtmp.isgd
                ? await (await import('./vault.js')).gd_move(mtmp)
                : await (await import('./priest.js')).pri_move(mtmp));
        if (xm === -2) {
            log_m_move_exit(2);
            return 2; // MMOVE_DIED
        }
        if (xm === -1) {
            // C ref: monmove.c:1833-1846 — "-1" means "let m_move do it";
            // keep running the regular m_move path (do not return via postmov).
        }
        else if (xm === 0 || xm === 1) {
            const ret = await postmov(mtmp, omx, omy, xm === 1 ? 1 : 0, can_open, can_unlock, can_tunnel);
            log_m_move_exit(ret);
            return ret;
        }
    }
    // Goal and approach direction — C ref: monmove.c:1870-1908
    let ggx = mtmp.mux ?? g.u?.ux ?? mtmp.mx;
    let ggy = mtmp.muy ?? g.u?.uy ?? mtmp.my;
    let appr = mtmp.mflee ? -1 : 1;
    let preferredrange_min = 0;
    let preferredrange_max = 0;
    let getitems = false;
    if (mtmp.mconf || engulfing_u(mtmp)) {
        appr = 0;
    } else {
        // C ref: monmove.c:1883-1886 — should_see: can monster plausibly see hero?
        const should_see = couldsee(omx, omy)
            && (g.level?.at(ggx, ggy)?.lit || !g.level?.at(omx, omy)?.lit)
            && (dist2(omx, omy, ggx, ggy) <= 36);
        // C ref: monmove.c:1863-1870 — conditions that make monster wander (appr=0)
        if (!mtmp.mcansee
            || (should_see && Invis() && !perceives(ptr) && rn2(11))
            || (U_AP_TYPE() === M_AP_OBJECT
                && (game.youmonst?.mappearance ?? 0) === STRANGE_OBJECT)
            || g.u?.uundetected
            || (U_AP_TYPE() === M_AP_OBJECT
                && (game.youmonst?.mappearance ?? 0) === GOLD_PIECE
                && !likes_gold(ptr))
            || (mtmp.mpeaceful && !mtmp.isshk)
            || ((ptr === mons[PM_STALKER] || ptr?.mlet === S_BAT
                 || ptr?.mlet === S_LIGHT) && !rn2(3)))
            appr = 0;
        if (appr === 1 && leppie_avoidance(mtmp))
            appr = -1;
        const prmin = { value: 0 };
        const prmax = { value: 0 };
        appr = m_balks_at_approaching(appr, mtmp, prmin, prmax);
        preferredrange_min = prmin.value;
        preferredrange_max = prmax.value;
        // C ref: monmove.c:1899-1905 — track-based goal when monster can't see hero
        if (!should_see && can_track(ptr)) {
            const cp = gettrack(omx, omy);
            if (cp) {
                ggx = cp.x;
                ggy = cp.y;
            }
        }
    }
    // C ref: monmove.c:1910-1923
    if ((!mtmp.mpeaceful || !rn2(10)) && !is_rogue_level(g.u?.uz)) {
        // C ref: monmove.c:1916-1919 — uses ACURRSTR (condensed 3-25), not raw ACURR
        const in_line = lined_up(mtmp)
            && (distmin(mtmp.mx, mtmp.my, mtmp.mux, mtmp.muy)
                <= (throws_rocks(g.youmonst?.data) ? 20 : (Math.trunc(ACURRSTR() / 2) + 1)));
        if (appr !== 1 || !in_line) {
            getitems = true;
        }
    }
    // C ref: monmove.c:1904 — m_search_items redirects monster goal to nearby items
    if (getitems && !mtmp.mtame) {
        const searchResult = { ggx, ggy, mmoved: 0, appr };
        if (await m_search_items(mtmp, searchResult)) {
            // C ref: monmove.c:1928 — return through postmov() even on item short-circuit.
            const ret = await postmov(
                mtmp, omx, omy, searchResult.mmoved,
                can_open, can_unlock, can_tunnel,
            );
            log_m_move_exit(ret);
            return ret;
        }
        ggx = searchResult.ggx;
        ggy = searchResult.ggy;
        appr = searchResult.appr;
    }
    // Compute allowflags (C ref: mon.c mon_allowflags + monmove.c m_move)
    const flag = mon_allowflags(mtmp);
    // Find valid positions
    const positions = mfndpos(mtmp, flag);
    const cnt = positions.length;
    // C ref: monmove.c:1950-1954 — no positions available
    if (cnt === 0 && !is_unicorn(mtmp.data)) {
        if (find_defensive(mtmp, true) && (await use_defensive(mtmp)))  {
            log_m_move_exit(MMOVE_DONE);
            return MMOVE_DONE;
        }
        log_m_move_exit(MMOVE_NOMOVES);
        return MMOVE_NOMOVES;
    }
    if (cnt === 0) {
        log_m_move_exit(MMOVE_NOMOVES);
        return MMOVE_NOMOVES;
    }
    const jcnt = Math.min(MTSZ, cnt - 1);
    let nix = omx, niy = omy;
    let chi = -1;
    let chcnt = 0;
    let nidist = dist2(nix, niy, ggx, ggy);
    // C ref: monmove.c:1934-1936 — shortsighted levels limit monster pursuit range
    if (!mtmp.mpeaceful && g.level?.flags?.shortsighted
        && nidist > (couldsee(nix, niy) ? 144 : 36) && appr === 1)
        appr = 0;
    // C ref: monmove.c:1940-1945 — unicorns on no-teleport levels avoid
    // line-to-hero squares if they have any alternative.
    let avoid = false;
    if (is_unicorn(ptr) && noteleport_level(mtmp)) {
        for (let i = 0; i < cnt; i++) {
            if (!(positions[i].info & NOTONL)) {
                avoid = true;
                break;
            }
        }
    }
    let mmoved = 0; // MMOVE_NOTHING
    const better_with_displacing = should_displace(mtmp, positions, ggx, ggy);
    for (let i = 0; i < cnt; i++) {
        const nx = positions[i].x;
        const ny = positions[i].y;
        const info = positions[i].info || 0;
        if (avoid && (info & NOTONL))
            continue;
        // C ref: monmove.c:1971-1972
        if (m_avoid_kicked_loc(mtmp, nx, ny))
            continue;
        // C ref: monmove.c:1975-1977
        if (map_m_at(nx, ny) && (info & ALLOW_MDISP) && !(info & ALLOW_M)
            && !better_with_displacing) {
            continue;
        }
        // Backtrack avoidance
        if (appr !== 0 && Array.isArray(mtmp.mtrack)) {
            let skipPos = false;
            for (let j = 0; j < jcnt; j++) {
                const prev = mtmp.mtrack[j];
                if (prev && nx === prev.x && ny === prev.y) {
                    if (rn2(4 * (cnt - j))) {
                        skipPos = true;
                        break;
                    }
                }
            }
            if (skipPos) continue;
        }
        const ndist = dist2(nx, ny, ggx, ggy);
        const nearer = (ndist < nidist);
        let randomChoose = false;
        if (appr === 0) {
            const choiceBound = ++chcnt;
            const choiceRoll = rn2(choiceBound);
            randomChoose = (choiceRoll === 0);
        }
        if ((appr === 1 && nearer)
            || (appr === -1 && !nearer)
            || (appr === -2
                && ((ndist <= preferredrange_min && !nearer)
                    || (ndist >= preferredrange_max && nearer)))
            || randomChoose
            || (mmoved === 0)) {
            nix = nx;
            niy = ny;
            nidist = ndist;
            chi = i;
            mmoved = 1; // MMOVE_MOVED
        }
    }
    if (mmoved && m_digweapon_check(mtmp, nix, niy)) {
        log_m_move_exit(3);
        return 3; // MMOVE_DONE
    }
    // C ref: monmove.c:2025-2061 — resolve target occupancy before movement.
    if (mmoved && chi >= 0) {
        const info = positions[chi]?.info || 0;
        if (info & ALLOW_U) {
            nix = mtmp.mux;
            niy = mtmp.muy;
        }
        if (u_at(nix, niy)) {
            log_m_move_exit(0);
            return 0; // MMOVE_NOTHING
        }
        if ((info & ALLOW_M) || (nix === mtmp.mux && niy === mtmp.muy)) {
            const ret = await m_move_aggress(mtmp, nix, niy);
            log_m_move_exit(ret);
            return ret;
        }
        if (info & ALLOW_MDISP) {
            const mtmp2 = map_m_at(nix, niy);
            const mstatus = mtmp2 ? await mdisplacem(mtmp, mtmp2, false) : 0;
            if (mstatus & (M_ATTK_AGR_DIED | M_ATTK_DEF_DIED)) {
                log_m_move_exit(2);
                return 2; // MMOVE_DIED
            }
            if (mstatus & M_ATTK_HIT) {
                log_m_move_exit(1);
                return 1; // MMOVE_MOVED
            }
            log_m_move_exit(3);
            return 3; // MMOVE_DONE
        }
    }
    if (mmoved) {
        // C ref: monmove.c:2038-2039 — abort move if region callbacks disallow it.
        if (!m_in_out_region(mtmp, nix, niy)) {
            log_m_move_exit(MMOVE_DONE);
            return MMOVE_DONE;
        }
        await m_postmove_effect(mtmp);
        // C ref: monmove.c:2047-2057 — move on map via remove/place; for
        // long worms, keep tail connectivity with worm_move().
        remove_monster(omx, omy);
        place_monster(mtmp, nix, niy);
        if (mtmp.wormno)
            worm_move(mtmp);
        maybe_unhide_at(mtmp.mx, mtmp.my);
        mon_track_add(mtmp, omx, omy);
        const ret = await postmov(mtmp, omx, omy, mmoved, can_open, can_unlock, can_tunnel);
        log_m_move_exit(ret);
        return ret;
    }
    // C ref: monmove.c:2067-2074 — long worm shrinks tail when it fails to move.
    if (mtmp.wormno)
        worm_nomove(mtmp);
    log_m_move_exit(0);
    return 0;
}
 
// C ref: monmove.c:2108 m_move_aggress()
async function m_move_aggress(mtmp, x, y) {
    let mstatus = 0;
    const mtmp2 = map_m_at(x, y);
    if (mtmp2) {
        mstatus = await mattackm(mtmp, mtmp2);
    }
    if ((mstatus & M_ATTK_AGR_DIED) || DEADMONSTER(mtmp)) {
        return 2; // MMOVE_DIED
    }
    if ((mstatus & (M_ATTK_HIT | M_ATTK_DEF_DIED)) === M_ATTK_HIT
        && rn2(4) && (mtmp2?.movement ?? 0) > rn2(NORMAL_SPEED)) {
        if ((mtmp2.movement ?? 0) > NORMAL_SPEED)
            mtmp2.movement -= NORMAL_SPEED;
        else
            mtmp2.movement = 0;
        mstatus = await mattackm(mtmp2, mtmp);
        if (mstatus & M_ATTK_DEF_DIED)
            return 2; // MMOVE_DIED
    }
    return 3; // MMOVE_DONE
}
// wake_nearto / wake_nearby / wakeup — use canonical versions from mon.js
// ============================================================================
// dist2 / mnearto — re-export from hacklib for convenience
// ============================================================================
// C ref: mon.c:4018 mnearto — place monster near (x,y)
// Returns: 2 if another monster was displaced, 1 if placed, 0 if failed
export async function mnearto(mtmp, x, y, move_other, rlocflags) {
    if (process?.env?.WEBHACK_MNEARTO_TRACE === '1') {
        pushRngLogEntry(
            `^mnearto_in[m=${mtmp?.mnum ?? -1} id=${mtmp?.m_id ?? -1} from=${mtmp?.mx ?? -1},${mtmp?.my ?? -1} to=${x},${y} move_other=${move_other ? 1 : 0}]`
        );
    }
    let othermon = null;
    let res = 1;
    if (mtmp.mx === x && mtmp.my === y && map_m_at(x, y) === mtmp)
        return res;
    if (move_other) {
        othermon = map_m_at(x, y);
        if (othermon) {
            if (othermon.wormno) remove_worm(othermon);
            else remove_monster(x, y);
            // Take othermon off the map temporarily
            othermon.mx = othermon.my = 0;
            othermon.mstate = (othermon.mstate || 0) | 0x01; // MON_OFFMAP
        }
    }
    let newx = x;
    let newy = y;
    if (!goodpos(newx, newy, mtmp, 0)) {
        const mm = { x: newx, y: newy };
        if (!enexto(mm, newx, newy, mtmp.data) || !isok(mm.x, mm.y)) {
            if (othermon) {
                // Can't place — deal with displaced monster
                // C ref: deal_with_overcrowding — for now, try rloc
                othermon.mx = x;
                othermon.my = y;
                othermon.mstate = (othermon.mstate || 0) & ~0x01;
            }
            return 0;
        }
        newx = mm.x;
        newy = mm.y;
    }
    await rloc_to_flag(mtmp, newx, newy, rlocflags);
    if (move_other && othermon) {
        res = 2;
        if (!await mnearto(othermon, x, y, false, rlocflags)) {
            // deal_with_overcrowding — try rloc as fallback
            othermon.mx = x;
            othermon.my = y;
            othermon.mstate = (othermon.mstate || 0) & ~0x01;
        }
    }
    return res;
}
// ============================================================================
// m_avoid_kicked_loc — C ref: monmove.c:1297
// ============================================================================
// Peaceful/tame monster avoids stepping on the last-kicked location next to hero.
export function m_avoid_kicked_loc(mtmp, nx, ny) {
    if ((mtmp.mpeaceful || mtmp.mtame)
        && mtmp.mcansee
        && !mtmp.mconf && !mtmp.mstun
        && !Conflict()
        && game.kickedloc && isok(game.kickedloc.x, game.kickedloc.y)
        && nx === game.kickedloc.x && ny === game.kickedloc.y
        && game.u && Math.abs(nx - game.u.ux) <= 1 && Math.abs(ny - game.u.uy) <= 1)
        return true;
    return false;
}
// ============================================================================
// m_avoid_soko_push_loc — C ref: monmove.c:1313
// ============================================================================
export function m_avoid_soko_push_loc(mtmp, nx, ny) {
    const ux = game.u?.ux ?? nx;
    const uy = game.u?.uy ?? ny;
    const bx = nx + sgn(ux - nx);
    const by = ny + sgn(uy - ny);
    const hasBoulder = !!sobj_at(BOULDER, bx, by);
    const isSoko = Sokoban();
    if (isSoko
        && (mtmp.mpeaceful || mtmp.mtame)
        && !mtmp.mconf && !mtmp.mstun
        && !Conflict()
        && dist2(nx, ny, ux, uy) === 4
        && hasBoulder)
        return true;
    return false;
}
/*monmove.js*/