All files / js priest.js

62.09% Statements 552/889
59.55% Branches 106/178
65.62% Functions 21/32
62.09% Lines 552/889

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 89073x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 17x 17x 17x 17x 17x 17x 73x 73x 73x 73x 26x 26x 26x 26x 26x 73x 1x 1x 73x 73x     73x 73x 73x 73x 73x 73x 73x 73x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 73x 73x 73x 73x           73x 73x 73x 73x 73x 97x 97x 97x 97x 97x 97x 97x 97x 73x 97x 97x 97x 97x 97x 97x 97x 97x       97x 97x 97x     97x           97x 97x 97x 97x     97x 73x 73x 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x 73x 73x 73x         73x 73x 73x 73x 73x 73x 73x 160x 160x 160x 160x 160x 160x 160x 160x       125x 125x 125x 125x 125x 125x 125x 160x 3x 3x 5x 3x 3x 3x 5x 3x 3x 125x 125x 125x 131x 126x 126x 126x 700x 700x 700x 700x 700x 700x 685x 685x 685x 685x 685x 131x 131x 131x 131x 685x 700x 126x 126x 126x 126x 1x 1x 1x 126x 125x 160x 100x     100x                                                 100x 100x 100x 100x 100x 100x 100x 100x 100x 100x 25x 160x 73x 73x 73x 73x 1269x 161x 161x 161x 161x 161x 161x 161x 159x 1269x 73x 73x 73x 73x 3x 3x 72x 72x 72x 72x 72x 72x 2x 3x 73x 73x 73x 73x 595x 595x 595x 595x         595x 595x 595x 73x 73x 73x 73x 17x 17x 73x 73x 73x 73x                                                                                                               73x 73x 73x 73x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 2x 2x 2x 1x 1x 2x 1x 1x 2x     2x   2x 2x                                 2x 3x 73x 73x 73x 73x               73x 73x 73x 73x                                                                                                                                                 73x 73x 73x 73x 97x 97x 97x     97x 97x 97x 97x 97x 97x 97x 97x 97x       97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 97x 73x 73x 73x 73x 91x 68x 91x 68x 68x 91x 56x 56x 56x 56x 68x 91x 73x 73x 73x 73x 1271x 1271x 1271x 1271x 1271x 1271x 1271x 1271x 1271x 1271x 2x 2x           2x 2x 2x     1271x 1271x 73x 73x 73x 73x                                                                                                         73x 73x 73x 73x                                             73x 73x 73x 73x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x     26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 3x 3x 26x 26x 26x 26x 76x 76x 76x 26x 26x 26x 15x 15x 15x 15x 13x 13x 15x 15x 26x 26x 73x 73x 73x 73x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x                         96x     96x 96x 96x 73x 73x 73x 73x 2x 6x 6x 6x     6x 2x 73x 73x 73x 73x                   73x 73x 73x 73x      
// priest.js — Priest and temple mechanics (port of priest.c)
// C ref: priest.c — 944 lines
 
import { game } from './gstate.js';
import { mon_pmname } from './do_name.js';
import { pline, You, You_feel, verbalize } from './pline.js';
import { canspotmon, newsym, SET_BOTL } from './display.js';
import { canseemon } from './display.js';
import { couldsee } from './vision.js';
import { rn2, rn1, c_d } from './rng.js';
import { makemon, mongets } from './makemon.js';
import { mkobj } from './mkobj.js';
import { mpickobj } from './steal.js';
import { MON_AT, m_at } from './map_access.js';
import { set_malign } from './dog.js';
import { is_minion, is_rider, m_canseeu, mon_learns_traps, resist_conflict } from './mondata.js';
import { tunnels, nohands, verysmall } from './mondata.js';
import { perceives } from './mondata.js';
import { which_armor } from './worn.js';
import { curse, uncurse } from './mkobj.js';
import { mons } from './monsters.js';
import { dist2, highc, monnear, on_level, s_suffix, sgn } from './hacklib.js';
import { DEADMONSTER, m_next2u, mfndpos, mon_allowflags, monhaskey, mon_nam, Monnam, setmangry, wakeup } from './mon.js';
import { newemin } from './minion.js';
import { inhishop, in_rooms, money2u } from './shk.js';
import { rndmonnam, bogon_is_pname } from './do_name.js';
import { halu_gname, a_gname_at } from './pray.js';
import { record_achievement } from './insight.js';
import { body_part } from './polyself.js';
import { nomul } from './cmd.js';
import { exercise } from './attrib.js';
import { linedup } from './mthrowu.js';
import { buzz } from './zap.js';
import { rloc } from './teleport.js';
import { place_monster, remove_monster } from './steed.js';
import { mattackm } from './mhitm.js';
import { check_special_room } from './hack.js';
import { MM_EPRI, N_DIRS, xdir, ydir, ROOMOFFSET,
    A_NONE, A_LAWFUL, A_CHAOTIC, A_NEUTRAL,
    W_ARMC, ALL_TRAPS, isok, Amask2align, TEMPLE, IS_ROOM,
    ALLOW_M, NOTONL, ALLOW_SANCT, ALLOW_SSM, ALLOW_U, ALLOW_DIG,
    ALLOW_ROCK, M_ATTK_AGR_DIED, M_ATTK_DEF_DIED, M_ATTK_HIT, NORMAL_SPEED,
    OPENDOOR, UNLOCKDOOR, IS_DOOR, IS_ALTAR, AM_SHRINE, AM_MASK,
    ACH_TMPL, SPINE,
    ARTICLE_NONE, ARTICLE_THE, ARTICLE_A, ARTICLE_YOUR,
    BZ_OFS_AD, RLOC_NOMSG } from './const.js';
