All files / js attrib.js

77.8% Statements 715/919
67.58% Branches 171/253
72.22% Functions 26/36
77.8% Lines 715/919

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 92073x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                     73x 73x 73x 73x 73x 39074x 39074x 39074x 8157x 8864x   39074x 73x 73x 144719x 144719x 144719x 143070x 143070x 143070x 73x 73x 73x 73x 73x 73x 73x 73x 142980x       73x 73x 2474x 1259x 1259x 1259x 1259x 73x 73x 73x 73x 73x 142980x 142980x 142980x     142980x 142980x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 25x 25x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 15x 15x 15x 15x 15x 15x 15x 22x 8x             8x 8x 8x 23x 23x 2x 2x 2x 2x 21x 21x 21x 21x 21x 21x 21x 3x 3x 3x 21x 21x 25x 73x 73x 73x 73x                           73x 73x 73x 73x                                                               73x 73x 73x 73x                               73x 73x         73x 73x 73x 1264x 1264x 1264x 1264x 1228x 1228x 1228x 1228x 1228x 1228x 1228x 1228x 1228x 1228x 1228x 1264x 1264x 1264x 73x 73x 6097x 6097x 6097x 6097x 6097x 6097x 583x 583x 583x 563x 8x 583x 583x 583x 583x 20x 20x 20x 20x 583x 555x 555x 583x         583x 583x     583x 583x 583x 583x 583x 583x 16x 16x 583x 43x 43x 43x 583x       583x 583x 6097x 6097x 6097x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 1204x 6097x 73x 73x 73x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 6097x 3x 3x 3x 3x 3x 18x 18x 10x 10x 10x 10x 18x 18x         10x 18x       10x 10x 10x 10x 10x 10x 18x 10x 10x 10x                         3x 3x 6097x 73x 73x 1674x 1674x 1674x 1674x 5830x 5830x 5830x   1674x 73x 73x 142x 142x 142x 142x 142x 142x 1674x 1674x 1674x 1674x 103x 103x 103x 1571x 1571x 1571x 1571x 1571x 142x 142x 73x 73x 73x 71x 71x 71x 71x 426x 426x 426x 426x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 73x 73x 73x 9x 9x 9x 54x 54x 36x 36x 36x 36x 54x 36x 54x 36x 36x 36x 54x 54x 9x 9x 73x 73x 73x 71x 426x 21x 21x 21x 21x 21x 426x 71x 71x 71x 73x 73x 73x 88x 88x 88x 88x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 3393x 3393x   411x 73x 73x                                                   73x 73x 2468x 73x 73x 73x 73x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 411x 1557x 1557x 1485x 411x 411x 411x 36x 36x 36x 1485x 1074x 1074x 1557x 72x 72x 36x 36x 1146x 1146x 1557x 88x 88x 88x 36x 36x 88x 36x 36x 36x 1557x                   1146x 1557x 1557x 411x 411x 340x 340x 7x 7x 340x 411x 73x 73x 73x 73x 73x 544x 544x 544x 544x 80x 80x 80x 80x 80x 80x 80x 71x 71x 71x 71x     71x 71x 80x 544x 464x 270x 270x 270x 270x 270x 464x 194x 194x 194x 194x 194x 194x 464x 464x 464x 464x 464x 464x 247x 247x 59x 59x 21x 21x     464x 464x 544x 544x 544x 544x 544x 544x           544x 544x 73x 73x 73x 63x 63x 63x 63x 63x 8x 8x 8x 8x 8x 8x 8x 60x 35x 35x 35x 35x 35x 35x 35x 63x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                     73x 73x 73x 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x       1x 1x 1x     1x 1x 1x                                   1x 1x 1x 1x 1x 1x 1x           1x 1x           1x 1x  
// attrib.js — Attribute initialization and management (port of attrib.c)
 
import { game } from './gstate.js';
import { c_d, pushRngLogEntry, rn1, rn2, rnd } from './rng.js';
import { A_CHA, A_CON, A_DEX, A_INT, A_MAX, A_STR, A_WIS, CLAIRVOYANT, COLD_RES, CONFUSION, DIED, EXT_ENCUMBER, FAINTED, FAINTING, FAST, FIRE_RES, FROMEXPER, FROMOUTSIDE, FROMRACE, FUMBLING, HALLUC, HUNGRY, HVY_ENCUMBER, INFRAVISION, INTRINSIC, KILLED_BY, KILLED_BY_AN, MAXULEV, MOD_ENCUMBER, NOT_HUNGRY, POISON_RES, POISONING, REGENERATION, SATIATED, SEARCHING, SEE_INVIS, SHOCK_RES, SICK, SLEEP_RES, STEALTH, STR19, STUNNED, TELEPORT_CONTROL, TIMEOUT, VOMITING, WARNING, WEAK, WOUNDED_LEGS } from './const.js';
import { Upolyd } from './macros.js';
import { setBotl, shieldeff } from './display.js';
import { cansee } from './vision.js';
import { sgn, strstri } from './hacklib.js';
 
// ---- Imports for deps ----
import { encumber_msg, near_capacity } from './pickup.js';
import { see_monsters } from './mon.js';
import { losehp } from './hack.js';
import { setuhpmax } from './polyself.js';
 
// ---- Remaining local stubs ----
// Fixed_abil: imported from macros.js
// add_weapon_skill: imported from weapon.js
// lose_weapon_skill: imported from weapon.js
// setuhpmax: imported from polyself.js
 
