All files / js detect.js

30.58% Statements 474/1550
46.95% Branches 54/115
38% Functions 19/50
30.58% Lines 474/1550

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 155173x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 29865x 29865x 29865x 29865x 29865x 29865x 29865x 29865x 29865x 22487x 3964x 3964x 3964x 3964x 3964x 3964x 3964x 3964x           22487x 1263x 1263x 1263x 1263x 1263x 1263x 22487x 29865x 29865x 29865x 29865x 29865x 29865x 29865x 29865x     29865x 73x 73x 29659x   3x     73x 3x 3x 3x 3x 3x 36x 36x 36x 36x 3x 73x 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x 29862x 73x           73x   73x 73x     73x 73x 73x 43x 43x 43x 43x     43x 43x 43x       43x 43x 43x                       43x 43x 73x 73x 1x 1x 1x 1x 1x             1x 1x 1x       1x 73x   73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                           73x 73x 73x                           73x 73x               73x 73x 73x                               73x 73x                         73x 73x 73x 73x                                                 73x 73x 321x 321x 321x 17x 17x               17x                       17x 17x 17x 321x 321x 73x 73x                                                                                       73x 73x 73x 73x 73x 73x 73x 73x                                                                                                                                               73x                                                                                                 73x 73x 73x 73x                                                                                                                                                                                                           73x 73x 73x 73x 73x                                                                                                                                                                                                                                                                         73x 73x 73x 73x 73x                                                                                                 73x 73x 73x 73x 73x                                                                                                                                                 73x 73x 73x                                                                       73x 73x 73x 73x                                           73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                                                                                                                                                                                                                                                                             73x 73x 73x 73x 29862x 29862x 29862x 29862x 29862x 20x 20x 20x 29862x 29862x 29862x 29862x 29762x 29762x 103x 29762x     29762x 29862x 29862x 29862x 29862x 29862x 73x 73x 73x 73x 18x 18x 18x 1422x 29862x 29862x 1422x 18x         18x 18x 18x 18x 18x 73x 73x 73x 73x                                                                                                                                                     73x 73x 73x 10x 10x   10x 10x 10x 10x 10x 10x 10x 10x 73x 73x 3x 3x 3x     3x 3x 73x 73x 73x 73x 159x 159x 159x 159x 159x 159x 159x 159x 159x 3x 3x 3x 3x 3x 3x 3x 159x               159x             159x               159x 159x 159x 159x 159x 159x 159x 159x 159x                                               159x       159x 73x 73x 73x 73x                                                                                                             73x 73x 73x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 79x 1659x 1659x 1659x   1659x 1659x 1659x 1659x         1659x 1659x 79x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x 73x 73x 73x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 2x         2x             2x         2x 2x             2x           2x 2x 2x 73x  
// detect.js — Detection spells and scrolls (port of detect.c)
// C ref: detect.c — 2420 lines
//
// Detection functions for gold, food, objects, monsters, traps,
// mapping, clairvoyance, crystal ball, and secret door conversion.
import { game } from './gstate.js';
import { A_INT, A_WIS, ARTICLE_THE, ARTICLE_YOUR, BEAR_TRAP, BOLT_LIM, COLNO, CORR, COULD_SEE, D_BROKEN, D_CLOSED, D_ISOPEN, D_LOCKED, D_NODOOR, D_TRAPPED, DOOR, Has_contents, I_SPECIAL, IN_SIGHT, IS_DOOR, IS_FURNITURE, Is_rogue_level, IS_WALL, isok, KILLED_BY_AN, LAVAPOOL, LAVAWALL, M_AP_FURNITURE, M_AP_OBJECT, M_AP_TYPE, Never_mind, NO_PART, OBJ_AT, ROOM, ROWNO, SCORR, SDOOR, STATUE_TRAP, SUPPRESS_SADDLE, SVALL, TER_DETECT, TER_FULL, TER_MAP, TER_MON, TER_OBJ, TER_TRP, TIMEOUT, TRAPPED_CHEST, TRAPPED_DOOR, u_at, WM_MASK } from './const.js';
import { COIN_CLASS, FOOD_CLASS, POTION_CLASS, SCROLL_CLASS, ROCK_CLASS, SPBOOK_CLASS, MAXOCLASSES, GOLD_PIECE, CHEST, LARGE_BOX, CRYSTAL_BALL, Is_box, SchroedingersBox } from './objects.js';
import { MAXMCLASSES, PM_GOLD_GOLEM, PM_LONG_WORM, PM_LONG_WORM_TAIL,
         PM_TENGU, S_EEL, S_WORM_TAIL } from './monsters.js';
import { S_hcdoor, S_vcdoor, S_corr, S_litcorr, S_darkroom, S_room, S_stone, S_tree, defsyms } from './symbols.js';
import { rn2, rnd, rnl, rn2_on_display_rng, pushRngLogEntry } from './rng.js';
import { pline, set_msg_xy, You, You_feel, You_see, Your, You_hear, pline_The, verbalize } from './pline.js';
import { Blind, Clairvoyant, Confusion, Deaf, Hallucination, Maybe_Half_Phys, Stunned, Underwater } from './macros.js';
import { back_to_glyph, canspotmon, cls, cmap_to_glyph, delay_output, display_nhwindow, display_self, docrt, docrt_cls, feel_newsym, flush_screen, glyph_at, glyph_is_monster, glyph_to_mon, map_invisible, map_object, map_trap, newsym, recalc_block_point, seemimic, sensemon, show_glyph, show_glyph_cell, terrain_sym_color, unblock_point, unmap_invisible, unmap_object } from './display.js';
import { cmap_to_glyph as _cmap_to_glyph_int_detect, mon_to_glyph as _mon_to_glyph_int, pet_to_glyph as _pet_to_glyph_int, detected_mon_to_glyph as _detected_mon_to_glyph_int, trap_to_glyph, glyph_is_trap, GLYPH_INVISIBLE, GLYPH_UNEXPLORED } from './glyph.js';
 