import { AD_ELEC, PM_HIGH_CLERIC, PM_ALIGNED_CLERIC, PM_GHOST, PM_ANGEL } from './monsters.js';
import { AMULET_OF_YENDOR, SPBOOK_no_NOVEL } from './objects.js';
import { SetVoice } from './sounds.js';
import { EMIN, EPRI, u_at } from './const.js';
import { helpless, money_cnt } from './hack.js';
import { Conflict, Deaf, Displaced, Hallucination, In_endgame, Invis, Is_astralevel, Is_sanctum, Underwater } from './macros.js';
import { mattacku } from './mhitu.js';
 
// Local stubs for functions not yet exported
function onlineu(x, y) {
    const u = game.u;
    if (!u) return false;
    return x === u.ux || y === u.uy
        || Math.abs(x - u.ux) === Math.abs(y - u.uy);
}
// MON_AT: imported from map_access.js
// m_canseeu: imported from mondata.js
// Is_sanctum: imported from macros.js
// SET_BOTL imported from display.js
function pm_good_location(px, py, _prim) {
    if (!isok(px, py)) return false;
    const loc = game.level?.at(px, py);
    return loc && !MON_AT(px, py);
}
// mon_pmname: imported from do_name.js
async function verbalize1(msg) { return await verbalize(msg); }
function mapseen_temple(_priest) { /* TODO */ }
// BZ_OFS_AD: imported from const.js
// AD_ELEC: imported from monsters.js
function BZ_M_SPELL(bztyp) { return -10 - bztyp; }
function program_state_gameover() { return false; }
 
// C ref: priest.c:9-10
const ALGN_SINNED = -4;
const ALGN_DEVOUT = 14;
 
// ── newepri ──
// C ref: priest.c:16
export function newepri(mtmp) {
    if (!mtmp.mextra) mtmp.mextra = {};
    if (!mtmp.mextra.epri) {
        mtmp.mextra.epri = {
            shroom: 0,
            shralign: 0,
            shrpos: { x: 0, y: 0 },
            shrlevel: { dnum: 0, dlevel: 0 },
            intone_time: 0,
            enter_time: 0,
            peaceful_time: 0,
            hostile_time: 0,
            cheapskate_count: 0,
            parentmid: mtmp.m_id || 0,
        };
    }
}
 
// ── free_epri ──
// C ref: priest.c:28
export function free_epri(mtmp) {
    if (mtmp.mextra && mtmp.mextra.epri) {
        mtmp.mextra.epri = null;
    }
    mtmp.ispriest = 0;
}
 
// Helper: get EPRI
// Helper: get EMIN
// ── histemple_at ──
// C ref: priest.c:153
function histemple_at(priest, x, y) {
    if (!priest || !priest.ispriest) return false;
    const epri = EPRI(priest);
    if (!epri) return false;
    const temple_rooms = in_rooms(x, y, TEMPLE);
    if (!template_rooms_includes(temple_rooms, epri.shroom)) return false;
    return on_level(epri.shrlevel, game.u?.uz);
}
 