// C ref: attrib.c:1182 adjuhploss()
function adjuhploss(loss, olduhp) {
    if (!Upolyd) {
        if (game.u.uhp < olduhp)
            loss -= (olduhp - game.u.uhp);
    } else {
        if (game.u.mh < olduhp)
            loss -= (olduhp - game.u.mh);
    }
    return Math.max(loss, 1);
}
 
// minuhpmax: imported from mondata.js
// C ref: attrib.c:1250 acurrstr() — condense encoded STR into 3..25
// STR encoding: 3-18 normal, 19-118 for 18/01-18/100, 119-125 for 19-25
export function ACURRSTR() {
    const str = ACURR(A_STR);
    if (str <= 18)
        return Math.max(str, 3);
    if (str <= 121) // STR19(21) = 100+21 = 121
        return 19 + Math.trunc(str / 50); // 18/01-18/31→19, 18/32-18/81→20, rest→21
    return Math.min(str, 125) - 100; // 22..25
}
 
// C ref: attrib.h — ATTRMAX(x) = gu.urace.attrmax[x], ATTRMIN(x) = gu.urace.attrmin[x]
function ATTRMAX(i) {
    return game.urace?.attrmax?.[i] ?? 18;
}
function ATTRMIN(i) {
    return game.urace?.attrmin?.[i] ?? 3;
}
 
// ---- Attribute access macros ----
// C ref: ABASE, AMAX, ACURR, ABON macros
export function ABASE(ndx) { return game.u.acurr.a[ndx]; }
export function AMAX(ndx) { return game.u.amax.a[ndx]; }
export function ABON(ndx) { return (game.u.abon?.a?.[ndx] ?? 0); }
 
// C ref: attrib.h — ATEMP(x) = u.atemp.a[x], ATIME(x) = u.atime.a[x]
function ATEMP(ndx) { return game.u.atemp?.a?.[ndx] ?? 0; }
function setATEMP(ndx, val) { game.u.atemp.a[ndx] = val; }
function ATIME(ndx) { return game.u.atime?.a?.[ndx] ?? 0; }
function setATIME(ndx, val) { game.u.atime.a[ndx] = val; }
 
// C ref: attrib.h — AEXE(x) = u.aexe.a[x]
function AEXE(ndx) { return game.u.aexe?.a?.[ndx] ?? 0; }
function setAEXE(ndx, val) {
    if (!game.u.aexe) game.u.aexe = { a: [0, 0, 0, 0, 0, 0] };
    game.u.aexe.a[ndx] = val;
}
 
// C ref: acurr() in attrib.c — simplified ACURR macro
// Full acurr() handles STR encoding, gauntlets of power, dunce cap, etc.
// This is the macro version used for most game logic.
export function ACURR(ndx) {
    let val = ABASE(ndx) + ABON(ndx) + ATEMP(ndx);
    if (ndx === A_STR && Gauntlets_of_power()) val = 118; // 18/100
    if ((ndx === A_INT || ndx === A_WIS) && Dunce_cap()) {
        if (val > 6) val = 6;
    }
    return Math.max(ATTRMIN(ndx), Math.min(val, ATTRMAX(ndx)));
}
 
const AVAL = 50; // tune value for exercise gains
 
// part of the output on gain or loss of attribute
const plusattr = ["strong", "smart", "wise", "agile", "tough", "charismatic"];
const minusattr = ["weak", "stupid", "foolish", "clumsy", "fragile", "repulsive"];
const attrname = ["strength", "intelligence", "wisdom", "dexterity", "constitution", "charisma"];
 
// exercise/abuse text (must be in attribute order)
// phrased as "You must have been [][0]." or "You haven't been [][1]."
const exertext = [
    ["exercising diligently", "exercising properly"],           // Str
    [null, null],                                                // Int
    ["very observant", "paying attention"],                      // Wis
    ["working on your reflexes", "working on reflexes lately"],  // Dex
    ["leading a healthy life-style", "watching your health"],    // Con
    [null, null],                                                // Cha
];
 
// C ref: attrib.c:117 adjattrib()
// Adjusts attribute ndx by incr. Sets botl on change.
// msgflg: positive => no message, zero => message, negative => conditional
// Returns true if attribute actually changed.
export async function adjattrib(ndx, incr, msgflg) {
    const u = game.u;
    if (Fixed_abil() || !incr) return false;
 
    // TODO: dunce cap check for INT/WIS (needs uarmh)
 
    const old_acurr = ACURR(ndx);
    const old_abase = ABASE(ndx);
    const old_amax = AMAX(ndx);
 
    u.acurr.a[ndx] += incr;
    let attrstr, abonflg;
    if (incr > 0) {
        if (u.acurr.a[ndx] > u.amax.a[ndx]) {
            u.amax.a[ndx] = u.acurr.a[ndx];
            if (u.amax.a[ndx] > ATTRMAX(ndx))
                u.acurr.a[ndx] = u.amax.a[ndx] = ATTRMAX(ndx);
        }
        attrstr = plusattr[ndx];
        abonflg = (ABON(ndx) < 0);
    } else {
        if (u.acurr.a[ndx] < ATTRMIN(ndx)) {
            const decr = rn2(ATTRMIN(ndx) - u.acurr.a[ndx] + 1);
            u.acurr.a[ndx] = ATTRMIN(ndx);
            u.amax.a[ndx] -= decr;
            if (u.amax.a[ndx] < ATTRMIN(ndx))
                u.amax.a[ndx] = ATTRMIN(ndx);
        }
        attrstr = minusattr[ndx];
        abonflg = (ABON(ndx) > 0);
    }
 
    if (ACURR(ndx) === old_acurr) {
        // No visible change
        // TODO: verbose messages for msgflg==0 (needs flags.verbose, async pline)
        return false;
    }
 
    // Any successful change also resets abuse / exercise level
    setAEXE(ndx, 0);
 
    setBotl('adjattrib');
    // C ref: attrib.c:194-195 — message for visible attribute change
    if (msgflg <= 0) {
        const prefix = (incr > 1 || incr < -1) ? 'very ' : '';
        await You_feel(`${prefix}${attrstr}!`);
    }
    // TODO: encumber_msg when in_moveloop and STR/CON change
    return true;
}
 