// Local convenience wrappers that build a {mnum, female} record from the
// JS mtmp shape and invoke the canonical glyph encoders.
function _mtmp_to_glyph(mtmp, fn) {
    const mnum = (mtmp && Number.isInteger(mtmp.mnum)) ? mtmp.mnum : monsndx(mtmp?.data);
    return fn({ mnum: Math.max(0, mnum), female: mtmp?.female ?? false },
              rn2_on_display_rng, Hallucination());
}
function mon_to_glyph(mtmp, _rng) { return _mtmp_to_glyph(mtmp, _mon_to_glyph_int); }
function pet_to_glyph(mtmp, _rng) { return _mtmp_to_glyph(mtmp, _pet_to_glyph_int); }
function detected_mon_to_glyph(mtmp, _rng) { return _mtmp_to_glyph(mtmp, _detected_mon_to_glyph_int); }
import { cansee, do_clear_area } from './vision.js';
import { exercise, ACURR } from './attrib.js';
import { nomul } from './cmd.js';
import { body_part, poly_gender } from './polyself.js';
import { makeplural, an, the, xname, Tobjnam } from './objnam.js';
import { depth, s_suffix } from './hacklib.js';
import { DEADMONSTER, a_monnam, see_monsters, wake_nearto, x_monnam, y_monnam } from './mon.js';
import { findgold } from './steal.js';
import { helpless, losehp, money_cnt } from './hack.js';
import { hidden_gold } from './vault.js';
import { consume_obj_charge, currency, makeknown, observe_object, useup } from './invent.js';
import { levl, m_at, t_at } from './map_access.js';
import { hides_under, is_hider, monsndx, resists_blnd, warning_of } from './mondata.js';
import { closed_door } from './monmove.js';
import { random_object, random_monster } from './glyph.js';
import { def_oc_syms, def_monsyms } from './symbols.js';
import { def_char_is_furniture, def_char_to_objclass, is_cmap_furniture, pchar_sym } from './drawing.js';
import { make_confused, make_blinded, make_hallucinated, strange_feeling_fn } from './potion.js';
import { hcolor } from './do_name.js';
import { activate_statue_trap, b_trapped, trapname } from './trap.js';
import { find_drawbridge, is_pool, open_drawbridge } from './dbridge.js';
import { ynFunction } from './input.js';
import { NO_COLOR } from './terminal.js';
import { is_quest_artifact } from './artifact.js';
import { getpos } from './getpos.js';
import { glyph_is_invisible } from './glyph.js';
// ── Local stubs for deps not yet exported ──
// These will be replaced with real imports as the functions are ported.
const ALL_CLASSES = MAXOCLASSES + 1;
// Clairvoyant: imported from macros.js
// SchroedingersBox: imported from objects.js
// Is_box: imported from objects.js
// Glyph stubs — these are display subsystem internals, not yet exported.
// show_glyph: imported from display.js
// map_object: imported from display.js
// map_trap: imported from display.js
// unmap_object: imported from display.js
// Sets the terrain glyph for a magically-revealed tile.
function magic_map_background(x, y, show) {
    const loc = levl(x, y);
    if (!loc) return;
    // C ref: display.c:233 magic_map_background()
    // Compute terrain display (equivalent to back_to_glyph)
    const result = terrain_sym_color(loc, x, y);
    let { ch, color, decgfx, symidx } = result;
    // C ref: display.c:242-249 — correct for out-of-sight unlit rooms/corridors
    if (!cansee(x, y) && !loc.waslit) {
        if (loc.typ === ROOM) {
            // C ref: display.c uses flags.dark_room && iflags.use_color.
            if (game.flags?.dark_room && game.iflags?.wc_color !== false) {
                const { ch: dch, decgfx: ddec } = pchar_sym(S_darkroom);
                ch = dch;
                color = defsyms[S_darkroom]?.color ?? NO_COLOR;
                decgfx = ddec;
                symidx = S_darkroom;
            } else {
                ch = ' ';
                color = NO_COLOR;
                decgfx = false;
                symidx = -1;
            }
        } else if (loc.typ === CORR) {
            const { ch: cch, decgfx: cdec } = pchar_sym(S_corr);
            ch = cch;
            color = defsyms[S_corr]?.color ?? NO_COLOR;
            decgfx = cdec;
            symidx = S_corr;
        }
    }
    // Store memory glyph so newsym's not-visible path renders it.
    // symidx=-1 (unlit out-of-sight, not-dark-room) maps to stone.
    const glyphSym = (Number.isFinite(symidx) && symidx >= 0) ? symidx : 0;
    loc.glyph = _cmap_to_glyph_int_detect(glyphSym);
    // Mark as seen
    if (!game._terrain_memory) game._terrain_memory = {};
    game._terrain_memory[`${x},${y}`] = true;
    if (show) {
        show_glyph_cell(x, y, ch, color, decgfx);
    }
}
// trap_to_glyph / back_to_glyph imported from display.js / glyph.js below.
// glyph_is_monster: imported from display.js
function glyph_is_object(_g) { return false; }
function glyph_is_swallow(_g) { return false; }
function glyph_is_cmap(_g) { return false; }
function glyph_to_cmap(_g) { return 0; }
function glyph_to_obj(_g) { return 0; }
// glyph_to_mon: imported from display.js
async function flash_glyph_at(x, y, tg, rpt) {
    const loc = levl(x, y);
    const glyph = [tg, (game.level?.flags?.hero_memory ? (loc?.glyph ?? 0) : back_to_glyph(x, y))];
    const total = (rpt | 0) * 2;
    for (let i = 0; i < total; i++) {
        show_glyph(x, y, glyph[i % 2]);
        await flush_screen(1);
        await delay_output();
    }
}
// display_self: imported from display.js
// C ref: detect.c:107 browse_map()
async function browse_map(ter_typ, ter_explain) {
    const g = game;
    const dummy_pos = { x: g.u.ux, y: g.u.uy };
    const had_autodescribe = Object.prototype.hasOwnProperty.call(g.iflags || {}, 'autodescribe');
    const prev_autodescribe = g.iflags?.autodescribe;
    g.iflags = g.iflags || {};
    g.iflags.autodescribe = true;
    g.iflags.terrainmode = ter_typ;
    try {
        await getpos(dummy_pos, false, ter_explain);
    } finally {
        g.iflags.terrainmode = 0;
        if (had_autodescribe) {
            g.iflags.autodescribe = prev_autodescribe;
        } else {
            delete g.iflags.autodescribe;
        }
    }
}
function unconstrain_map() {
    const g = game;
    const u = g.u;
    const res = !!(u.uinwater || u.uburied || u.uswallow);
    g.iflags = g.iflags || {};
    g.iflags.save_uinwater = u.uinwater; u.uinwater = 0;
    g.iflags.save_uburied = u.uburied; u.uburied = 0;
    g.iflags.save_uswallow = u.uswallow; u.uswallow = 0;
    return res;
}
function reconstrain_map() {
    const g = game;
    const u = g.u;
    g.iflags = g.iflags || {};
    u.uinwater = g.iflags.save_uinwater || 0; g.iflags.save_uinwater = 0;
    u.uburied = g.iflags.save_uburied || 0; g.iflags.save_uburied = 0;
    u.uswallow = g.iflags.save_uswallow || 0; g.iflags.save_uswallow = 0;
}
async function map_redisplay() {
    reconstrain_map();
    // JS docrt is split: docrt_cls() performs C's cls()/window clear path,
    // docrt() performs C's docrt_flags() redraw path.
    await docrt_cls();
    await docrt();
    // TODO: if (Underwater) under_water(2);
    // TODO: if (u.uburied) under_ground(2);
}
// get_obj_location: import from mkobj.js if needed
function room_discovered(_roomno) { }
// C ref: display.h:221 covers_objects / covers_traps
function covers_objects(x, y) {
    const t = levl(x, y)?.typ;
    return (is_pool(x, y) && !Underwater()) || t === LAVAPOOL || t === LAVAWALL;
}
function covers_traps(x, y) { return covers_objects(x, y); }
// yn_function: use ynFunction imported from input.js
async function yn_function(query, resp, def, flag) { return await ynFunction(query, resp, def, flag); }
// set_msg_xy: imported from pline.js
// feel_newsym: imported from display.js
function openholdingtrap(_mon, _dummy) { return false; }
function openfallingtrap(_mon, _flag, _dummy) { return false; }
// activate_statue_trap: imported from trap.js
// C ref: detect.c:1964 mfind0 — detect a monster during searching
export async function mfind0(mtmp, via_warning) {
    const x = mtmp.mx, y = mtmp.my;
    let found_something = false;
    if (via_warning) return -1; // TODO: warning_of check
    if (mtmp.m_ap_type) {
        seemimic(mtmp);
        found_something = true;
    } else {
        found_something = !canspotmon(mtmp);
        if (mtmp.mundetected) {
            mtmp.mundetected = 0;
            found_something = true;
        }
        newsym(x, y);
    }
    if (found_something) {
        exercise(A_WIS, true);
        if (!canspotmon(mtmp)) {
            map_invisible(x, y);
            set_msg_xy(x, y);
            await You_feel('an unseen monster!');
        } else if (!sensemon(mtmp)) {
            set_msg_xy(x, y);
            await You(`find ${mtmp.mtame ? y_monnam(mtmp) : a_monnam(mtmp)}.`);
        }
        return 1;
    }
    return 0;
}
// C ref: detect.c:1935 find_trap — reveal a trap found by searching
export async function find_trap(trap) {
    let cleared = false;
    trap.tseen = 1;
    exercise(A_WIS, true);
    feel_newsym(trap.tx, trap.ty);
    if (Hallucination()) {
        // Too much clutter — clear and show trap
        await cls();
        map_trap(trap, 1);
        display_self();
        cleared = true;
    }
    set_msg_xy(trap.tx, trap.ty);
    await You(`find ${an(trapname(trap.ttyp, false))}.`);
    if (cleared) {
        await display_nhwindow('map', true);
        await docrt();
    }
}
// warning_of: imported from mondata.js
function map_engraving(_ep, _show) { }
const FOUND_FLASH_COUNT = 6;
const WIN_MAP = 2; // stub
const DEF_MIMIC_DEF = ']';
const DEF_MIMIC = 'm';
const OTRAP_NONE = 0;
const OTRAP_HERE = 1;
const OTRAP_THERE = 2;
// ── Helper: levl access ──
// ── o_in: recursively search obj for an object in class oclass ──
// C ref: detect.c:200
export function o_in(obj, oclass) {
    if (!obj || !oclass) return null;
    if (obj.oclass === oclass) return obj;
    if (Has_contents(obj) && !SchroedingersBox(obj)) {
        for (let otmp = obj.cobj; otmp; otmp = otmp.nobj) {
            if (otmp.oclass === oclass) return otmp;
            if (Has_contents(otmp)) {
                const temp = o_in(otmp, oclass);
                if (temp) return temp;
            }
        }
    }
    return null;
}
// ── o_material: recursively search obj for specified material ──
// C ref: detect.c:229
export function o_material(obj, material) {
    if (!obj) return null;
    if (game.objects[obj.otyp]?.oc_material === material) return obj;
    if (Has_contents(obj)) {
        for (let otmp = obj.cobj; otmp; otmp = otmp.nobj) {
            if (game.objects[otmp.otyp]?.oc_material === material) return otmp;
            if (Has_contents(otmp)) {
                const temp = o_material(otmp, material);
                if (temp) return temp;
            }
        }
    }
    return null;
}
// ── observe_recursively: mark object and contents as seen ──
// C ref: detect.c:249
function observe_recursively(obj) {
    observe_object(obj);
    if (Has_contents(obj)) {
        for (let otmp = obj.cobj; otmp; otmp = otmp.nobj)
            observe_recursively(otmp);
    }
}
// observe_object: canonical version in invent.js (removed local duplicate)
// ── check_map_spot: check for outdated object display ──
// C ref: detect.c:262
function check_map_spot(x, y, oclass, material) {
    const glyph = glyph_at(x, y);
    if (glyph_is_object(glyph)) {
        if (oclass === ALL_CLASSES) {
            const g = game;
            const floorObj = g.level?.objects?.find(o => o.ox === x && o.oy === y);
            const mtmp = m_at(x, y);
            return !(floorObj || (mtmp && mtmp.minvent));
        } else {
            // Simplified — full glyph_to_obj matching not yet available
            return false;
        }
    }
    return false;
}
// ── clear_stale_map: remove outdated display data ──
// C ref: detect.c:318
function clear_stale_map(oclass, material) {
    let change_made = false;
    for (let zx = 1; zx < COLNO; zx++) {
        for (let zy = 0; zy < ROWNO; zy++) {
            if (check_map_spot(zx, zy, oclass, material)) {
                unmap_object(zx, zy);
                change_made = true;
            }
        }
    }
    return change_made;
}
// ── sense_trap: display a detected trap (or fake object if halluc/cursed) ──
// C ref: detect.c:865
// RNG: random_object(rn2) if Hallucination, rnd(10) or rnd(2) for quantity,
//      random_monster(rn2) for corpsenm
function sense_trap(trap, x, y, src_cursed) {
    if (Hallucination() || src_cursed) {
        const obj = {};
        if (trap) {
            obj.ox = trap.tx;
            obj.oy = trap.ty;
        } else {
            obj.ox = x;
            obj.oy = y;
        }
        obj.otyp = !Hallucination() ? GOLD_PIECE : random_object(rn2);
        obj.quan = (obj.otyp === GOLD_PIECE) ? rnd(10)
                   : (game.objects[obj.otyp]?.oc_merge ? rnd(2) : 1);
        obj.corpsenm = random_monster(rn2); // if otyp == CORPSE
        map_object(obj, 1);
    } else if (trap) {
        map_trap(trap, 1);
        trap.tseen = 1;
    } else {
        // Obsolete path for trapped door/chest
        const dummytrap = { tx: x, ty: y, ttyp: BEAR_TRAP };
        map_trap(dummytrap, 1);
    }
}
// ── detect_obj_traps: check objects for chest traps ──
// C ref: detect.c:907
function detect_obj_traps(objlist, show_them, how, ft) {
    let result = OTRAP_NONE;
    for (let otmp = objlist; otmp; otmp = otmp.nobj) {
        let x = 0, y = 0;
        if ((Is_box(otmp) && otmp.otrapped) || Has_contents(otmp)) {
            // Simplified: use obj coordinates directly
            x = otmp.ox || 0;
            y = otmp.oy || 0;
            if (ft && (x !== ft.ft_cc_x || y !== ft.ft_cc_y))
                continue;
            if (!isok(x, y)) continue;
        }
        if (Is_box(otmp) && otmp.otrapped) {
            otmp.tknown = 1;
            observe_object(otmp);
            result |= u_at(x, y) ? OTRAP_HERE : OTRAP_THERE;
            if (show_them) {
                const dummytrap = { tx: x, ty: y, ttyp: TRAPPED_CHEST };
                sense_trap(dummytrap, x, y, how);
            }
            if (ft) {
                ft.num_traps = (ft.num_traps || 0) + 1;
            }
        }
        if (Has_contents(otmp))
            result |= detect_obj_traps(otmp.cobj, show_them, how, ft);
    }
    return result;
}
// ── display_trap_map: show all traps on map ──
// C ref: detect.c:956
async function display_trap_map(cursed_src) {
    const g = game;
    const ter_typ = TER_DETECT | (cursed_src ? TER_OBJ : TER_TRP);
    await cls();
    unconstrain_map();
    // Show chest traps
    detect_obj_traps(g.level?.buriedobjlist, true, cursed_src, null);
    for (let obj = g.fobj; obj; obj = obj.nobj) {
        // fobj iteration — detect_obj_traps expects linked list head
    }
    detect_obj_traps(g.fobj, true, cursed_src, null);
    for (let mon = g.fmon; mon; mon = mon.nmon) {
        if (DEADMONSTER(mon) || (mon.isgd && !mon.mx)) continue;
        detect_obj_traps(mon.minvent, true, cursed_src, null);
    }
    detect_obj_traps(g.invent, true, cursed_src, null);
    // Show floor/ceiling traps
    for (let ttmp = g.ftrap; ttmp; ttmp = ttmp.ntrap) {
        sense_trap(ttmp, 0, 0, cursed_src);
    }
    // Show trapped doors
    const dummytrap = { ttyp: TRAPPED_DOOR, tx: 0, ty: 0 };
    const doors = g.level?.doors || [];
    for (let door = 0; door < (g.doorindex || 0); door++) {
        const cc = doors[door];
        if (!cc) continue;
        const loc = levl(cc.x, cc.y);
        if (loc.typ === SDOOR) continue;
        if (loc.doormask & D_TRAPPED) {
            dummytrap.tx = cc.x;
            dummytrap.ty = cc.y;
            sense_trap(dummytrap, cc.x, cc.y, cursed_src);
        }
    }
    // Redisplay hero if needed
    const glyph = glyph_at(g.u.ux, g.u.uy);
    if (!(glyph_is_trap(glyph) || glyph_is_object(glyph))) {
        newsym(g.u.ux, g.u.uy);
    }
    await You_feel(cursed_src ? 'very greedy.' : 'entrapped.');
    await browse_map(ter_typ, cursed_src ? 'gold' : 'trap of interest');
    await map_redisplay();
}
// ══════════════════════════════════════════════════════════════════════
// Exported detection functions
// ══════════════════════════════════════════════════════════════════════
// ── gold_detect: detect gold on the level ──
// C ref: detect.c:335
// RNG: rnd(10) for gold quantity display per monster with gold
// Returns 1 if nothing found, 0 if something found.
export async function gold_detect(sobj) {
    const g = game;
    const GOLD = 6; // material constant for gold
    let stale = clear_stale_map(COIN_CLASS, sobj?.blessed ? GOLD : 0);
    let known = stale;
    let ugold = false, steedgold = false;
    // Look for gold carried by monsters
    for (let mtmp = g.fmon; mtmp; mtmp = mtmp.nmon) {
        if (DEADMONSTER(mtmp) || (mtmp.isgd && !mtmp.mx)) continue;
        if (findgold(mtmp.minvent) || monsndx(mtmp.data) === PM_GOLD_GOLEM) {
            if (mtmp === g.u?.usteed) {
                steedgold = true;
            } else {
                known = true;
                // goto outgoldmap
                await _gold_detect_outgoldmap(g, sobj, ugold, GOLD);
                return 0;
            }
        } else {
            for (let obj = mtmp.minvent; obj; obj = obj.nobj) {
                if ((sobj?.blessed && o_material(obj, GOLD))
                    || o_in(obj, COIN_CLASS)) {
                    if (mtmp === g.u?.usteed) {
                        steedgold = true;
                    } else {
                        known = true;
                        await _gold_detect_outgoldmap(g, sobj, ugold, GOLD);
                        return 0;
                    }
                }
            }
        }
    }
    // Look for gold objects on floor
    const fobj = g.fobj;
    for (let obj = fobj; obj; obj = obj.nobj) {
        if (sobj?.blessed && o_material(obj, GOLD)) {
            known = true;
            if (!u_at(obj.ox, obj.oy)) {
                await _gold_detect_outgoldmap(g, sobj, ugold, GOLD);
                return 0;
            }
        } else if (o_in(obj, COIN_CLASS)) {
            known = true;
            if (!u_at(obj.ox, obj.oy)) {
                await _gold_detect_outgoldmap(g, sobj, ugold, GOLD);
                return 0;
            }
        }
    }
    if (!known) {
        // No gold found — generate appropriate message
        let buf;
        if (monsndx(g.youmonst?.data) === PM_GOLD_GOLEM) {
            buf = `You feel like a million ${currency(2)}!`;
        } else if (money_cnt(g.invent) || hidden_gold(true)) {
            buf = 'You feel worried about your future financial situation.';
        } else if (steedgold) {
            buf = `You feel interested in ${s_suffix(x_monnam(g.u?.usteed,
                g.u?.usteed?.mtame ? ARTICLE_YOUR : ARTICLE_THE,
                null, SUPPRESS_SADDLE, false))} financial situation.`;
        } else {
            buf = 'You feel materially poor.';
        }
        await strange_feeling_fn(sobj, buf);
        return 1;
    }
    // Gold only under hero
    if (stale) await docrt();
    await You(`notice some gold between your ${makeplural(body_part(0))}.`); // FOOT=0
    return 0;
}
// Internal helper for gold_detect outgoldmap path
async function _gold_detect_outgoldmap(g, sobj, ugold, GOLD) {
    const ter_typ = TER_DETECT | TER_OBJ;
    await cls();
    unconstrain_map();
    // Map floor gold
    for (let obj = g.fobj; obj; obj = obj.nobj) {
        let temp;
        if (sobj?.blessed && (temp = o_material(obj, GOLD))) {
            if (temp !== obj) { temp.ox = obj.ox; temp.oy = obj.oy; }
            map_object(temp, 1);
        } else if ((temp = o_in(obj, COIN_CLASS))) {
            if (temp !== obj) { temp.ox = obj.ox; temp.oy = obj.oy; }
            map_object(temp, 1);
        }
        if (temp && u_at(temp.ox, temp.oy)) ugold = true;
    }
    // Map monster gold — RNG: rnd(10) per monster with findgold
    for (let mtmp = g.fmon; mtmp; mtmp = mtmp.nmon) {
        if (DEADMONSTER(mtmp) || (mtmp.isgd && !mtmp.mx)) continue;
        let temp = null;
        if (findgold(mtmp.minvent) || monsndx(mtmp.data) === PM_GOLD_GOLEM) {
            const gold = { otyp: GOLD_PIECE, quan: rnd(10),
                           ox: mtmp.mx, oy: mtmp.my };
            map_object(gold, 1);
            temp = gold;
        } else {
            for (let obj = mtmp.minvent; obj; obj = obj.nobj) {
                if (sobj?.blessed && (temp = o_material(obj, GOLD))) {
                    temp.ox = mtmp.mx; temp.oy = mtmp.my;
                    map_object(temp, 1);
                    break;
                } else if ((temp = o_in(obj, COIN_CLASS))) {
                    temp.ox = mtmp.mx; temp.oy = mtmp.my;
                    map_object(temp, 1);
                    break;
                }
            }
        }
        if (temp && u_at(temp.ox, temp.oy)) ugold = true;
    }
    if (!ugold) {
        newsym(g.u.ux, g.u.uy);
    }
    await You_feel('very greedy, and sense gold!');
    exercise(A_WIS, true);
    await browse_map(ter_typ | (ugold ? 0 : TER_MON), 'gold');
    await map_redisplay();
}
// ── food_detect: detect food on the level ──
// C ref: detect.c:479
// Returns 1 if nothing was detected, 0 if something was detected.
export async function food_detect(sobj) {
    const g = game;
    let ct = 0, ctu = 0;
    const confused = Confusion() || (sobj && sobj.cursed);
    const oclass = confused ? POTION_CLASS : FOOD_CLASS;
    const what = confused ? 'something' : 'food';
    const stale = clear_stale_map(oclass, 0);
    if (g.u?.usteed) {
        g.u.usteed.mx = g.u.ux;
        g.u.usteed.my = g.u.uy;
    }
    for (let obj = g.fobj; obj; obj = obj.nobj) {
        if (o_in(obj, oclass)) {
            if (u_at(obj.ox, obj.oy)) ctu++;
            else ct++;
        }
    }
    for (let mtmp = g.fmon; mtmp && (!ct || !ctu); mtmp = mtmp.nmon) {
        if (DEADMONSTER(mtmp) || (mtmp.isgd && !mtmp.mx)) continue;
        for (let obj = mtmp.minvent; obj; obj = obj.nobj) {
            if (o_in(obj, oclass)) {
                if (u_at(mtmp.mx, mtmp.my)) ctu++;
                else ct++;
                break;
            }
        }
    }
    if (!ct && !ctu) {
        const known = stale && !confused;
        if (stale) {
            await docrt();
            await You(`sense a lack of ${what} nearby.`);
            if (sobj?.blessed) {
                if (!g.u?.uedibility)
                    await Your(`${body_part(10)} starts to tingle.`); // NOSE=10
                g.u.uedibility = 1;
            }
        } else if (sobj) {
            let buf = `Your ${body_part(10)} twitches` +
                ((sobj.blessed && !g.u?.uedibility)
                    ? ' then starts to tingle' : '') + '.';
            if (sobj.blessed && !g.u?.uedibility) {
                const savebeginner = g.flags?.beginner;
                if (g.flags) g.flags.beginner = false;
                await strange_feeling_fn(sobj, buf);
                if (g.flags) g.flags.beginner = savebeginner;
                g.u.uedibility = 1;
            } else {
                await strange_feeling_fn(sobj, buf);
            }
        }
        return !stale ? 1 : 0;
    } else if (!ct) {
        g.known = true;
        await You(`${sobj ? 'smell' : 'sense'} ${what} nearby.`);
        if (sobj?.blessed) {
            if (!g.u?.uedibility)
                await Your(`${body_part(10)} starts to tingle.`);
            g.u.uedibility = 1;
        }
    } else {
        const ter_typ = TER_DETECT | TER_OBJ;
        g.known = true;
        await cls();
        unconstrain_map();
        for (let obj = g.fobj; obj; obj = obj.nobj) {
            const temp = o_in(obj, oclass);
            if (temp) {
                if (temp !== obj) { temp.ox = obj.ox; temp.oy = obj.oy; }
                map_object(temp, 1);
            }
        }
        for (let mtmp = g.fmon; mtmp; mtmp = mtmp.nmon) {
            if (DEADMONSTER(mtmp) || (mtmp.isgd && !mtmp.mx)) continue;
            for (let obj = mtmp.minvent; obj; obj = obj.nobj) {
                const temp = o_in(obj, oclass);
                if (temp) {
                    temp.ox = mtmp.mx; temp.oy = mtmp.my;
                    map_object(temp, 1);
                    break;
                }
            }
        }
        if (!ctu) {
            newsym(g.u.ux, g.u.uy);
        }
        if (sobj) {
            if (sobj.blessed) {
                await Your(`${body_part(10)} ${g.u?.uedibility ? 'continues' : 'starts'} to tingle and you smell ${what}.`);
                g.u.uedibility = 1;
            } else {
                await Your(`${body_part(10)} tingles and you smell ${what}.`);
            }
        } else {
            await You(`sense ${what}.`);
        }
        exercise(A_WIS, true);
        await browse_map(ter_typ | (ctu ? 0 : TER_MON), 'food');
        await map_redisplay();
    }
    return 0;
}
// ── object_detect: detect objects on the level ──
// C ref: detect.c:603
// RNG: rnd(10) for gold quantity display
// Returns 1 if nothing was detected, 0 if something was detected.
export async function object_detect(detector, oclass) {
    const g = game;
    if (oclass < 0 || oclass >= MAXOCLASSES) { oclass = 0; }
    const is_cursed = detector && detector.cursed;
    const do_dknown = detector && (detector.oclass === POTION_CLASS
                      || detector.oclass === SPBOOK_CLASS) && detector.blessed;
    let ct = 0, ctu = 0;
    let otmp = null;
    // Boulder symbol check
    const sym = oclass ? (def_oc_syms[oclass]?.sym || 0) : 0;
    let boulder = 0;
    // TODO: showsyms boulder check
    const stuff = (Hallucination() || (Confusion() && oclass === SCROLL_CLASS))
        ? 'something'
        : (oclass ? (def_oc_syms[oclass]?.name || 'objects') : 'objects');
    if (do_dknown) {
        for (let obj = g.invent; obj; obj = obj.nobj)
            observe_recursively(obj);
    }
    for (let obj = g.fobj; obj; obj = obj.nobj) {
        if ((!oclass && !boulder) || o_in(obj, oclass) || (boulder && o_in(obj, boulder))) {
            if (u_at(obj.ox, obj.oy)) ctu++;
            else ct++;
        }
        if (do_dknown) observe_recursively(obj);
    }
    // Buried objects
    const buriedlist = g.level?.buriedobjlist;
    for (let obj = buriedlist; obj; obj = obj?.nobj) {
        if (!oclass || o_in(obj, oclass)) {
            if (u_at(obj.ox, obj.oy)) ctu++;
            else ct++;
        }
        if (do_dknown) observe_recursively(obj);
    }
    if (g.u?.usteed) {
        g.u.usteed.mx = g.u.ux;
        g.u.usteed.my = g.u.uy;
    }
    for (let mtmp = g.fmon; mtmp; mtmp = mtmp.nmon) {
        if (DEADMONSTER(mtmp) || (mtmp.isgd && !mtmp.mx)) continue;
        for (let obj = mtmp.minvent; obj; obj = obj.nobj) {
            if ((!oclass && !boulder) || o_in(obj, oclass)
                || (boulder && o_in(obj, boulder)))
                ct++;
            if (do_dknown) observe_recursively(obj);
        }
        if ((is_cursed && M_AP_TYPE(mtmp) === M_AP_OBJECT
             && (!oclass || oclass === game.objects[mtmp.mappearance]?.oc_class))
            || (findgold(mtmp.minvent) && (!oclass || oclass === COIN_CLASS))) {
            ct++;
            break;
        }
    }
    if (!clear_stale_map(!oclass ? ALL_CLASSES : oclass, 0) && !ct) {
        if (!ctu) {
            if (detector)
                await strange_feeling_fn(detector, 'You feel a lack of something.');
            return 1;
        }
        await You(`sense ${stuff} nearby.`);
        return 0;
    }
    await cls();
    unconstrain_map();
    // Map buried objects
    for (let obj = buriedlist; obj; obj = obj?.nobj) {
        if (!oclass || (otmp = o_in(obj, oclass))) {
            if (oclass) {
                if (otmp !== obj) { otmp.ox = obj.ox; otmp.oy = obj.oy; }
                map_object(otmp, 1);
            } else {
                map_object(obj, 1);
            }
        }
    }
    // Map floor objects
    for (let x = 1; x < COLNO; x++) {
        for (let y = 0; y < ROWNO; y++) {
            const floorObjs = g.level?.objects?.filter(o => o.ox === x && o.oy === y) || [];
            for (const obj of floorObjs) {
                if ((!oclass && !boulder) || (otmp = o_in(obj, oclass))
                    || (boulder && (otmp = o_in(obj, boulder)))) {
                    if (oclass || boulder) {
                        if (otmp !== obj) { otmp.ox = obj.ox; otmp.oy = obj.oy; }
                        map_object(otmp, 1);
                    } else {
                        map_object(obj, 1);
                    }
                    break;
                }
            }
        }
    }
    // Map monster inventory objects — RNG: rnd(10) for gold
    for (let mtmp = g.fmon; mtmp; mtmp = mtmp.nmon) {
        if (DEADMONSTER(mtmp) || (mtmp.isgd && !mtmp.mx)) continue;
        for (let obj = mtmp.minvent; obj; obj = obj.nobj) {
            if ((!oclass && !boulder) || (otmp = o_in(obj, oclass))
                || (boulder && (otmp = o_in(obj, boulder)))) {
                if (!oclass && !boulder) otmp = obj;
                otmp.ox = mtmp.mx;
                otmp.oy = mtmp.my;
                map_object(otmp, 1);
                break;
            }
        }
        // Mimic as object
        if (is_cursed && M_AP_TYPE(mtmp) === M_AP_OBJECT
            && (!oclass || oclass === game.objects[mtmp.mappearance]?.oc_class)) {
            const temp = { otyp: mtmp.mappearance, quan: 1,
                           ox: mtmp.mx, oy: mtmp.my,
                           corpsenm: mtmp.mcorpsenm ?? PM_TENGU };
            map_object(temp, 1);
        } else if (findgold(mtmp.minvent)
                   && (!oclass || oclass === COIN_CLASS)) {
            const gold = { otyp: GOLD_PIECE, quan: rnd(10),
                           ox: mtmp.mx, oy: mtmp.my };
            map_object(gold, 1);
        }
    }
    if (!glyph_is_object(glyph_at(g.u.ux, g.u.uy))) {
        newsym(g.u.ux, g.u.uy);
    }
    await You(`detect the ${ct ? 'presence' : 'absence'} of ${stuff}.`);
    if (!ct) {
        await display_nhwindow(WIN_MAP, true);
    } else {
        await browse_map(TER_DETECT | TER_OBJ, 'object');
    }
    await map_redisplay();
    return 0;
}
// ── monster_detect: detect monsters on the level ──
// C ref: detect.c:798
// RNG: none for basic detection (display rng for glyph only).
// Returns 1 if nothing was detected, 0 if something was detected.
export async function monster_detect(otmp, mclass) {
    const g = game;
    let mcnt = 0;
    for (let mtmp = g.fmon; mtmp; mtmp = mtmp.nmon) {
        if (DEADMONSTER(mtmp) || (mtmp.isgd && !mtmp.mx)) continue;
        ++mcnt;
        break;
    }
    if (!mcnt) {
        if (otmp) {
            await strange_feeling_fn(otmp,
                Hallucination()
                    ? 'You get the heebie jeebies.'
                    : 'You feel threatened.');
        }
        return 1;
    } else {
        let woken = false;
        const swallowed = g.u?.uswallow;
        await cls();
        const unconstrained = unconstrain_map();
        for (let mtmp = g.fmon; mtmp; mtmp = mtmp.nmon) {
            if (DEADMONSTER(mtmp) || (mtmp.isgd && !mtmp.mx)) continue;
            if (!mclass || mtmp.data?.mlet === mclass
                || (mtmp.data === g.mons?.[PM_LONG_WORM]
                    && mclass === S_WORM_TAIL)) {
                // map_monst equivalent — display RNG only
                show_glyph(mtmp.mx, mtmp.my,
                    mon_to_glyph(mtmp, rn2_on_display_rng));
            }
            if (otmp && otmp.cursed && helpless(mtmp)) {
                mtmp.msleeping = 0;
                mtmp.mfrozen = 0;
                mtmp.mcanmove = 1;
                woken = true;
            }
        }
        if (!swallowed) display_self();
        await You('sense the presence of monsters.');
        if (woken) await pline('Monsters sense the presence of you.');
        if (otmp?.blessed && !unconstrained) {
            await display_nhwindow(WIN_MAP, true);
        } else {
            await browse_map(TER_DETECT | TER_MON, 'monster of interest');
        }
        await map_redisplay();
    }
    return 0;
}
// ── trap_detect: detect traps on the level ──
// C ref: detect.c:1011
// RNG: via sense_trap if Hallucination or cursed
// Returns 1 if nothing was detected, 0 if something was detected.
export async function trap_detect(sobj) {
    const g = game;
    const cursed_src = sobj && sobj.cursed;
    let found = false;
    if (g.u?.usteed) {
        g.u.usteed.mx = g.u.ux;
        g.u.usteed.my = g.u.uy;
    }
    // Floor/ceiling traps
    for (let ttmp = g.ftrap; ttmp; ttmp = ttmp.ntrap) {
        if (ttmp.tx !== g.u.ux || ttmp.ty !== g.u.uy) {
            await display_trap_map(cursed_src);
            return 0;
        }
        found = true;
    }
    // Chest traps (floor)
    let tr = detect_obj_traps(g.fobj, false, 0, null);
    if (tr !== OTRAP_NONE) {
        if (tr & OTRAP_THERE) {
            await display_trap_map(cursed_src);
            return 0;
        }
        found = true;
    }
    // Chest traps (buried)
    tr = detect_obj_traps(g.level?.buriedobjlist, false, 0, null);
    if (tr !== OTRAP_NONE) {
        if (tr & OTRAP_THERE) {
            await display_trap_map(cursed_src);
            return 0;
        }
        found = true;
    }
    // Monster inventory chest traps
    for (let mon = g.fmon; mon; mon = mon.nmon) {
        if (DEADMONSTER(mon) || (mon.isgd && !mon.mx)) continue;
        tr = detect_obj_traps(mon.minvent, false, 0, null);
        if (tr !== OTRAP_NONE) {
            if (tr & OTRAP_THERE) {
                await display_trap_map(cursed_src);
                return 0;
            }
            found = true;
        }
    }
    // Player inventory chest traps
    if (detect_obj_traps(g.invent, false, 0, null) !== OTRAP_NONE)
        found = true;
    // Door traps
    const doors = g.level?.doors || [];
    for (let door = 0; door < (g.doorindex || 0); door++) {
        const cc = doors[door];
        if (!cc) continue;
        const loc = levl(cc.x, cc.y);
        if (loc.typ === SDOOR) continue;
        if (loc.doormask & D_TRAPPED) {
            if (cc.x !== g.u.ux || cc.y !== g.u.uy) {
                await display_trap_map(cursed_src);
                return 0;
            }
            found = true;
        }
    }
    if (!found) {
        const buf = `Your ${makeplural(body_part(18))} stop itching.`; // TOE=18
        await strange_feeling_fn(sobj, buf);
        return 1;
    }
    // Traps exist but only under hero
    await Your(`${makeplural(body_part(18))} itch.`);
    return 0;
}
// ── furniture_detect: detect altars, fountains, etc. ──
// C ref: detect.c:1092
export async function furniture_detect() {
    const g = game;
    let found = 0, revealed = 0;
    unconstrain_map();
    for (let y = 0; y < ROWNO; ++y) {
        for (let x = 1; x < COLNO; ++x) {
            const glyph = glyph_at(x, y);
            const sym = glyph_to_cmap(glyph);
            const loc = levl(x, y);
            if (IS_FURNITURE(loc.typ)) {
                ++found;
                magic_map_background(x, y, 1);
            } else if (is_cmap_furniture(sym)) {
                ++found;
                const mon = m_at(x, y);
                if (mon && M_AP_TYPE(mon) === M_AP_FURNITURE)
                    seemimic(mon);
                if (!mon || !canspotmon(mon))
                    map_invisible(x, y);
            }
            if (glyph_at(x, y) !== glyph)
                ++revealed;
        }
    }
    if (!found)
        await pline('There seems to be nothing of interest on this level.');
    else if (!revealed)
        await Your('map already shows all relevant locations.');
    if (!revealed)
        await display_nhwindow(WIN_MAP, true);
    else
        await browse_map(TER_DETECT | TER_MAP | TER_TRP | TER_OBJ | TER_MON,
                         'location');
    await map_redisplay();
    return 0;
}
// ── level_distance: describe relative position of a level ──
// C ref: detect.c:1143
// RNG: rn2(3) for distance threshold
export function level_distance(where) {
    const g = game;
    const ll = depth(g.u?.uz) - depth(where);
    const indun = g.u?.uz?.dnum === where?.dnum;
    if (ll < 0) {
        if (ll < (-8 - rn2(3)))
            return !indun ? 'far away' : 'far below';
        else if (ll < -1)
            return !indun ? 'away below you' : 'below you';
        else
            return !indun ? 'in the distance' : 'just below';
    } else if (ll > 0) {
        if (ll > (8 + rn2(3)))
            return !indun ? 'far away' : 'far above';
        else if (ll > 1)
            return !indun ? 'away above you' : 'above you';
        else
            return !indun ? 'in the distance' : 'just above';
    } else {
        return !indun ? 'in the distance' : 'near you';
    }
}
// Level detects table for crystal ball
// C ref: detect.c:1196
const level_detects = [
    { what: 'Delphi', where: null }, // oracle_level TODO
    { what: "Medusa's lair", where: null }, // medusa_level TODO
    { what: 'a castle', where: null }, // stronghold_level TODO
    { what: "the Wizard of Yendor's tower", where: null }, // wiz1_level TODO
];
// ── use_crystal_ball: peer into a crystal ball ──
// C ref: detect.c:1206
// RNG: rnd(oops) for oops check, rnd(100-3*INT) for impairment,
//      rnd(4 or 5) for oops effect, rnd(30) for explosion damage,
//      rnd(4 or 2) for hallucination nomul, rnd(6) for halluc message,
//      rnd(10 or 2) for peering nomul, rn2(SIZE) for level_detects,
//      rn2(100) for wizard vision
export async function use_crystal_ball(optr) {
    const g = game;
    let obj = optr.obj;
    const charged = obj && obj.spe > 0;
    if (Blind()) {
        await pline(`Too bad you can't see ${the(xname(obj))}.`);
        return;
    }
    const oops = is_quest_artifact(obj) ? 8 : obj.blessed ? 16 : 20;
    if (charged && (obj.cursed || rnd(oops) > ACURR(A_INT))) {
        const impair = rnd(100 - 3 * ACURR(A_INT));
        switch (rnd(obj.oartifact || obj.blessed ? 4 : 5)) {
        case 1:
            await pline(`${Tobjnam(obj, 'are')} too much to comprehend!`);
            break;
        case 2:
            await pline(`${Tobjnam(obj, 'confuse')} you!`);
            await make_confused((g.u?.HConfusion ?? 0 & TIMEOUT) + impair, false);
            break;
        case 3:
            if (!resists_blnd(g.youmonst)) {
                await pline(`${Tobjnam(obj, 'damage')} your vision!`);
                await make_blinded((g.u?.BlindedTimeout ?? 0) + impair, false);
                if (!Blind()) await Your('vision clears.');
            } else {
                await pline(`${Tobjnam(obj, 'assault')} your vision.`);
                await You('are unaffected!');
            }
            break;
        case 4:
            await pline(`${Tobjnam(obj, 'zap')} your mind!`);
            await make_hallucinated((g.u?.HHallucination ?? 0 & TIMEOUT) + impair,
                                    false, 0);
            break;
        case 5:
            await pline(`${Tobjnam(obj, 'explode')}!`);
            useup(obj);
            optr.obj = null;
            obj = null;
            await losehp(Maybe_Half_Phys(rnd(30)), 'exploding crystal ball',
                         KILLED_BY_AN);
            break;
        }
        if (obj) consume_obj_charge(obj, true);
        return;
    }
    if (Hallucination()) {
        nomul(-rnd(charged ? 4 : 2));
        g.multi_reason = 'gazing into a Magic 8-Ball (tm)';
        g.nomovemsg = '';
        if (!charged) {
            await pline(`All you see is funky ${hcolor(null)} haze.`);
            if (obj.spe < 0) {
                // implode
                await pline(`${Tobjnam(obj, 'implode')}!`);
                useup(obj);
                optr.obj = null;
                return;
            }
        } else {
            switch (rnd(6)) {
            case 1:
                await You('grok some groovy globs of incandescent lava.');
                break;
            case 2:
                await pline(`Whoa!  Psychedelic colors, ${poly_gender() === 1 ? 'babe' : 'dude'}!`);
                break;
            case 3:
                await pline_The(`crystal pulses with sinister ${hcolor(null)} light!`);
                break;
            case 4:
                await You_see('goldfish swimming above fluorescent rocks.');
                break;
            case 5:
                await You_see('tiny snowflakes spinning around a miniature farmhouse.');
                break;
            default:
                await pline('Oh wow... like a kaleidoscope!');
                break;
            }
            consume_obj_charge(obj, true);
        }
        return;
    }
    // Read a single character
    if (g.flags?.verbose)
        await You('may look for an object, monster, or special map symbol.');
    const ch = await yn_function('What do you look for?', null, '\0', true);
    if (ch === '\x1b' || ch === 'q' || ch === 'Q') {
        if (g.flags?.verbose) await pline(Never_mind);
        return;
    }
    await You(`peer into ${the(xname(obj))}...`);
    nomul(-rnd(charged ? 10 : 2));
    g.multi_reason = 'gazing into a crystal ball';
    g.nomovemsg = '';
    if (!charged) {
        await pline_The('vision is unclear.');
        if (obj.spe < 0) {
            // implode
            await pline(`${Tobjnam(obj, 'implode')}!`);
            useup(obj);
            optr.obj = null;
            return;
        }
    } else {
        let ret = 0;
        makeknown(CRYSTAL_BALL);
        consume_obj_charge(obj, true);
        // Check furniture first, then objects, then monsters
        const furnitureIdx = def_char_is_furniture(ch);
        const objClass = def_char_to_objclass(ch);
        // def_char_to_monclass not yet available as export, stub inline
        const monClass = MAXMCLASSES; // TODO: def_char_to_monclass(ch)
        if (furnitureIdx >= 0) {
            ret = await furniture_detect();
        } else if (objClass !== MAXOCLASSES) {
            ret = await object_detect(null, objClass);
        } else if (monClass !== MAXMCLASSES) {
            ret = await monster_detect(null, monClass);
        } else if (ch === '^') {
            ret = await trap_detect(null);
        } else {
            const i = rn2(level_detects.length);
            await You_see(`${level_detects[i].what}, ${level_distance(level_detects[i].where)}.`);
            ret = 0;
        }
        if (ret) {
            if (!rn2(100))
                await You_see('the Wizard of Yendor gazing out at you.');
            else
                await pline_The('vision is unclear.');
        }
    }
}
// ── show_map_spot: reveal one map location (magic mapping, clairvoyance) ──
// C ref: detect.c:1372
// RNG: rn2(7) if confused
export function show_map_spot(x, y, cnf) {
    if (cnf && rn2(7)) return;
    const loc = levl(x, y);
    loc.seenv = SVALL;
    // Secret corridors are found, but not secret doors
    if (loc.typ === SCORR) {
        loc.typ = CORR;
        unblock_point(x, y);
    }
    const oldglyph = glyph_at(x, y);
    magic_map_background(x, y, 0);
    newsym(x, y);
    if (!IS_FURNITURE(loc.typ)) {
        const t = t_at(x, y);
        if (t && t.tseen) {
            map_trap(t, 1);
        } else if (glyph_is_trap(oldglyph) || glyph_is_object(oldglyph)) {
            show_glyph(x, y, oldglyph);
        }
    }
    // Possibly update #overview
    if (!cnf && loc.roomno >= 0) {
        room_discovered(loc.roomno);
    }
}
// ── do_mapping: magic mapping ──
// C ref: detect.c:1422
// RNG: rn2(7) per tile if confused (via show_map_spot)
export async function do_mapping() {
    const g = game;
    const unconstrained = unconstrain_map();
    for (let zx = 1; zx < COLNO; zx++) {
        for (let zy = 0; zy < ROWNO; zy++) {
            show_map_spot(zx, zy, Confusion());
        }
    }
    if (!g.level?.flags?.hero_memory || unconstrained) {
        await flush_screen(1);
        await browse_map(TER_DETECT | TER_MAP | TER_TRP | TER_OBJ,
                         'anything of interest');
        await map_redisplay();
    } else {
        reconstrain_map();
    }
    exercise(A_WIS, true);
}
// ── do_vicinity_map: clairvoyance ──
// C ref: detect.c:1448
// RNG: rn2(7) per tile if confused (via show_map_spot)
export async function do_vicinity_map(sobj) {
    const g = game;
    const extended = sobj && (sobj.blessed || Clairvoyant());
    const random_farsight = !sobj;
    const lo_y = Math.max(0, g.u.uy - 5);
    const hi_y = Math.min(ROWNO - 1, g.u.uy + 6);
    const lo_x = Math.max(1, g.u.ux - 9);
    const hi_x = Math.min(COLNO - 1, g.u.ux + 10);
    let ter_typ = TER_DETECT | TER_MAP | TER_TRP | TER_OBJ;
    let mdetected = false, odetected = false;
    let refresh = false;
    const unconstrained = unconstrain_map();
    for (let zx = lo_x; zx <= hi_x; zx++) {
        for (let zy = lo_y; zy <= hi_y; zy++) {
            const oldglyph = glyph_at(zx, zy);
            show_map_spot(zx, zy, Confusion());
            // If objects here, see the top one
            if (OBJ_AT(zx, zy)) {
                const floorObjs = g.level?.objects?.filter(o => o.ox === zx && o.oy === zy) || [];
                if (floorObjs.length > 0) {
                    const topObj = floorObjs[0];
                    if (extended) observe_object(topObj);
                    map_object(topObj, true);
                    const newglyph = glyph_at(zx, zy);
                    if (newglyph !== oldglyph && covers_objects(zx, zy))
                        odetected = true;
                }
            }
            // If monster here, see or detect it
            const mtmp = m_at(zx, zy);
            if (mtmp && mtmp.mx === zx && mtmp.my === zy) {
                if ((unconstrained || !g.level?.flags?.hero_memory)
                    && !extended && (zx !== g.u.ux || zy !== g.u.uy)
                    && !glyph_is_monster(oldglyph)) {
                    map_invisible(zx, zy);
                } else {
                    // map_monst inline
                    show_glyph(mtmp.mx, mtmp.my,
                        mon_to_glyph(mtmp, rn2_on_display_rng));
                }
                const newglyph = glyph_at(zx, zy);
                if (extended && newglyph !== oldglyph
                    && !glyph_is_invisible(newglyph))
                    mdetected = true;
            }
        }
    }
    if (random_farsight && g.flags?.quick_farsight)
        mdetected = odetected = false;
    if (!g.level?.flags?.hero_memory || unconstrained
        || mdetected || odetected) {
        await flush_screen(1);
        await You('sense your surroundings.');
        if (extended || glyph_is_monster(glyph_at(g.u.ux, g.u.uy)))
            ter_typ |= TER_MON;
        await browse_map(ter_typ, 'anything of interest');
        refresh = true;
    }
    reconstrain_map();
    // Replace monsters with remembered unseen, then run see_monsters
    for (let zx = lo_x; zx <= hi_x; zx++) {
        for (let zy = lo_y; zy <= hi_y; zy++) {
            if (u_at(zx, zy)) continue;
            const newglyph = glyph_at(zx, zy);
            if (glyph_is_monster(newglyph)
                && glyph_to_mon(newglyph) !== PM_LONG_WORM_TAIL) {
                const mt = m_at(zx, zy);
                if (!mt || !canspotmon(mt))
                    map_invisible(zx, zy);
            }
        }
    }
    see_monsters();
    if (refresh) await docrt();
}
// ── cvt_sdoor_to_door: convert secret door to normal door ──
// C ref: detect.c:1589
export function cvt_sdoor_to_door(loc) {
    let newmask = (loc.doormask || 0) & ~WM_MASK;
    if (Is_rogue_level()) {
        newmask = D_NODOOR;
    } else {
        if (!(newmask & D_LOCKED))
            newmask |= D_CLOSED;
    }
    loc.typ = DOOR;
    loc.doormask = newmask;
    if (loc.arboreal_sdoor !== undefined) loc.arboreal_sdoor = 0;
}
// ── foundone: update map for newly found item ──
// C ref: detect.c:1610
function foundone(zx, zy, glyph) {
    const loc = levl(zx, zy);
    if (glyph_is_cmap(glyph)) {
        loc.seenv = SVALL;
    }
    newsym(zx, zy);
}
// ── findone: find something at one location (magical detection) ──
// C ref: detect.c:1639
// RNG: display RNG via mon_to_glyph if mimic/hidden monster found
export async function findone(zx, zy, whatfound) {
    const loc = levl(zx, zy);
    const ttmp = t_at(zx, zy);
    let mtmp = m_at(zx, zy);
    const found_p = whatfound;
    if (mtmp && (DEADMONSTER(mtmp) || (mtmp.isgd && !mtmp.mx)))
        mtmp = null;
    found_p.ft_cc_x = zx;
    found_p.ft_cc_y = zy;
    if (loc.typ === SDOOR) {
        const sym = loc.horizontal ? S_hcdoor : S_vcdoor;
        await flash_glyph_at(zx, zy, cmap_to_glyph(sym), FOUND_FLASH_COUNT);
        cvt_sdoor_to_door(loc);
        recalc_block_point(zx, zy);
        magic_map_background(zx, zy, 0);
        foundone(zx, zy, back_to_glyph(zx, zy));
        found_p.num_sdoors = (found_p.num_sdoors || 0) + 1;
    } else if (loc.typ === SCORR) {
        await flash_glyph_at(zx, zy, cmap_to_glyph(S_corr), FOUND_FLASH_COUNT);
        loc.typ = CORR;
        unblock_point(zx, zy);
        magic_map_background(zx, zy, 0);
        foundone(zx, zy, cmap_to_glyph(S_corr));
        found_p.num_scorrs = (found_p.num_scorrs || 0) + 1;
    }
    if (ttmp && !ttmp.tseen && ttmp.ttyp !== STATUE_TRAP) {
        await flash_glyph_at(zx, zy, trap_to_glyph(ttmp), FOUND_FLASH_COUNT);
        ttmp.tseen = 1;
        sense_trap(ttmp, zx, zy, 0);
        foundone(zx, zy, trap_to_glyph(ttmp));
        found_p.num_traps = (found_p.num_traps || 0) + 1;
    }
    if (closed_door(zx, zy) && (loc.doormask & D_TRAPPED)) {
        const dummytrap = { ttyp: TRAPPED_DOOR, tx: zx, ty: zy, tseen: 0 };
        await flash_glyph_at(zx, zy, trap_to_glyph(dummytrap), FOUND_FLASH_COUNT);
        dummytrap.tseen = 1;
        sense_trap(dummytrap, zx, zy, 0);
        foundone(zx, zy, trap_to_glyph(dummytrap));
        found_p.num_traps = (found_p.num_traps || 0) + 1;
    }
    // Trapped chests
    detect_obj_traps(game.level?.buriedobjlist, true, 0, found_p);
    detect_obj_traps(game.fobj, true, 0, found_p);
    if (mtmp)
        detect_obj_traps(mtmp.minvent, true, 0, found_p);
    if (u_at(zx, zy))
        detect_obj_traps(game.invent, true, 0, found_p);
    // Hidden/disguised monsters — display RNG for glyph
    if (mtmp && (!canspotmon(mtmp) || mtmp.mundetected || M_AP_TYPE(mtmp))) {
        if (M_AP_TYPE(mtmp)) {
            await flash_glyph_at(zx, zy, mon_to_glyph(mtmp, rn2_on_display_rng),
                FOUND_FLASH_COUNT);
            seemimic(mtmp);
            found_p.num_mons = (found_p.num_mons || 0) + 1;
        } else if (mtmp.mundetected && (is_hider(mtmp.data)
                                        || hides_under(mtmp.data)
                                        || mtmp.data?.mlet === S_EEL)) {
            await flash_glyph_at(zx, zy, mon_to_glyph(mtmp, rn2_on_display_rng),
                FOUND_FLASH_COUNT);
            mtmp.mundetected = 0;
            newsym(zx, zy);
            found_p.num_mons = (found_p.num_mons || 0) + 1;
        }
        if (!glyph_is_invisible(loc.glyph)) {
            if (!canspotmon(mtmp)) {
                await flash_glyph_at(zx, zy, GLYPH_INVISIBLE, FOUND_FLASH_COUNT);
                map_invisible(zx, zy);
                found_p.num_invis = (found_p.num_invis || 0) + 1;
            }
        } else {
            found_p.num_kept_invis = (found_p.num_kept_invis || 0) + 1;
        }
    } else if (unmap_invisible(zx, zy)) {
        await flash_glyph_at(zx, zy, GLYPH_INVISIBLE, FOUND_FLASH_COUNT);
        found_p.num_cleared_invis = (found_p.num_cleared_invis || 0) + 1;
    }
}
// ── openone: open doors/traps at one location ──
// C ref: detect.c:1729
// RNG: none directly (sub-functions may use RNG)
export async function openone(zx, zy, num_p) {
    const g = game;
    if (OBJ_AT(zx, zy)) {
        const floorObjs = g.level?.objects?.filter(o => o.ox === zx && o.oy === zy) || [];
        for (const otmp of floorObjs) {
            if (Is_box(otmp) && otmp.olocked) {
                otmp.olocked = 0;
                num_p.value++;
            }
        }
    }
    const loc = levl(zx, zy);
    if (loc.typ === SDOOR
        || (loc.typ === DOOR
            && ((loc.doormask || 0) & (D_CLOSED | D_LOCKED)))) {
        if (loc.typ === SDOOR)
            cvt_sdoor_to_door(loc);
        if ((loc.doormask || 0) & D_TRAPPED) {
            const dist = (zx - g.u.ux) * (zx - g.u.ux) + (zy - g.u.uy) * (zy - g.u.uy);
            if (dist < 3) {
                await b_trapped('door', NO_PART);
            } else {
                const msg = cansee(zx, zy) ? 'see' : (!Deaf() ? 'hear' : 'feel the shock of');
                await pline(`You ${msg} an explosion!`);
            }
            wake_nearto(zx, zy, 11 * 11);
            loc.doormask = D_NODOOR;
        } else {
            loc.doormask = D_ISOPEN;
        }
        unblock_point(zx, zy);
        newsym(zx, zy);
        num_p.value++;
    } else if (loc.typ === SCORR) {
        loc.typ = CORR;
        unblock_point(zx, zy);
        newsym(zx, zy);
        num_p.value++;
    } else {
        const ttmp = t_at(zx, zy);
        if (ttmp) {
            if (!ttmp.tseen && ttmp.ttyp !== STATUE_TRAP) {
                ttmp.tseen = 1;
                newsym(zx, zy);
                num_p.value++;
            }
        } else {
            const db = find_drawbridge(zx, zy);
            if (db.found) {
                await open_drawbridge(db.x, db.y);
                num_p.value++;
            }
        }
    }
}
// ── reveal_terrain: show known map without monsters/objects/traps ──
// C ref: detect.c:2356
export async function reveal_terrain(which_subset) {
    const g = game;
    const full = (which_subset & TER_FULL) !== 0;
    if ((Hallucination() || Stunned() || Confusion()) && !full) {
        await You('are too disoriented for this.');
    } else {
        const keep_traps = (which_subset & TER_TRP) !== 0;
        const keep_objs = (which_subset & TER_OBJ) !== 0;
        const keep_mons = (which_subset & TER_MON) !== 0;
        const swallowed = g.u?.uswallow;
        if (unconstrain_map()) await docrt();
        // C ref: detect.c:2168 reveal_terrain_getglyph + 2357 reveal_terrain.
        // Partial port: picks the map-layer glyph. Object / trap / monster
        // stripping is not yet implemented (keep_* flags are ignored), but
        // the map background follows C: memory glyph for hero_memory mode,
        // back_to_glyph for seen cells, GLYPH_UNEXPLORED otherwise.
        const default_glyph = GLYPH_UNEXPLORED;
        const hero_memory = !!g.level?.flags?.hero_memory;
        for (let x = 1; x < COLNO; x++) {
            for (let y = 0; y < ROWNO; y++) {
                const loc = g.level?.at(x, y);
                let glyph;
                if (full) {
                    glyph = back_to_glyph(x, y);
                } else if (hero_memory) {
                    glyph = Number.isInteger(loc?.glyph) && loc.glyph >= 0
                        ? loc.glyph : default_glyph;
                } else if (loc?.seenv) {
                    glyph = back_to_glyph(x, y);
                } else {
                    glyph = default_glyph;
                }
                show_glyph(x, y, glyph);
            }
        }
        await flush_screen(1);
        let buf;
        if (full) {
            buf = 'underlying terrain';
        } else {
            buf = 'known terrain';
            if (keep_traps)
                buf += ((keep_objs || keep_mons) ? ',' : ' and') + ' traps';
            if (keep_objs)
                buf += ((keep_traps || keep_mons) ? ',' : '') +
                        (keep_mons ? '' : ' and') + ' objects';
            if (keep_mons)
                buf += ((keep_traps || keep_objs) ? ',' : '') + ' and monsters';
        }
        await pline(`Showing ${buf} only...`);
        which_subset |= TER_MAP;
        g._reveal_terrain_active = true;
        try {
            await browse_map(which_subset, 'anything of interest');
            await map_redisplay();
        } finally {
            g._reveal_terrain_active = false;
        }
    }
}
// ── findit: reveal secret doors, corridors, traps, hidden monsters ──
// C ref: detect.c:1792 findit()
// Called by WAN_SECRET_DOOR_DETECTION / SPE_DETECT_UNSEEN
export async function findit() {
    if (game.u?.uswallow) return 0;
    const found = {
        num_sdoors: 0,
        num_scorrs: 0,
        num_traps: 0,
        num_mons: 0,
        num_invis: 0,
        num_cleared_invis: 0,
        num_kept_invis: 0,
        ft_cc_x: 0,
        ft_cc_y: 0,
    };
    await do_clear_area(game.u.ux, game.u.uy, BOLT_LIM, findone, found);
    let num = 0;
    const k = (found.num_sdoors ? 1 : 0)
        + (found.num_scorrs ? 1 : 0)
        + (found.num_traps ? 1 : 0)
        + (found.num_mons ? 1 : 0);
    let buf = '';
    if (found.num_sdoors) {
        buf += (found.num_sdoors > 1) ? `${found.num_sdoors} secret doors` : 'a secret door';
        num += found.num_sdoors;
    }
    if (found.num_scorrs) {
        if (buf) buf += (k === 2) ? ' and ' : ', ';
        buf += (found.num_scorrs > 1) ? `${found.num_scorrs} secret corridors` : 'a secret corridor';
        num += found.num_scorrs;
    }
    if (found.num_traps) {
        if (buf) {
            buf += (k === 3 && !found.num_mons) ? ', and ' : (k === 2) ? ' and ' : ', ';
        }
        buf += (found.num_traps > 1) ? `${found.num_traps} traps` : 'a trap';
        num += found.num_traps;
    }
    if (found.num_mons) {
        if (buf) buf += (k > 2) ? ', and ' : ' and ';
        buf += (found.num_mons > 1) ? `${found.num_mons} hidden monsters` : 'a hidden monster';
        num += found.num_mons;
    }
    if (buf) await You(`reveal ${buf}!`);
    if (found.num_invis) {
        const msg = (found.num_invis > 1)
            ? `${found.num_invis}${found.num_kept_invis ? ' other' : ''} unseen monsters`
            : `${found.num_kept_invis ? 'another' : 'an'} unseen monster`;
        await You(`detect ${msg}!`);
        num += found.num_invis;
    }
    if (found.num_cleared_invis) {
        if (!num) {
            await You_feel(`${found.num_kept_invis ? 'somewhat ' : ''}less paranoid.`);
        }
        num += found.num_cleared_invis;
    }
    if (!num) await You("don't find anything.");
    return num;
}
/*detect.js*/