function template_rooms_includes(rooms, shroom) {
    const room_matches_shroom = (room) => {
        if (typeof room === 'number') {
            // Accept either C-style room number (already ROOMOFFSET-based)
            // or JS in_rooms() 0-based room index.
            return room === shroom || (room + ROOMOFFSET) === shroom;
        }
        if (typeof room === 'string' && room.length > 0) {
            return room.charCodeAt(0) === shroom;
        }
        return false;
    };
 
    if (typeof rooms === 'number') {
        return room_matches_shroom(rooms);
    }
    if (typeof rooms === 'string') {
        for (let i = 0; i < rooms.length; i++) {
            if (rooms.charCodeAt(i) === shroom) return true;
        }
        return false;
    }
    if (Array.isArray(rooms)) {
        for (const room of rooms) {
            if (room_matches_shroom(room)) return true;
        }
    }
    return false;
}
 
// ── has_shrine ──
// C ref: priest.c:376
function has_shrine(pri) {
    if (!pri || !pri.ispriest) return false;
    const epri_p = EPRI(pri);
    if (!epri_p) return false;
    const lev = game.level?.at(epri_p.shrpos.x, epri_p.shrpos.y);
    if (!lev || !IS_ALTAR(lev.typ) || !(lev.altarmask & AM_SHRINE))
        return false;
    return epri_p.shralign === Amask2align(lev.altarmask & ~AM_SHRINE);
}
 
// ── inhistemple ──
// C ref: priest.c:161
export function inhistemple(priest) {
    if (!priest || !priest.ispriest) return false;
    if (!histemple_at(priest, priest.mx, priest.my)) return false;
    return has_shrine(priest);
}
 
/*
 * Move for priests and shopkeepers. Called from shk_move() and pri_move().
 * Valid returns are  1: moved  0: didn't  -1: let m_move do it  -2: died.
 */
// C ref: priest.c:42
export async function move_special(mtmp, in_his_shop, appr, uondoor, avoid,
                                   omx, omy, ggx, ggy) {
    let nx, ny, nix, niy;
    let chcnt = 0;
    let ninfo = 0;
 
    if (omx === ggx && omy === ggy)
        return 0;
    if (mtmp.mconf) {
        avoid = false;
        appr = 0;
    }
 
    nix = omx;
    niy = omy;
    // C ref: priest.c:65 — mon_allowflags computes all capability flags
    const allowflags = mon_allowflags(mtmp);
    const positions = mfndpos(mtmp, allowflags);
 
    if (mtmp.isshk && avoid && uondoor) {
        let found_non_onl = false;
        for (let i = 0; i < positions.length; i++) {
            if (!(positions[i].info & NOTONL)) {
                found_non_onl = true;
                break;
            }
        }
        if (!found_non_onl) avoid = false;
    }
 
    // pick_move loop
    let pick_again = true;
    while (pick_again) {
        pick_again = false;
        chcnt = 0;
        for (let i = 0; i < positions.length; i++) {
            nx = positions[i].x;
            ny = positions[i].y;
            const info = positions[i].info ?? 0;
            const typ = game.level?.at(nx, ny)?.typ ?? 0;
            if (IS_ROOM(typ)
                || (mtmp.isshk && (!in_his_shop || mtmp?.mextra?.eshk?.following))) {
                if (avoid && (info & NOTONL) && !(info & ALLOW_M))
                    continue;
                if ((!appr && !rn2(++chcnt))
                    || (appr && dist2(nx, ny, ggx, ggy) < dist2(nix, niy, ggx, ggy))
                    || (info & ALLOW_M)) {
                    nix = nx;
                    niy = ny;
                    ninfo = info;
                }
            }
        }
 
        // C ref: priest.c:95-101 — priest retry if on line with hero
        if (mtmp.ispriest && avoid && nix === omx && niy === omy
            && onlineu(omx, omy)) {
            avoid = false;
            pick_again = true;
        }
    }
 
    if (nix !== omx || niy !== omy) {
        if (ninfo & ALLOW_ROCK) {
            // m_break_boulder(mtmp, nix, niy); // TODO
            return 1;
        } else if (ninfo & ALLOW_M) {
            /* C ref: priest.c:107-116 move_special() calls m_move_aggress(),
               translating its return values to move_special semantics. */
            let mstatus = 0;
            const mtmp2 = m_at(nix, niy);
            if (mtmp2) {
                mstatus = await mattackm(mtmp, mtmp2);
            }
            if ((mstatus & M_ATTK_AGR_DIED) || DEADMONSTER(mtmp)) {
                return -2;
            }
            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;
                }
            }
            return 1;
        }
 
        if (MON_AT(nix, niy) || u_at(nix, niy))
            return 0;
        remove_monster(omx, omy);
        place_monster(mtmp, nix, niy);
        newsym(nix, niy);
        if (mtmp.isshk && !in_his_shop && inhishop(mtmp))
            await check_special_room(false);
        return 1;
    }
    return 0;
}
 