// C ref: attrib.c:201 gainstr()
// Strength gain from potions, etc.
export async function gainstr(otmp, incr, givemsg) {
    let num = incr;

    if (!num) {
        if (ABASE(A_STR) < 18)
            num = (rn2(4) ? 1 : rnd(6));
        else if (ABASE(A_STR) < 103) // STR18(85) = 18+85 = 103
            num = rnd(10);
        else
            num = 1;
    }
    await adjattrib(A_STR, (otmp && otmp.cursed) ? -num : num,
              givemsg ? -1 : 1);
}
 
// C ref: attrib.c:219 losestr()
// Strength loss, may kill you; cause may be poison or monster
export async function losestr(num, knam, k_format) {
    const u = game.u;
    const uhpmin = minuhpmax(1);
    let ustr = ABASE(A_STR) - num;
    const waspolyd = Upolyd();
    let dmg = 0;

    if (num <= 0 || ABASE(A_STR) < ATTRMIN(A_STR)) {
        // impossible
        return;
    }

    while (ustr < ATTRMIN(A_STR)) {
        ++ustr;
        --num;
        const amt = rn1(4, 3); // 3..6
        dmg += amt;
    }
    if (dmg) {
        if (!knam || knam === '') {
            knam = "terminal frailty";
            // k_format = KILLED_BY;
        }
        await losehp(dmg, knam, k_format);

        // TODO: setuhpmax adjustments for poly/non-poly
        setBotl('losestr');
    }
    // num could have been reduced to 0
    if (num > 0 && (Upolyd() || !waspolyd))
        await adjattrib(A_STR, -num, 1);
}
 
// C ref: attrib.c:453 restore_attrib()
// (not used in current C — ATIME is never set to non-zero)
export function restore_attrib() {
    for (let i = 0; i < A_MAX; i++) {
        const equilibrium = ((i === A_STR && (game.u.uhs ?? 0) >= WEAK)
                            || (i === A_DEX && Wounded_legs_check())) ? -1 : 0;
        if (ATEMP(i) !== equilibrium && ATIME(i) !== 0) {
            const newtime = ATIME(i) - 1;
            setATIME(i, newtime);
            if (!newtime) {
                setATEMP(i, ATEMP(i) + (ATEMP(i) > 0 ? -1 : 1));
                setBotl('restore_attrib');
                if (ATEMP(i)) // reset timer
                    setATIME(i, Math.trunc(100 / ACURR(A_CON)));
            }
        }
    }
}
 
// Helper for Wounded_legs check (avoids importing macros.js to prevent circular deps)
function Wounded_legs_check() {
    const wl = game.u?.uprops?.[WOUNDED_LEGS];
    return !!((wl?.intrinsic || 0) || (wl?.extrinsic || 0));
}
 
// C ref: attrib.c:488 exercise()
export function exercise(i, inc_or_dec) {
    if (i === A_INT || i === A_CHA) return; // can't exercise these
 
    // no physical exercise while polymorphed; the body's temporary
    if (Upolyd() && i !== A_WIS) return;
 
    if (Math.abs(AEXE(i)) < AVAL) {
        /*
         *  Law of diminishing returns (Part I):
         *  Gain is harder at higher attribute values.
         *  79% at "3" --> 0% at "18"
         *  Loss is even at all levels (50%).
         */
        const delta = inc_or_dec ? (rn2(19) > ACURR(i) ? 1 : 0) : -rn2(2);
        setAEXE(i, AEXE(i) + delta);
    }
    // C: encumber_msg() if moves > 0 && (STR or CON)
    // TODO: encumber_msg (async)
}
 