// ── temple_occupied ──
// C ref: priest.c:141
export function temple_occupied(rooms) {
    if (!rooms) return 0;
    const g = game;
    for (let i = 0; i < rooms.length; i++) {
        const ch = typeof rooms === 'string' ? rooms.charCodeAt(i) : rooms[i];
        const idx = ch - ROOMOFFSET;
        const rm = g.level?.rooms?.[idx];
        if (rm && rm.rtype === TEMPLE) return ch;
    }
    return 0;
}
 
// ── findpriest ──
// C ref: priest.c:392
export function findpriest(roomno) {
    if (!roomno) return null;
    for (let mtmp = game.fmon; mtmp; mtmp = mtmp.nmon) {
        if (mtmp.dead) continue;
        if (mtmp.ispriest && EPRI(mtmp)
            && EPRI(mtmp).shroom === roomno
            && histemple_at(mtmp, mtmp.mx, mtmp.my))
            return mtmp;
    }
    return null;
}
 
// ── mon_aligntyp ──
// C ref: priest.c:280
export function mon_aligntyp(mon) {
    let algn;
    if (mon.ispriest) {
        algn = EPRI(mon)?.shralign ?? mon.data?.maligntyp ?? 0;
    } else if (mon.isminion) {
        algn = EMIN(mon)?.min_align ?? mon.data?.maligntyp ?? 0;
    } else {
        algn = mon.data?.maligntyp ?? 0;
    }
    if (algn === A_NONE) return A_NONE;
    return (algn > 0) ? A_LAWFUL : (algn < 0) ? A_CHAOTIC : A_NEUTRAL;
}
 
// ── p_coaligned ──
// C ref: priest.c:370
export function p_coaligned(priest) {
    return game.u?.ualign?.type === mon_aligntyp(priest);
}
 
// ── priestname ──
// C ref: priest.c:301
export function priestname(mon, article, reveal_high_priest, pname_buf) {
    const do_hallu = Hallucination();
    const aligned_priest = (mon.data === mons[PM_ALIGNED_CLERIC]);
    const high_priest = (mon.data === mons[PM_HIGH_CLERIC]);
    let whatcode = { value: '\0' };
    let what = do_hallu ? rndmonnam(whatcode) : mon_pmname(mon);

    if (!mon.ispriest && !mon.isminion)
        return what;

    if (mon.ispriest || aligned_priest || high_priest)
        what = do_hallu ? 'poohbah' : mon.female ? 'priestess' : 'priest';

    let pname = '';
    if (article !== ARTICLE_NONE && (!do_hallu || !bogon_is_pname(whatcode.value))) {
        if (article === ARTICLE_YOUR || (article === ARTICLE_A && high_priest))
            article = ARTICLE_THE;
        if (article === ARTICLE_THE) {
            pname = 'the ';
        } else if (what === 'Angel') {
            pname = 'an ';
        } else {
            // just_an approximation
            pname = /^[aeiouAEIOU]/.test(what) ? 'an ' : 'a ';
        }
    }

    if (mon.minvis) {
        if (pname === 'a ') pname = 'an ';
        pname += 'invisible ';
    }
    if (mon.isminion && EMIN(mon)?.renegade) {
        if (pname === 'an ' && !mon.minvis) pname = 'a ';
        pname += 'renegade ';
    }

    if (mon.ispriest || aligned_priest) {
        if (high_priest)
            pname += do_hallu ? 'grand ' : 'high ';
    } else {
        if (mon.mtame && what.toLowerCase() === 'angel')
            pname += 'guardian ';
    }

    pname += what;

    if (do_hallu || !high_priest || reveal_high_priest
        || !Is_astralevel(game.u?.uz)
        || m_next2u(mon) || program_state_gameover()) {
        pname += ' of ';
        pname += halu_gname(mon_aligntyp(mon));
    }

    if (pname_buf !== undefined) return pname;
    return pname;
}
 
// ── intemple ──
// C ref: priest.c:410 — called from check_special_room when player enters temple
export async function intemple(roomno) {
    const u = game.u;
    if (!u) return;
 
    // don't do anything if hero is already in the room
    if (temple_occupied(u.urooms0)) return;
 
    const priest = findpriest(roomno);
    if (priest) {
        // tended temple
        record_achievement(ACH_TMPL);
 
        const epri_p = EPRI(priest);
        const shrined = has_shrine(priest);
        const sanctum = (priest.data === mons[PM_HIGH_CLERIC]
            && (Is_sanctum(u.uz) || In_endgame(u.uz)));
        const can_speak = !helpless(priest);
 
        if (can_speak && !Deaf() && game.moves >= (epri_p.intone_time || 0)) {
            const save_priest = priest.ispriest;
            if (sanctum && !Hallucination())
                priest.ispriest = 0;
            await pline(`${canseemon(priest) ? Monnam(priest) : 'A nearby voice'} intones:`);
            priest.ispriest = save_priest;
            epri_p.intone_time = game.moves + c_d(10, 500);
            epri_p.enter_time = 0;
        }
 
        let msg1 = null, msg2 = null;
        if (sanctum && Is_sanctum(u.uz)) {
            if (priest.mpeaceful) {
                msg1 = "Infidel, you have entered Moloch's Sanctum!";
                msg2 = "Be gone!";
                priest.mpeaceful = 0;
                set_malign(priest);
            } else {
                msg1 = "You desecrate this place by your presence!";
            }
        } else if (game.moves >= (epri_p.enter_time || 0)) {
            msg1 = `Pilgrim, you enter a ${!shrined ? 'desecrated' : 'sacred'} place!`;
        }
 
        if (msg1 && can_speak && !Deaf()) {
            SetVoice(priest, 0, 80, 0);
            await verbalize1(msg1);
            if (msg2) await verbalize1(msg2);
            epri_p.enter_time = game.moves + c_d(10, 100);
        }
 
        if (!sanctum) {
            let this_time_key, other_time_key;
            if (!shrined || !p_coaligned(priest)
                || (u.ualign?.record ?? 0) <= ALGN_SINNED) {
                const strange = (!shrined || !p_coaligned(priest)) ? '' : ' strange';
                msg1 = `have a${strange} forbidding feeling...`;
                this_time_key = 'hostile_time';
                other_time_key = 'peaceful_time';
            } else {
                const article = ((u.ualign?.record ?? 0) >= ALGN_DEVOUT) ? 'a' : 'an unusual';
                msg1 = `experience ${article} sense of peace.`;
                this_time_key = 'peaceful_time';
                other_time_key = 'hostile_time';
            }
            const this_time = epri_p[this_time_key] || 0;
            const other_time = epri_p[other_time_key] || 0;
            if (game.moves >= this_time || other_time >= this_time) {
                await You(msg1);
                epri_p[this_time_key] = game.moves + c_d(10, 20);
                if (epri_p[this_time_key] <= epri_p[other_time_key])
                    epri_p[other_time_key] = epri_p[this_time_key] - 1;
            }
        }
        // C: recognize Valley/Sanctum — mapseen_temple
        mapseen_temple(priest);
    } else {
        // untended temple
        switch (rn2(4)) {
        case 0:
            await You("have an eerie feeling...");
            break;
        case 1:
            await You_feel("like you are being watched.");
            break;
        case 2:
            await pline(`A shiver runs down your ${body_part(SPINE)}.`);
            break;
        default:
            break;
        }
        if (!rn2(5)) {
            const mtmp = await makemon(mons[PM_GHOST], game.u.ux, game.u.uy, 0x00020000 /* MM_NOMSG */);
            if (mtmp) {
                const ngen = game.mvitals?.[PM_GHOST]?.born ?? 0;
                if (canspotmon(mtmp))
                    await pline(`A${ngen < 5 ? 'n enormous' : ''} ghost appears next to you${ngen < 10 ? '!' : '.'}`);
                else
                    await You("sense a presence close by!");
                mtmp.mpeaceful = 0;
                set_malign(mtmp);
                if (game.flags?.verbose)
                    await You("are frightened to death, and unable to move.");
                nomul(-3);
                game.multi_reason = "being terrified of a ghost";
                game.nomovemsg = "You regain your composure.";
            }
        }
    }
}
 
// ── forget_temple_entry ──
// C ref: priest.c:544
export function forget_temple_entry(priest) {
    const epri_p = priest.ispriest ? EPRI(priest) : null;
    if (!epri_p) return;
    epri_p.intone_time = 0;
    epri_p.enter_time = 0;
    epri_p.peaceful_time = 0;
    epri_p.hostile_time = 0;
}
 