// C ref: attrib.c:520 exerper()
async function exerper() {
    const g = game;
    const u = g.u;
    if (!u) return;
 
    if (!((g.moves || 0) % 10)) {
        // Hunger Checks
        const hs = (u.uhunger > 1000) ? SATIATED
            : (u.uhunger > 150) ? NOT_HUNGRY
            : (u.uhunger > 50) ? HUNGRY
            : (u.uhunger > 0) ? WEAK
            : FAINTING;
 
        switch (hs) {
        case SATIATED:
            exercise(A_DEX, false);
            if (Role_if(PM_MONK))
                exercise(A_WIS, false);
            break;
        case NOT_HUNGRY:
            exercise(A_CON, true);
            break;
        case WEAK:
            exercise(A_STR, false);
            if (Role_if(PM_MONK)) // PM_MONK — fasting
                exercise(A_WIS, true);
            break;
        case FAINTING:
        case FAINTED:
            exercise(A_CON, false);
            break;
        }
 
        // Encumbrance Checks
        const enc = near_capacity();
        switch (enc) {
        case MOD_ENCUMBER:
            exercise(A_STR, true);
            break;
        case HVY_ENCUMBER:
            exercise(A_STR, true);
            exercise(A_DEX, false);
            break;
        case EXT_ENCUMBER:
            exercise(A_DEX, false);
            exercise(A_CON, false);
            break;
        }
    }
 
    // status checks
    if (!((g.moves || 0) % 5)) {
        // C: if ((HClairvoyant & (INTRINSIC | TIMEOUT)) && !BClairvoyant)
        const hclair = u.uprops?.[CLAIRVOYANT]?.intrinsic || 0;
        const bclair = u.uprops?.[CLAIRVOYANT]?.blocked || 0;
        if ((hclair & (INTRINSIC | TIMEOUT)) && !bclair)
            exercise(A_WIS, true);
        // C: if (HRegeneration)
        const hregen = u.uprops?.[REGENERATION]?.intrinsic || 0;
        if (hregen)
            exercise(A_STR, true);
 
        const hsick = u.uprops?.[SICK]?.intrinsic || 0;
        const hvomit = u.uprops?.[VOMITING]?.intrinsic || 0;
        if (hsick || hvomit)
            exercise(A_CON, false);
        const hconf = u.uprops?.[CONFUSION]?.intrinsic || 0;
        const hhalluc = u.uprops?.[HALLUC]?.intrinsic || 0;
        if (hconf || hhalluc)
            exercise(A_WIS, false);
        const hwl = u.uprops?.[WOUNDED_LEGS]?.intrinsic || 0;
        const ewl = u.uprops?.[WOUNDED_LEGS]?.extrinsic || 0;
        const hfumb = u.uprops?.[FUMBLING]?.intrinsic || 0;
        const efumb = u.uprops?.[FUMBLING]?.extrinsic || 0;
        const hstun = u.uprops?.[STUNNED]?.intrinsic || 0;
        if (((hwl || ewl) && !u.usteed) || (hfumb || efumb) || hstun)
            exercise(A_DEX, false);
    }
}
 
// C ref: attrib.c:597 exerchk()
export async function exerchk() {
    const g = game;
    const u = g.u;
 
    // Check out the periodic accumulations
    await exerper();
 
    // Are we ready for a test?
    if ((g.moves || 0) >= (g.context?.next_attrib_check ?? Infinity)
        && !(g.multi || 0)) {
        /*
         *  Law of diminishing returns (Part II):
         *  The effects of "exercise" and "abuse" wear off over time.
         */
        for (let i = 0; i < A_MAX; ++i) {
            let ax = AEXE(i);
            if (!ax) continue; // ok to skip nextattrib
 
            const mod_val = sgn(ax); // +1 or -1
            const lolim = ATTRMIN(i);
            let hilim = ATTRMAX(i);
            if (hilim > 18) hilim = 18;
            if ((ax < 0) ? (ABASE(i) <= lolim) : (ABASE(i) >= hilim)) {
                // goto nextattrib — just do the decay
                setAEXE(i, Math.trunc(Math.abs(ax) / 2) * mod_val);
                continue;
            }
            // can't exercise non-Wisdom while polymorphed
            if (Upolyd() && i !== A_WIS) {
                setAEXE(i, Math.trunc(Math.abs(ax) / 2) * mod_val);
                continue;
            }
 
            /*
             *  Law of diminishing returns (Part III):
             *  You don't *always* gain by exercising.
             *  [MRS 92/10/28 - Treat Wisdom specially for balance.]
             */
            if (rn2(AVAL) > ((i !== A_WIS) ? Math.trunc(Math.abs(ax) * 2 / 3) : Math.abs(ax))) {
                setAEXE(i, Math.trunc(Math.abs(ax) / 2) * mod_val);
                continue;
            }

            if (await adjattrib(i, mod_val, -1)) {
                // if you actually changed an attrib - zero accumulation
                setAEXE(i, 0);
                ax = 0;
                // then print an explanation
                // TODO: You() message (async) — skipping for now
            }
            // this used to be AEXE(i) /= 2 but that would produce
            // platform-dependent rounding/truncation for negative vals
            setAEXE(i, Math.trunc(Math.abs(ax) / 2) * mod_val);
        }
        g.context.next_attrib_check += rn1(200, 800);
    }
}
 
// C ref: attrib.c:682 rnd_attr()
function rnd_attr() {
    let x = rn2(100);
    const attrdist = game.urole?.attrdist || [20, 15, 15, 20, 20, 10];
    for (let i = 0; i < A_MAX; i++) {
        x -= attrdist[i];
        if (x < 0) return i;
    }
    return A_MAX;
}
 
// C ref: attrib.c:699 init_attr_role_redist()
function init_attr_role_redist(np, addition) {
    const u = game.u;
    let tryct = 0;
    const adj = addition ? 1 : -1;
 
    while ((addition ? (np > 0) : (np < 0)) && tryct < 100) {
        const i = rnd_attr();
        if (i >= A_MAX
            || (addition ? (ABASE(i) >= ATTRMAX(i))
                         : (ABASE(i) <= ATTRMIN(i)))) {
            tryct++;
            continue;
        }
        tryct = 0;
        u.acurr.a[i] += adj;
        u.amax.a[i] += adj;
        np -= adj;
    }
    return np;
}
 