// ── priest_talk ──
// C ref: priest.c:558
export async function priest_talk(priest) {
    const coaligned = p_coaligned(priest);
    const strayed = (game.u?.ualign?.record ?? 0) < 0;
    const epri = EPRI(priest);
    let cheapskate = epri ? epri : null;

    // KMH, conduct
    if (!game.u?.uconduct) game.u.uconduct = {};
    if (!(game.u.uconduct.gnostic++)) {
        // livelog_printf — not ported
    }

    if (priest.mflee || (!priest.ispriest && coaligned && strayed)) {
        await pline(`${Monnam(priest)} doesn't want anything to do with you!`);
        priest.mpeaceful = 0;
        return;
    }

    if (!inhistemple(priest) || !priest.mpeaceful || helpless(priest)) {
        const cranky_msg = [
            "Thou wouldst have words, eh?  I'll give thee a word or two!",
            "Talk?  Here is what I have to say!",
            "Pilgrim, I would speak no longer with thee."
        ];
        if (helpless(priest)) {
            await pline(`${Monnam(priest)} breaks out of ${priest.female ? 'her' : 'his'} reverie!`);
            priest.mfrozen = 0;
            priest.msleeping = 0;
            priest.mcanmove = 1;
        }
        priest.mpeaceful = 0;
        SetVoice(priest, 0, 80, 0);
        await verbalize1(cranky_msg[rn2(3)]);
        return;
    }

    // desecrated temple
    if (priest.mpeaceful && in_rooms(priest.mx, priest.my, TEMPLE).length > 0
        && !has_shrine(priest)) {
        SetVoice(priest, 0, 80, 0);
        await verbalize("Begone!  Thou desecratest this holy place with thy presence.");
        priest.mpeaceful = 0;
        return;
    }

    if (!money_cnt(game.invent)) {
        if (coaligned && !strayed) {
            const pmoney = money_cnt(priest.minvent);
            if (pmoney > 0) {
                const bits = Hallucination() ? 'zorkmids'
                    : (pmoney === 1) ? 'bit' : 'bits';
                await pline(`${Monnam(priest)} gives you ${pmoney === 1 ? 'one' : 'two'} ${bits} for an ale.`);
                money2u(priest, pmoney > 1 ? 2 : 1);
            } else {
                await pline(`${Monnam(priest)} preaches the virtues of poverty.`);
            }
            exercise(6 /* A_WIS */, true);
        } else {
            await pline(`${Monnam(priest)} is not interested.`);
        }
        return;
    } else {
        // donation logic
        const suggested = (game.u.ulevelpeak || 1) *
            rn1(101, 150 + (cheapskate?.cheapskate_count || 0) * 40);
        let quan = Math.trunc(money_cnt(game.invent) / (suggested * 3));
        if (quan < 1) quan = 1;

        await pline(`${Monnam(priest)} asks you for a contribution for the temple.`);
        // bribe() interaction — TODO: full implementation
        // For now, stub out the donation interaction
    }
}
 
// ── mk_roamer ──
// C ref: priest.c:724
export async function mk_roamer(ptr, alignment, x, y, peaceful) {
    const coaligned = (game.u?.ualign?.type === alignment);
 
    if (MON_AT(x, y)) {
        await rloc(m_at(x, y), RLOC_NOMSG);
    }
 
    const MM_ADJACENTOK_VAL = 0x00000010;
    const MM_EMIN_VAL = 0x00000400;
    const MM_NOMSG_VAL = 0x00020000;
    const roamer = await makemon(ptr, x, y, MM_ADJACENTOK_VAL | MM_EMIN_VAL | MM_NOMSG_VAL);
    if (!roamer) return null;
 
    if (!roamer.emin && roamer.mextra) roamer.emin = roamer.mextra.emin;
    if (!roamer.emin) {
        newemin(roamer);
        if (roamer.mextra?.emin) roamer.emin = roamer.mextra.emin;
    }
 
    const emin = EMIN(roamer);
    if (emin) {
        emin.min_align = alignment;
        emin.renegade = coaligned && !peaceful;
    }
    roamer.ispriest = 0;
    roamer.isminion = 1;
    mon_learns_traps(roamer, ALL_TRAPS);
    roamer.mpeaceful = peaceful ? 1 : 0;
    roamer.msleeping = 0;
    set_malign(roamer);
 
    return roamer;
}
 
// ── reset_hostility ──
// C ref: priest.c:755
export function reset_hostility(roamer) {
    if (!roamer.isminion) return;
    if (roamer.data !== mons[PM_ALIGNED_CLERIC]
        && roamer.data !== mons[PM_ANGEL]) return;
 
    const emin = EMIN(roamer);
    if (emin && emin.min_align !== game.u?.ualign?.type) {
        roamer.mpeaceful = 0;
        roamer.mtame = 0;
        set_malign(roamer);
    }
    newsym(roamer.mx, roamer.my);
}
 