// C ref: attrib.c:723 init_attr()
export function init_attr(np) {
    const u = game.u;
    const attrbase = game.urole?.attrbase || [10, 10, 10, 10, 10, 10];
 
    for (let i = 0; i < A_MAX; i++) {
        u.acurr.a[i] = u.amax.a[i] = attrbase[i];
        u.atemp.a[i] = u.atime.a[i] = 0;
        np -= attrbase[i];
    }
 
    // C ref: event checkpoint — attribute base values before redistribution
    pushRngLogEntry(`^attr_base[${u.acurr.a.join(',')}]`);
 
    // distribute leftover points
    np = init_attr_role_redist(np, true);
    // if we went over, remove points
    np = init_attr_role_redist(np, false);
 
    // C ref: event checkpoint — attribute values after redistribution
    pushRngLogEntry(`^attr_redist[${u.acurr.a.join(',')}]`);
}
 
// C ref: attrib.c:739 redist_attr()
export function redist_attr() {
    const u = game.u;
 
    for (let i = 0; i < A_MAX; i++) {
        if (i === A_INT || i === A_WIS)
            continue;
        // Polymorphing doesn't change your mind
        const tmp = u.amax.a[i];
        u.amax.a[i] += (rn2(5) - 2);
        if (u.amax.a[i] > ATTRMAX(i))
            u.amax.a[i] = ATTRMAX(i);
        if (u.amax.a[i] < ATTRMIN(i))
            u.amax.a[i] = ATTRMIN(i);
        u.acurr.a[i] = Math.trunc(u.acurr.a[i] * u.amax.a[i] / tmp);
        // ABASE(i) > ATTRMAX(i) is impossible
        if (u.acurr.a[i] < ATTRMIN(i))
            u.acurr.a[i] = ATTRMIN(i);
    }
    // encumber_msg() — caller needs to do this
}
 
// C ref: attrib.c:764 vary_init_attr()
export async function vary_init_attr() {
    for (let i = 0; i < A_MAX; i++) {
        if (!rn2(20)) {
            const xd = rn2(7) - 2; // biased variation
            await adjattrib(i, xd, 1); // msgflg=1 means silent (TRUE)
            if (ABASE(i) < AMAX(i))
                game.u.amax.a[i] = game.u.acurr.a[i];
        }
    }
    // C ref: event checkpoint — attribute values after variation
    pushRngLogEntry(`^attr_vary[${game.u.acurr.a.join(',')}]`);
}
 
// C ref: attrib.c:778 postadjabil()
export function postadjabil(ability_prop) {
    if (ability_prop == null) return;
    if (ability_prop === WARNING || ability_prop === SEE_INVIS)
        see_monsters();
}
 
// ---- Innate ability tables ----
// Each entry: { ulevel, ability_prop, gainstr, losestr }
// ability_prop is the property index into u.uprops[].intrinsic
const arc_abil = [
    { ulevel: 1, ability: SEARCHING, gainstr: "", losestr: "" },
    { ulevel: 5, ability: STEALTH, gainstr: "stealthy", losestr: "" },
    { ulevel: 10, ability: FAST, gainstr: "quick", losestr: "slow" },
    null,
];
const bar_abil = [
    { ulevel: 1, ability: POISON_RES, gainstr: "", losestr: "" },
    { ulevel: 7, ability: FAST, gainstr: "quick", losestr: "slow" },
    { ulevel: 15, ability: STEALTH, gainstr: "stealthy", losestr: "" },
    null,
];
const cav_abil = [
    { ulevel: 7, ability: FAST, gainstr: "quick", losestr: "slow" },
    { ulevel: 15, ability: WARNING, gainstr: "sensitive", losestr: "" },
    null,
];
const hea_abil = [
    { ulevel: 1, ability: POISON_RES, gainstr: "", losestr: "" },
    { ulevel: 15, ability: WARNING, gainstr: "sensitive", losestr: "" },
    null,
];
const kni_abil = [
    { ulevel: 7, ability: FAST, gainstr: "quick", losestr: "slow" },
    null,
];
const mon_abil = [
    { ulevel: 1, ability: FAST, gainstr: "", losestr: "" },
    { ulevel: 1, ability: SLEEP_RES, gainstr: "", losestr: "" },
    { ulevel: 1, ability: SEE_INVIS, gainstr: "", losestr: "" },
    { ulevel: 3, ability: POISON_RES, gainstr: "healthy", losestr: "" },
    { ulevel: 5, ability: STEALTH, gainstr: "stealthy", losestr: "" },
    { ulevel: 7, ability: WARNING, gainstr: "sensitive", losestr: "" },
    { ulevel: 9, ability: SEARCHING, gainstr: "perceptive", losestr: "unaware" },
    { ulevel: 11, ability: FIRE_RES, gainstr: "cool", losestr: "warmer" },
    { ulevel: 13, ability: COLD_RES, gainstr: "warm", losestr: "cooler" },
    { ulevel: 15, ability: SHOCK_RES, gainstr: "insulated", losestr: "conductive" },
    { ulevel: 17, ability: TELEPORT_CONTROL, gainstr: "controlled", losestr: "uncontrolled" },
    null,
];
const pri_abil = [
    { ulevel: 15, ability: WARNING, gainstr: "sensitive", losestr: "" },
    { ulevel: 20, ability: FIRE_RES, gainstr: "cool", losestr: "warmer" },
    null,
];
const ran_abil = [
    { ulevel: 1, ability: SEARCHING, gainstr: "", losestr: "" },
    { ulevel: 7, ability: STEALTH, gainstr: "stealthy", losestr: "" },
    { ulevel: 15, ability: SEE_INVIS, gainstr: "", losestr: "" },
    null,
];
const rog_abil = [
    { ulevel: 1, ability: STEALTH, gainstr: "", losestr: "" },
    { ulevel: 10, ability: SEARCHING, gainstr: "perceptive", losestr: "" },
    null,
];
const sam_abil = [
    { ulevel: 1, ability: FAST, gainstr: "", losestr: "" },
    { ulevel: 15, ability: STEALTH, gainstr: "stealthy", losestr: "" },
    null,
];
const tou_abil = [
    { ulevel: 10, ability: SEARCHING, gainstr: "perceptive", losestr: "" },
    { ulevel: 20, ability: POISON_RES, gainstr: "hardy", losestr: "" },
    null,
];
const val_abil = [
    { ulevel: 1, ability: COLD_RES, gainstr: "", losestr: "" },
    { ulevel: 3, ability: STEALTH, gainstr: "stealthy", losestr: "" },
    { ulevel: 7, ability: FAST, gainstr: "quick", losestr: "slow" },
    null,
];
const wiz_abil = [
    { ulevel: 15, ability: WARNING, gainstr: "sensitive", losestr: "" },
    { ulevel: 17, ability: TELEPORT_CONTROL, gainstr: "controlled", losestr: "uncontrolled" },
    null,
];
 
// Race intrinsics
const dwa_abil = [
    { ulevel: 1, ability: INFRAVISION, gainstr: "", losestr: "" },
    null,
];
const elf_abil = [
    { ulevel: 1, ability: INFRAVISION, gainstr: "", losestr: "" },
    { ulevel: 4, ability: SLEEP_RES, gainstr: "awake", losestr: "tired" },
    null,
];
const gno_abil = [
    { ulevel: 1, ability: INFRAVISION, gainstr: "", losestr: "" },
    null,
];
const orc_abil = [
    { ulevel: 1, ability: INFRAVISION, gainstr: "", losestr: "" },
    { ulevel: 1, ability: POISON_RES, gainstr: "", losestr: "" },
    null,
];
const hum_abil = [null];
 
import { pline, pline_The, You, You_feel, Your } from './pline.js';
// Import PM_ constants for role/race lookup
import { G_UNIQ, mons, PM_ARCHEOLOGIST, PM_BARBARIAN, PM_CAVE_DWELLER, PM_CLERIC, PM_DWARF, PM_ELF, PM_GNOME, PM_HEALER, PM_HUMAN, PM_KNIGHT, PM_MONK, PM_ORC, PM_RANGER, PM_ROGUE, PM_SAMURAI, PM_TOURIST, PM_VALKYRIE, PM_WIZARD } from './monsters.js';
import { add_weapon_skill, lose_weapon_skill } from './weapon.js';
import { type_is_pname } from './do_name.js';
import { done } from './end.js';
import { Fixed_abil, Poison_resistance, Role_if, setH, Dunce_cap, Gauntlets_of_power } from './macros.js';
import { minuhpmax, name_to_mon } from './mondata.js';
import { the } from './objnam.js';
 
// C ref: attrib.c:788 role_abil()
function role_abil(r) {
    const roleabils = [
        { role: PM_ARCHEOLOGIST, abil: arc_abil },
        { role: PM_BARBARIAN, abil: bar_abil },
        { role: PM_CAVE_DWELLER, abil: cav_abil },
        { role: PM_HEALER, abil: hea_abil },
        { role: PM_KNIGHT, abil: kni_abil },
        { role: PM_MONK, abil: mon_abil },
        { role: PM_CLERIC, abil: pri_abil },
        { role: PM_RANGER, abil: ran_abil },
        { role: PM_ROGUE, abil: rog_abil },
        { role: PM_SAMURAI, abil: sam_abil },
        { role: PM_TOURIST, abil: tou_abil },
        { role: PM_VALKYRIE, abil: val_abil },
        { role: PM_WIZARD, abil: wiz_abil },
    ];
    for (const entry of roleabils) {
        if (entry.role === r) return entry.abil;
    }
    return null;
}
 
// C ref: attrib.c:817 check_innate_abil()
function check_innate_abil(ability_prop, frommask) {
    let abil = null;

    if (frommask === FROMEXPER) {
        abil = role_abil(game.urole?.mnum ?? -1);
    } else if (frommask === FROMRACE) {
        const race_mnum = game.urace?.mnum ?? -1;
        switch (race_mnum) {
        case PM_DWARF: abil = dwa_abil; break;
        case PM_ELF:   abil = elf_abil; break;
        case PM_GNOME: abil = gno_abil; break;
        case PM_ORC:   abil = orc_abil; break;
        case PM_HUMAN: abil = hum_abil; break;
        default: break;
        }
    }

    if (!abil) return null;
    for (const entry of abil) {
        if (!entry) break; // null sentinel
        if (entry.ability === ability_prop && game.u.ulevel >= entry.ulevel)
            return entry;
    }
    return null;
}
 