// ── in_your_sanctuary ──
// C ref: priest.c:771
export function in_your_sanctuary(mon, x, y) {
    if (mon) {
        if (is_minion(mon.data) || is_rider(mon.data))
            return false;
        x = mon.mx;
        y = mon.my;
    }
    if ((game.u?.ualign?.record ?? 0) <= ALGN_SINNED)
        return false;
    const roomno = temple_occupied(game.u?.urooms);
    if (!roomno) return false;
    const rooms_at = in_rooms(x, y, TEMPLE);
    if (typeof rooms_at === 'string') {
        let found = false;
        for (let i = 0; i < rooms_at.length; i++) {
            if (rooms_at.charCodeAt(i) === roomno) { found = true; break; }
        }
        if (!found) return false;
    } else {
        if (!rooms_at.includes(roomno)) return false;
    }
    const priest = findpriest(roomno);
    if (!priest) return false;
    return has_shrine(priest) && p_coaligned(priest) && priest.mpeaceful;
}
 
// ── ghod_hitsu ──
// C ref: priest.c:796
export async function ghod_hitsu(priest) {
    const u = game.u;
    const roomno = temple_occupied(u?.urooms);
    if (!roomno || !has_shrine(priest)) return;

    const epri = EPRI(priest);
    let ax = epri.shrpos.x;
    let ay = epri.shrpos.y;
    let x = ax, y = ay;
    const rooms = game.level?.rooms || [];
    const troom = rooms[roomno - ROOMOFFSET];
    if (!troom) return;

    if (u_at(x, y) || !linedup(u.ux, u.uy, x, y, 1)) {
        const lev = game.level?.at(u.ux, u.uy);
        if (lev && IS_DOOR(lev.typ)) {
            if (u.ux === troom.lx - 1) {
                x = troom.hx; y = u.uy;
            } else if (u.ux === troom.hx + 1) {
                x = troom.lx; y = u.uy;
            } else if (u.uy === troom.ly - 1) {
                x = u.ux; y = troom.hy;
            } else if (u.uy === troom.hy + 1) {
                x = u.ux; y = troom.ly;
            }
        } else {
            switch (rn2(4)) {
            case 0: x = u.ux; y = troom.ly; break;
            case 1: x = u.ux; y = troom.hy; break;
            case 2: x = troom.lx; y = u.uy; break;
            default: x = troom.hx; y = u.uy; break;
            }
        }
        if (!linedup(u.ux, u.uy, x, y, 1)) return;
    }

    switch (rn2(3)) {
    case 0:
        await pline(`${a_gname_at(ax, ay)} roars in anger:  "Thou shalt suffer!"`);
        break;
    case 1:
        await pline(`${s_suffix(a_gname_at(ax, ay))} voice booms:  "How darest thou harm my servant!"`);
        break;
    default:
        await pline(`${a_gname_at(ax, ay)} roars:  "Thou dost profane my shrine!"`);
        break;
    }

    // bolt of lightning
    await buzz(BZ_M_SPELL(BZ_OFS_AD(AD_ELEC)), 6, x, y,
        sgn(game.tbx || 0), sgn(game.tby || 0));
    exercise(6 /* A_WIS */, false);
}
 
// ── angry_priest ──
// C ref: priest.c:877
export async function angry_priest() {
    const priest = findpriest(temple_occupied(game.u?.urooms));
    if (!priest) return;
    const eprip = EPRI(priest);

    wakeup(priest, false);
    if (setmangry) await setmangry(priest, false);

    // If altar has been destroyed or converted, priest becomes roamer
    const lev = game.level?.at(eprip.shrpos.x, eprip.shrpos.y);
    if (!lev || !IS_ALTAR(lev.typ)
        || Amask2align(lev.altarmask & AM_MASK) !== eprip.shralign) {
        newemin(priest);
        priest.ispriest = 0;
        priest.isminion = 1;
        const emin = EMIN(priest);
        if (emin) {
            emin.min_align = eprip.shralign;
            emin.renegade = false;
        }
        free_epri(priest);
    }
}
 