// Helper: get/set intrinsic for a property
function getH(prop) { return game.u?.uprops?.[prop]?.intrinsic || 0; }
// setH: imported from macros.js
 
// C ref: attrib.c:1005 adjabil()
export async function adjabil(oldlevel, newlevel) {
    let abil = role_abil(game.urole?.mnum ?? -1);
    let rabil;
    let mask = FROMEXPER;
 
    const race_mnum = game.urace?.mnum ?? -1;
    switch (race_mnum) {
    case PM_ELF: rabil = elf_abil; break;
    case PM_ORC: rabil = orc_abil; break;
    case PM_HUMAN:
    case PM_DWARF:
    case PM_GNOME:
    default: rabil = null; break;
    }
 
    let ai = 0; // index into abil
    let ri = 0; // index into rabil
    let using_rabil = false;
 
    while (true) {
        let entry;
        if (!using_rabil) {
            if (!abil || !abil[ai] || abil[ai] === null) {
                // Try race intrinsics
                if (!rabil || !rabil[ri] || rabil[ri] === null)
                    break;
                using_rabil = true;
                mask = FROMRACE;
                entry = rabil[ri++];
            } else {
                entry = abil[ai++];
            }
        } else {
            if (!rabil || !rabil[ri] || rabil[ri] === null)
                break;
            entry = rabil[ri++];
        }
 
        const prevabil = getH(entry.ability);
        if (oldlevel < entry.ulevel && newlevel >= entry.ulevel) {
            // Gaining ability
            if (entry.ulevel === 1)
                setH(entry.ability, getH(entry.ability) | (mask | FROMOUTSIDE));
            else
                setH(entry.ability, getH(entry.ability) | mask);
            if (!(getH(entry.ability) & INTRINSIC & ~mask)) {
                if (entry.gainstr)
                    await You_feel(`${entry.gainstr}!`);
            }
        } else if (oldlevel >= entry.ulevel && newlevel < entry.ulevel) {
            // Losing ability
            setH(entry.ability, getH(entry.ability) & ~mask);
            if (!(getH(entry.ability) & INTRINSIC)) {
                if (entry.losestr)
                    await You_feel(`${entry.losestr}!`);
                else if (entry.gainstr)
                    await You_feel(`less ${entry.gainstr}!`);
            }
        }
        if (prevabil !== getH(entry.ability))
            postadjabil(entry.ability);
    }
 
    if (oldlevel > 0) {
        if (newlevel > oldlevel)
            await add_weapon_skill(newlevel - oldlevel);
        else
            lose_weapon_skill(oldlevel - newlevel);
    }
}
 
// C ref: attrib.c:1079 newhp()
// Called when gaining a level (before u.ulevel gets incremented);
// also called with u.ulevel==0 during hero initialization
export function newhp() {
    const u = game.u;
    let hp, conplus;
 
    if (u.ulevel === 0) {
        // Initialize hit points
        hp = (game.urole?.hpadv?.infix ?? 0) + (game.urace?.hpadv?.infix ?? 0);
        if ((game.urole?.hpadv?.inrnd ?? 0) > 0)
            hp += rnd(game.urole.hpadv.inrnd);
        if ((game.urace?.hpadv?.inrnd ?? 0) > 0)
            hp += rnd(game.urace.hpadv.inrnd);
        if ((game.moves || 0) === 0) {
            // initial hero; skip for polyself to new man
            // Initialize alignment stuff
            const aligns = game.aligns; // imported in roles.js
            if (aligns && game.flags?.initalign != null) {
                u.ualign.type = aligns[game.flags.initalign].value;
            }
            u.ualign.record = game.urole?.initrecord ?? 0;
        }
        // no Con adjustment for initial hit points
    } else {
        if (u.ulevel < (game.urole?.xlev ?? 14)) {
            hp = (game.urole?.hpadv?.lofix ?? 0) + (game.urace?.hpadv?.lofix ?? 0);
            if ((game.urole?.hpadv?.lornd ?? 0) > 0)
                hp += rnd(game.urole.hpadv.lornd);
            if ((game.urace?.hpadv?.lornd ?? 0) > 0)
                hp += rnd(game.urace.hpadv.lornd);
        } else {
            hp = (game.urole?.hpadv?.hifix ?? 0) + (game.urace?.hpadv?.hifix ?? 0);
            if ((game.urole?.hpadv?.hirnd ?? 0) > 0)
                hp += rnd(game.urole.hpadv.hirnd);
            if ((game.urace?.hpadv?.hirnd ?? 0) > 0)
                hp += rnd(game.urace.hpadv.hirnd);
        }
        if (ACURR(A_CON) <= 3)
            conplus = -2;
        else if (ACURR(A_CON) <= 6)
            conplus = -1;
        else if (ACURR(A_CON) <= 14)
            conplus = 0;
        else if (ACURR(A_CON) <= 16)
            conplus = 1;
        else if (ACURR(A_CON) === 17)
            conplus = 2;
        else if (ACURR(A_CON) === 18)
            conplus = 3;
        else
            conplus = 4;
        hp += conplus;
    }
    if (hp <= 0) hp = 1;
    if (u.ulevel < MAXULEV) {
        // remember increment; future level drain could take it away again
        if (!u.uhpinc) u.uhpinc = new Array(MAXULEV).fill(0);
        u.uhpinc[u.ulevel] = hp;
    } else {
        // after level 30, throttle hit point gains from extra experience
        let lim = 5 - Math.trunc(u.uhpmax / 300);
        lim = Math.max(lim, 1);
        if (hp > lim) hp = lim;
    }
    return hp;
}
 