// ── priestini ──
// C ref: priest.c:220-276
export async function priestini(lvl, sroom, sx, sy, sanctum) {
    const g = game;
    const prim = mons[sanctum ? PM_HIGH_CLERIC : PM_ALIGNED_CLERIC];
    let px = 0, py = 0;
    const si = rn2(N_DIRS);
 
    let i;
    for (i = 0; i < N_DIRS; i++) {
        const dir = ((i + si) % N_DIRS + N_DIRS) % N_DIRS;
        px = sx + xdir[dir];
        py = sy + ydir[dir];
        if (pm_good_location(px, py, prim))
            break;
    }
    if (i === N_DIRS) { px = sx; py = sy; }
 
    if (MON_AT(px, py)) {
        await rloc(m_at(px, py), RLOC_NOMSG);
    }
 
    const priest = await makemon(prim, px, py, MM_EPRI);
    if (priest) {
        const epri = EPRI(priest);
        if (!epri) return null;
        const rooms = g.level.rooms || [];
        const roomIdx = rooms.indexOf(sroom);
        epri.shroom = (roomIdx >= 0 ? roomIdx : 0) + ROOMOFFSET;
        const altarLoc = g.level?.at(sx, sy);
        epri.shralign = Amask2align(altarLoc?.altarmask ?? altarLoc?.flags ?? 0);
        epri.shrpos = { x: sx, y: sy };
        epri.shrlevel = lvl ? { ...lvl } : { ...(g.u?.uz || { dnum: 0, dlevel: 1 }) };
        mon_learns_traps(priest, ALL_TRAPS);
        priest.mpeaceful = 1;
        priest.ispriest = 1;
        priest.isminion = 0;
        priest.msleeping = 0;
        set_malign(priest);
 
        // Amulet of Yendor for high priest in sanctum
        const sl = g.sanctum_level;
        const uz = g.u?.uz;
        if (sanctum && epri.shralign === A_NONE
            && sl && uz && sl.dnum === uz.dnum && sl.dlevel === uz.dlevel) {
            await mongets(priest, AMULET_OF_YENDOR);
        }
 
        // 2 to 4 spellbooks
        const cnt = rn1(3, 2);
        for (let c = 0; c < cnt; c++) {
            const book = mkobj(SPBOOK_no_NOVEL, false);
            if (book) await mpickobj(priest, book);
        }
 
        // Robe: bless or curse based on alignment
        if (rn2(2)) {
            const robe = which_armor(priest, W_ARMC);
            if (robe) {
                if (p_coaligned(priest))
                    uncurse(robe);
                else
                    curse(robe);
            }
        }
    }
}
 
// ── pri_move ──
// C ref: priest.c:177
export async function pri_move(priest) {
    const omx = priest?.mx ?? 0;
    const omy = priest?.my ?? 0;
    let avoid = true;
 
    if (!histemple_at(priest, omx, omy))
        return -1;
 
    const epri = EPRI(priest);
    const temple = epri.shroom;
 
    let ggx = epri.shrpos.x;
    let ggy = epri.shrpos.y;
 
    ggx += rn1(3, -1); // mill around the altar
    ggy += rn1(3, -1);
 
    if (!priest.mpeaceful
        || (Conflict() && !resist_conflict(priest))) {
        if (monnear(priest, game.u.ux, game.u.uy)) {
            if (Displaced())
                await pline(`Your displaced image doesn't fool ${mon_nam(priest)}!`);
            await mattacku(priest);
            return 0;
        } else if ((game.u?.urooms || '').includes(String.fromCharCode(temple))) {
            if (priest.mcansee && m_canseeu(priest)) {
                ggx = game.u.ux;
                ggy = game.u.uy;
            }
            avoid = false;
        }
    } else if (Invis()) {
        avoid = false;
    }
 
    return await move_special(priest, false, 1, false, avoid, omx, omy, ggx, ggy);
}
 
// ── clearpriests ──
// C ref: priest.c:919
export function clearpriests() {
    for (let mtmp = game.fmon; mtmp; mtmp = mtmp.nmon) {
        if (mtmp.dead) continue;
        if (mtmp.ispriest && EPRI(mtmp)
            && !on_level(EPRI(mtmp).shrlevel, game.u?.uz)) {
            // mongone(mtmp); // TODO
        }
    }
}
 
// ── restpriest ──
// C ref: priest.c:933
export function restpriest(mtmp, ghostly) {
    if (game.u?.uz?.dlevel) {
        if (ghostly) {
            const epri = EPRI(mtmp);
            if (epri) {
                epri.shrlevel = { ...game.u.uz };
            }
        }
    }
}
 
// ── priesthit ──
// C ref: priest.c (attack from priest)
export function priesthit(mtmp, mattk) {
    // TODO: full port of priest attack
}