// C ref: attrib.c:1297 adjalign()
export function adjalign(n) {
    const u = game.u;
    if (!u?.ualign) return;
    const newalign = u.ualign.record + n;
 
    if (n < 0) {
        const newabuse = (u.ualign.abuse || 0) - n;
        if (newalign < u.ualign.record)
            u.ualign.record = newalign;
        if (newabuse > (u.ualign.abuse || 0)) {
            u.ualign.abuse = newabuse;
            // TODO: adj_erinys(newabuse);
        }
    } else if (newalign > u.ualign.record) {
        u.ualign.record = newalign;
        // C ref: include/align.h — ALIGNLIM = 10 + (moves / 200)
        // Use truncation for C-style integer division.
        const alignlim = 10 + Math.trunc((game.moves || 0) / 200);
        if (u.ualign.record > alignlim)
            u.ualign.record = alignlim;
    }
}
 
// C ref: attrib.c:280-313 — poiseff[] and poisontell()
const poiseff = [
    { func: You_feel, msg: 'weaker' },             // A_STR
    { func: Your,     msg: 'brain is on fire' },    // A_INT
    { func: Your,     msg: 'judgement is impaired' }, // A_WIS
    { func: Your,     msg: 'muscles won\'t obey you' }, // A_DEX
    { func: You_feel, msg: 'very sick' },           // A_CON
    { func: You,      msg: 'break out in hives' },  // A_CHA
];
 
export async function poisontell(typ, exclaim) {
    let msg_txt = poiseff[typ].msg;
    const func = poiseff[typ].func;

    if (typ === A_STR && ACURR(A_STR) === STR19(25))
        msg_txt = 'innately weaker';
    else if (typ === A_CON && ACURR(A_CON) === 25)
        msg_txt = 'sick inside';

    await func(`${msg_txt}${exclaim ? '!' : '.'}`);
}
 
// C ref: attrib.c:317-408 — poisoned()
// Handles poison damage from traps, darts, etc.
export async function poisoned(reason, typ, pkiller, fatal, thrown_weapon) {
    const u = game.u;
    const disp = game.disp || (game.disp = {});
    let kprefix = KILLED_BY_AN;
    const blast = (reason === 'blast');
 
    // inform player about being poisoned
    if (!blast && !strstri(reason, 'poison')) {
        const plural = reason[reason.length - 1] === 's';
        const article = (reason[0] === reason[0].toUpperCase()) ? '' : 'The ';
        await pline(`${article}${reason} ${plural ? 'were' : 'was'} poisoned!`);
    }
    if (Poison_resistance()) {
        if (blast) shieldeff(u.ux, u.uy);
        await pline_The("poison doesn't seem to affect you.");
        return;
    }
 
    // suppress killer prefix if it already has one
    let i = name_to_mon(pkiller, null);
    if (i >= 0 && i < mons.length && (mons[i].geno & G_UNIQ)) {
        kprefix = KILLED_BY;
        if (!type_is_pname(mons[i]))
            pkiller = the(pkiller);
    } else if (pkiller.slice(0, 4).toLowerCase() === 'the '
               || pkiller.slice(0, 3).toLowerCase() === 'an '
               || pkiller.slice(0, 2).toLowerCase() === 'a ') {
        kprefix = KILLED_BY;
    }
 
    i = !fatal ? 1 : rn2(fatal + (thrown_weapon ? 20 : 0));
    if (i === 0 && typ !== A_CHA) {
        // sometimes survivable instant kill
        const loss_base = 6 + c_d(4, 6); // 6 + 4d6 => 10..34
        if (u.uhp <= loss_base) {
            u.uhp = -1;
            disp.botl = true;
            await pline_The('poison was deadly...');
        } else {
            const olduhp = u.uhp;
            const newuhpmax = u.uhpmax - Math.trunc(loss_base / 2);
            setuhpmax(Math.max(newuhpmax, minuhpmax(3)), true);
            const loss = adjuhploss(loss_base, olduhp);
            await losehp(loss, pkiller, kprefix);
            if (await adjattrib(A_CON, (typ !== A_CON) ? -1 : -3, true))
                await poisontell(A_CON, true);
            if (typ !== A_CON && await adjattrib(typ, -3, 1))
                await poisontell(typ, true);
        }
    } else if (i > 5) {
        const cloud = (reason === 'gas cloud');
        let loss = thrown_weapon ? rnd(6) : rn1(10, 6);
        if ((blast || cloud) && false /* Half_gas_damage */)
            loss = Math.trunc((loss + 1) / 2);
        await losehp(loss, pkiller, kprefix);
    } else {
        // attribute loss
        const loss = (thrown_weapon || !fatal) ? 1 : c_d(2, 2);
        if (await adjattrib(typ, -loss, 1))
            await poisontell(typ, true);
    }
 
    if (u.uhp < 1) {
        game.killer = game.killer || {};
        game.killer.format = kprefix;
        game.killer.name = pkiller;
        await done(strstri(pkiller, 'poison') ? DIED : POISONING);
    }
    await encumber_msg();
}