All files / js ball.js

57.47% Statements 527/917
58.46% Branches 76/130
63.63% Functions 14/22
57.47% Lines 527/917

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 91873x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 53x 53x 53x 53x 53x 53x 53x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 183x 183x 183x 183x 183x 183x 73x 12x 12x 12x 12x 73x 73x 73x 73x 4x 4x 4x                       4x 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 73x 73x 73x                                                                   73x 73x 73x 73x 1x 1x 1x   1x 73x 73x 73x 73x 1x 1x 1x 1x       1x 1x 73x 73x 73x 73x             73x 73x 73x 73x                   73x 73x 73x 73x                   73x 73x 73x 83x 83x 83x 83x 83x 83x 83x 83x 2x 2x 2x 83x 83x 2x 2x 2x 2x 2x   2x 2x       83x 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 73x 73x 73x 73x 229x 229x 229x 229x 229x 102x 49x 20x 20x 1x 1x 1x 20x       20x 20x 20x 20x 20x 20x 20x 20x 20x 49x                                               29x 13x 1x 1x 1x 1x               1x 1x 13x 13x 13x 13x 13x     13x 13x 13x 49x 49x 49x 229x 127x 127x 80x 33x 33x 80x 80x 80x 80x 80x 80x 80x 80x 80x 127x 47x 47x 47x 47x 30x 30x 30x 47x 17x 17x 17x 17x 47x 47x 47x 47x 127x 229x 73x 73x 73x 73x 73x 73x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 49x 49x 49x 49x 84x 84x 133x 27x 27x 27x 27x 27x 27x 27x               27x 27x 27x 27x 27x 27x 20x 20x 27x 27x 27x 27x           27x 27x 27x 9x 9x 9x 9x 9x 9x 27x 27x 10x 10x 7x 7x 7x 10x 3x 3x 3x 3x 10x 10x                           10x 10x                           10x 10x   10x 10x 10x 10x 9x 10x 1x 1x 10x 9x 9x 9x 10x 10x 10x 27x 27x 2x 2x 2x 2x 2x 2x 2x 27x 27x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 5x 5x 5x 4x 4x 4x 4x 1x 1x 1x 27x 27x     27x 27x 27x 27x 27x 27x 27x 57x 57x 133x         57x 57x 57x 133x 1x 133x 133x 133x                                                                 57x 57x 57x 57x 133x       133x 57x 57x 57x 57x 28x 28x 28x       28x 57x 57x 57x 57x 57x 57x 57x 57x 133x 73x 73x 73x 73x                                                                                                                                                               73x 73x 73x 3x 3x 3x 3x 3x 31x 31x 1x           1x 31x 31x 3x 73x 73x 73x 73x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x             4x 4x               4x 3x 3x 3x 3x 3x 3x 4x 4x 73x 73x 73x 73x                                                                                                                   73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 72x 72x  
// ball.js — Ball and chain (punishment) mechanics (port of ball.c)
// C ref: ball.c — 1105 lines
//
// Full port of ball & chain management: placement, movement, dragging,
// and sanity checks. No RNG in most functions; drag_ball has rn2 for
// chain placement tiebreaking and combat.
 
import { game } from './gstate.js';
 
import { You, You_feel, Your, impossible, pline, pline_The } from './pline.js';
import { map_object, newsym } from './display.js';
import { place_object, remove_object, obj_extract_self } from './mkobj.js';
import { carried } from './invent.js';
import { freeinv } from './invent.js';
import { MON_AT, levl, m_at, t_at } from './map_access.js';
import { A_STR, BC_BALL, BC_CHAIN, D_CLOSED, D_LOCKED, HEAD, HMON_DRAGGED, IS_DOOR, is_hole, IS_OBSTRUCTED, is_pit, isok, KILLED_BY_AN, LEFT_SIDE, LEG, NO_KILLER_PREFIX, OBJ_FLOOR, OBJ_FREE, OBJ_INVENT, POOL, RIGHT_SIDE, SLT_ENCUMBER, TT_BEARTRAP, TT_BURIEDBALL, TT_INFLOOR, TT_LAVA, TT_PIT, TT_WEB, W_BALL, W_CHAIN, W_WEAPONS } from './const.js';
import { HEAVY_IRON_BALL, IRON_CHAIN } from './objects.js';
import { rn2, rnd, rn1 } from './rng.js';
import { dist2, distmin } from './hacklib.js';
import { near_capacity, encumber_msg } from './pickup.js';
import { nomul } from './cmd.js';
import { welded } from './wield.js';
import { setuwep, setuqwep, setuswapwep } from './wield.js';
import { xname, yname, Yname2, otense } from './objnam.js';
import { body_part } from './polyself.js';
import { is_pool } from './dbridge.js';
// dbridge import removed (level predicates moved to const.js);
import { Blind, Is_waterlevel, Levitation, Maybe_Half_Phys, Punished } from './macros.js';
import { losehp, spoteffects } from './hack.js';
import { canletgo, flooreffects } from './do.js';
import { exercise } from './attrib.js';
import { hmon } from './uhitm.js';
import { miss } from './zap.js';
import { find_mac } from './worn.js';
import { hitfloor, omon_adj } from './dothrow.js';
import { set_wounded_legs } from './do.js';
import { Soundeffect } from './sounds.js';
import { hard_helmet } from './do_wear.js';
import { cls } from './display.js';
import { weight_cap } from './pickup.js';
import { fill_pit, reset_utrap } from './trap.js';
import { deltrap } from './trap.js';
import { hliquid } from './do_name.js';
import { setnotworn } from './worn.js';
import { maybe_unhide_at } from './mon.js';
// safe_typename not yet ported; inline fallback used in bc_sanity_check
 
// ── Local stubs for not-yet-ported dependencies ──
 
// C ref: hack.c:808 movobj() — move object, updating display
function movobj(obj, ox, oy) {
    remove_object(obj);
    // maybe_unhide_at(obj.ox, obj.oy); // TODO
    newsym(obj.ox, obj.oy);
    place_object(obj, ox, oy);
    newsym(ox, oy);
}
 
// C ref: display.c:333 map_object() — show object glyph at its position
// map_object: imported from display.js
// maybe_unhide_at: imported from mon.js
 
// C ref: invent.c:XXX canletgo() — can hero drop this object?
// C ref: dothrow.c hitfloor() — object hits the floor
// C ref: trap.c fill_pit() — fill in a pit
// C ref: hack.c MON_AT macro
// MON_AT: imported from map_access.js
const BCPOS_DIFFER = 0; // ball & chain at different positions
const BCPOS_CHAIN = 1;  // chain on top of ball
const BCPOS_BALL = 2;   // ball on top of chain
 
// ── module-level state (C static) ──
 
// ── Helper macros used in drag_ball ──
 
function IS_CHAIN_ROCK(x, y) {
    const loc = levl(x, y);
    if (!loc) return true;
    return IS_OBSTRUCTED(loc.typ)
        || (IS_DOOR(loc.typ) && (loc.doormask & (D_CLOSED | D_LOCKED)));
}
 
function CHAIN_IN_MIDDLE(chx, chy, x, y, uball) {
    return distmin(x, y, chx, chy) <= 1
        && distmin(chx, chy, uball.ox, uball.oy) <= 1;
}
 
// ── ballrelease ──
// C ref: ball.c:23
export async function ballrelease(showmsg) {
    const u = game.u;
    const uball = u.uball;
    if (carried(uball) && !welded(uball)) {
        if (showmsg)
            await pline("Startled, you drop the iron ball.");
        if (u.uwep === uball)
            await setuwep(null);
        if (u.uswapwep === uball)
            setuswapwep(null);
        if (u.uquiver === uball)
            setuqwep(null);
        freeinv(uball);
        await encumber_msg();
    }
}
 
// ── ballfall ──
// C ref: ball.c:42
export async function ballfall() {
    const u = game.u;
    const uball = u.uball;
    if (!uball || (uball && carried(uball) && welded(uball)))
        return;

    const gets_hit = ((uball.ox !== u.ux || uball.oy !== u.uy)
        && (u.uwep === uball ? false : !!rn2(5)));
    await ballrelease(true);
    if (gets_hit) {
        let dmg = rn1(7, 25);

        await pline_The(`iron ball falls on your ${body_part(HEAD)}.`);
        if (u.uarmh) {
            if (hard_helmet(u.uarmh)) {
                await pline("Fortunately, you are wearing a hard helmet.");
                dmg = 3;
            } else if (game.flags?.verbose) {
                await pline(`${Yname2(u.uarmh)} does not protect you.`);
            }
        }
        await losehp(Maybe_Half_Phys(dmg),
            "crunched in the head by an iron ball", NO_KILLER_PREFIX);
    }
}
 
// ── placebc_core (static) ──
// C ref: ball.c:119
function placebc_core() {
    const u = game.u;
    const uchain = u.uchain;
    const uball = u.uball;
    if (!uchain || !uball) {
        impossible("Where are your ball and chain?");
        return;
    }
 
    // chain might rust
    // flooreffects is async but C calls it synchronously here with (void) cast
    // For now, skip the async call in this sync context — rust is cosmetic
    // TODO: make placebc async if flooreffects matters
 
    if (carried(uball)) {
        u.bc_order = BCPOS_DIFFER;
    } else {
        // ball might rust -- already checked when carried
        place_object(uball, u.ux, u.uy);
        u.bc_order = BCPOS_CHAIN;
    }
 
    place_object(uchain, u.ux, u.uy);
 
    const loc = levl(u.ux, u.uy);
    u.bglyph = u.cglyph = loc ? loc.glyph : -1;
 
    newsym(u.ux, u.uy);
    game.bcrestriction = 0;
}
 
// ── unplacebc_core (static) ──
// C ref: ball.c:146
function unplacebc_core() {
    const u = game.u;
    const uchain = u.uchain;
    const uball = u.uball;

    if (u.uswallow) {
        if (Is_waterlevel(u.uz)) {
            if (!carried(uball))
                obj_extract_self(uball);
            obj_extract_self(uchain);
        }
        return;
    }

    if (!carried(uball)) {
        obj_extract_self(uball);
        if (Blind() && (u.bc_felt & BC_BALL)) {
            const loc = levl(uball.ox, uball.oy);
            if (loc) loc.glyph = u.bglyph;
        }
        maybe_unhide_at(uball.ox, uball.oy);
        newsym(uball.ox, uball.oy);
    }
    obj_extract_self(uchain);
    if (Blind() && (u.bc_felt & BC_CHAIN)) {
        const loc = levl(uchain.ox, uchain.oy);
        if (loc) loc.glyph = u.cglyph;
    }
    maybe_unhide_at(uchain.ox, uchain.oy);

    newsym(uchain.ox, uchain.oy);
    u.bc_felt = 0;
}
 
// ── check_restriction (static) ──
// C ref: ball.c:179
const override_restriction = -1; // sentinel value
function check_restriction(restriction) {
    if (!game.bcrestriction || restriction === override_restriction)
        return true;
    return game.bcrestriction === restriction;
}
 
// ── placebc ──
// C ref: ball.c:192 (non-BREADCRUMBS version)
export function placebc() {
    if (!check_restriction(0))
        return;
    const uchain = game.u.uchain;
    if (uchain && uchain.where !== OBJ_FREE) {
        impossible("bc already placed?");
        return;
    }
    placebc_core();
}
 
// ── unplacebc ──
// C ref: ball.c:211
export function unplacebc() {
    if (game.bcrestriction) {
        impossible("unplacebc denied, restriction in place");
        return;
    }
    unplacebc_core();
}
 
// ── unplacebc_and_covet_placebc ──
// C ref: ball.c:221
export function unplacebc_and_covet_placebc() {
    let restriction = 0;
    if (game.bcrestriction) {
        impossible("unplacebc_and_covet_placebc denied, already restricted");
    } else {
        restriction = game.bcrestriction = rnd(400);
        unplacebc_core();
    }
    return restriction;
}
 
// ── lift_covet_and_placebc ──
// C ref: ball.c:235
export function lift_covet_and_placebc(pin) {
    if (!check_restriction(pin))
        return;
    const uchain = game.u.uchain;
    if (uchain && uchain.where !== OBJ_FREE) {
        impossible("bc already placed?");
        return;
    }
    placebc_core();
}
 
// ── bc_order (static) ──
// C ref: ball.c:353
function bc_order() {
    const u = game.u;
    const uchain = u.uchain;
    const uball = u.uball;
 
    if (uchain.ox !== uball.ox || uchain.oy !== uball.oy
        || carried(uball) || u.uswallow)
        return BCPOS_DIFFER;
 
    // Walk the object chain at ball's position
    // In JS, we iterate level.objects to find objects at this position
    const objs = game.level?.objects;
    if (objs) {
        // Walk from most-recently-placed (top of pile) to find ordering
        for (let i = objs.length - 1; i >= 0; i--) {
            const obj = objs[i];
            if (obj.ox === uball.ox && obj.oy === uball.oy) {
                if (obj === uchain) return BCPOS_CHAIN;
                if (obj === uball) return BCPOS_BALL;
            }
        }
    }
    impossible("bc_order:  ball&chain not in same location!");
    return BCPOS_DIFFER;
}
 
// ── set_bc ──
// C ref: ball.c:379
export function set_bc(already_blind) {
    const u = game.u;
    const uball = u.uball;
    const uchain = u.uchain;
    const ball_on_floor = !carried(uball);
 
    u.bc_order = bc_order();
    u.bc_felt = ball_on_floor ? (BC_BALL | BC_CHAIN) : BC_CHAIN;
 
    if (already_blind || u.uswallow) {
        const loc = levl(u.ux, u.uy);
        u.cglyph = u.bglyph = loc ? loc.glyph : -1;
        return;
    }
 
    // Remove ball&chain, get underlying glyphs, put them back
    remove_object(uchain);
    if (ball_on_floor)
        remove_object(uball);
 
    newsym(uchain.ox, uchain.oy);
    const chainLoc = levl(uchain.ox, uchain.oy);
    u.cglyph = chainLoc ? chainLoc.glyph : -1;
 
    if (u.bc_order === BCPOS_DIFFER) {
        place_object(uchain, uchain.ox, uchain.oy);
        newsym(uchain.ox, uchain.oy);
        if (ball_on_floor) {
            newsym(uball.ox, uball.oy);
            const ballLoc = levl(uball.ox, uball.oy);
            u.bglyph = ballLoc ? ballLoc.glyph : -1;
            place_object(uball, uball.ox, uball.oy);
            newsym(uball.ox, uball.oy);
        }
    } else {
        u.bglyph = u.cglyph;
        if (u.bc_order === BCPOS_CHAIN) {
            place_object(uball, uball.ox, uball.oy);
            place_object(uchain, uchain.ox, uchain.oy);
        } else {
            place_object(uchain, uchain.ox, uchain.oy);
            place_object(uball, uball.ox, uball.oy);
        }
        newsym(uball.ox, uball.oy);
    }
}
 
// ── move_bc ──
// C ref: ball.c:436
export function move_bc(before, control, ballx, bally, chainx, chainy) {
    const u = game.u;
    const uball = u.uball;
    const uchain = u.uchain;
 
    if (Blind()) {
        if (!before) {
            if ((control & BC_CHAIN) && (control & BC_BALL)) {
                // Both moved
                if (u.bc_felt & BC_BALL) {
                    const loc = levl(uball.ox, uball.oy);
                    if (loc) loc.glyph = u.bglyph;
                }
                if (u.bc_felt & BC_CHAIN) {
                    const loc = levl(uchain.ox, uchain.oy);
                    if (loc) loc.glyph = u.cglyph;
                }
                u.bc_felt = 0;
 
                const bLoc = levl(ballx, bally);
                u.bglyph = bLoc ? bLoc.glyph : -1;
                const cLoc = levl(chainx, chainy);
                u.cglyph = cLoc ? cLoc.glyph : -1;
 
                movobj(uball, ballx, bally);
                movobj(uchain, chainx, chainy);
            } else if (control & BC_BALL) {
                if (u.bc_felt & BC_BALL) {
                    if (u.bc_order === BCPOS_DIFFER) {
                        const loc = levl(uball.ox, uball.oy);
                        if (loc) loc.glyph = u.bglyph;
                    } else if (u.bc_order === BCPOS_BALL) {
                        if (u.bc_felt & BC_CHAIN) {
                            map_object(uchain, 0);
                        } else {
                            const loc = levl(uball.ox, uball.oy);
                            if (loc) loc.glyph = u.bglyph;
                        }
                    }
                    u.bc_felt &= ~BC_BALL;
                }

                if (ballx !== chainx || bally !== chainy) {
                    const loc = levl(ballx, bally);
                    u.bglyph = loc ? loc.glyph : -1;
                } else {
                    u.bglyph = u.cglyph;
                }

                movobj(uball, ballx, bally);
            } else if (control & BC_CHAIN) {
                if (u.bc_felt & BC_CHAIN) {
                    if (u.bc_order === BCPOS_DIFFER) {
                        const loc = levl(uchain.ox, uchain.oy);
                        if (loc) loc.glyph = u.cglyph;
                    } else if (u.bc_order === BCPOS_CHAIN) {
                        if (u.bc_felt & BC_BALL) {
                            map_object(uball, 0);
                        } else {
                            const loc = levl(uchain.ox, uchain.oy);
                            if (loc) loc.glyph = u.cglyph;
                        }
                    }
                    u.bc_felt &= ~BC_CHAIN;
                }
 
                if (ballx !== chainx || bally !== chainy) {
                    const loc = levl(chainx, chainy);
                    u.cglyph = loc ? loc.glyph : -1;
                } else {
                    u.cglyph = u.bglyph;
                }
 
                movobj(uchain, chainx, chainy);
            }
 
            u.bc_order = bc_order();
        }
    } else {
        // Hero is not blind
        if (before) {
            if (!control) {
                u.bc_order = bc_order();
            }
 
            remove_object(uchain);
            maybe_unhide_at(uchain.ox, uchain.oy);
            newsym(uchain.ox, uchain.oy);
            if (!carried(uball)) {
                remove_object(uball);
                maybe_unhide_at(uball.ox, uball.oy);
                newsym(uball.ox, uball.oy);
            }
        } else {
            const on_floor = !carried(uball);
 
            if ((control & BC_CHAIN)
                || (!control && u.bc_order === BCPOS_CHAIN)) {
                if (on_floor)
                    place_object(uball, ballx, bally);
                place_object(uchain, chainx, chainy);
            } else {
                place_object(uchain, chainx, chainy);
                if (on_floor)
                    place_object(uball, ballx, bally);
            }
            newsym(chainx, chainy);
            if (on_floor)
                newsym(ballx, bally);
        }
    }
}
 
// ── drag_ball ──
// C ref: ball.c:559
// Returns { result, bc_control, ballx, bally, chainx, chainy, cause_delay }
// In C this takes pointers; in JS we return an object.
export async function drag_ball(x, y, _bc_control, _ballx, _bally,
    _chainx, _chainy, _cause_delay, allow_drag) {
    const u = game.u;
    const uball = u.uball;
    const uchain = u.uchain;
 
    let ballx = uball.ox;
    let bally = uball.oy;
    let chainx = uchain.ox;
    let chainy = uchain.oy;
    let bc_control = 0;
    let cause_delay = false;
    let t = null;
 
    if (dist2(x, y, uchain.ox, uchain.oy) <= 2) {
        // nothing moved
        move_bc(1, bc_control, ballx, bally, chainx, chainy);
        return { result: true, bc_control, ballx, bally, chainx, chainy, cause_delay };
    }
 
    // only need to move the chain?
    if (carried(uball) || distmin(x, y, uball.ox, uball.oy) <= 2) {
        const oldchainx = uchain.ox;
        const oldchainy = uchain.oy;
 
        bc_control = BC_CHAIN;
        move_bc(1, bc_control, ballx, bally, chainx, chainy);
 
        if (carried(uball)) {
            // move chain only if necessary
            if (distmin(x, y, uchain.ox, uchain.oy) > 1) {
                chainx = u.ux;
                chainy = u.uy;
            }
            return { result: true, bc_control, ballx, bally, chainx, chainy, cause_delay };
        }
 
        // Check if chain is already in rock
        let already_in_rock;
        if (IS_CHAIN_ROCK(u.ux, u.uy) || IS_CHAIN_ROCK(chainx, chainy)
            || IS_CHAIN_ROCK(uball.ox, uball.oy))
            already_in_rock = true;
        else
            already_in_rock = false;
 
        // SKIP_TO_DRAG helper: undo and fall through to drag
        let skip_to_drag = false;
        function SKIP_TO_DRAG() {
            chainx = oldchainx;
            chainy = oldchainy;
            move_bc(0, bc_control, ballx, bally, chainx, chainy);
            skip_to_drag = true;
        }
 
        switch (dist2(x, y, uball.ox, uball.oy)) {
        case 8:
            // two spaces diagonal from ball
            chainx = Math.trunc((uball.ox + x) / 2);
            chainy = Math.trunc((uball.oy + y) / 2);
            if (IS_CHAIN_ROCK(chainx, chainy) && !already_in_rock)
                SKIP_TO_DRAG();
            break;
 
        case 5: {
            let tempx, tempy, tempx2, tempy2;
            if (Math.abs(x - uball.ox) === 1) {
                tempx = x;
                tempx2 = uball.ox;
                tempy = tempy2 = Math.trunc((uball.oy + y) / 2);
            } else {
                tempx = tempx2 = Math.trunc((uball.ox + x) / 2);
                tempy = y;
                tempy2 = uball.oy;
            }
            if (IS_CHAIN_ROCK(tempx, tempy) && !IS_CHAIN_ROCK(tempx2, tempy2)
                && !already_in_rock) {
                if (allow_drag) {
                    if (dist2(u.ux, u.uy, uball.ox, uball.oy) === 5
                        && dist2(x, y, tempx, tempy) === 1)
                        SKIP_TO_DRAG();
                    if (!skip_to_drag
                        && dist2(u.ux, u.uy, uball.ox, uball.oy) === 4
                        && dist2(x, y, tempx, tempy) === 2)
                        SKIP_TO_DRAG();
                }
                if (!skip_to_drag) {
                    chainx = tempx2;
                    chainy = tempy2;
                }
            } else if (!IS_CHAIN_ROCK(tempx, tempy)
                       && IS_CHAIN_ROCK(tempx2, tempy2) && !already_in_rock) {
                if (allow_drag) {
                    if (dist2(u.ux, u.uy, uball.ox, uball.oy) === 5
                        && dist2(x, y, tempx2, tempy2) === 1)
                        SKIP_TO_DRAG();
                    if (!skip_to_drag
                        && dist2(u.ux, u.uy, uball.ox, uball.oy) === 4
                        && dist2(x, y, tempx2, tempy2) === 2)
                        SKIP_TO_DRAG();
                }
                if (!skip_to_drag) {
                    chainx = tempx;
                    chainy = tempy;
                }
            } else if (IS_CHAIN_ROCK(tempx, tempy)
                       && IS_CHAIN_ROCK(tempx2, tempy2) && !already_in_rock) {
                SKIP_TO_DRAG();
            } else if (!skip_to_drag) {
                if (dist2(tempx, tempy, uchain.ox, uchain.oy)
                        < dist2(tempx2, tempy2, uchain.ox, uchain.oy)
                    || (dist2(tempx, tempy, uchain.ox, uchain.oy)
                        === dist2(tempx2, tempy2, uchain.ox, uchain.oy)
                        && rn2(2))) {
                    chainx = tempx;
                    chainy = tempy;
                } else {
                    chainx = tempx2;
                    chainy = tempy2;
                }
            }
            break;
        }
 
        case 4:
            if (CHAIN_IN_MIDDLE(uchain.ox, uchain.oy, x, y, uball))
                break;
            chainx = Math.trunc((x + uball.ox) / 2);
            chainy = Math.trunc((y + uball.oy) / 2);
            if (IS_CHAIN_ROCK(chainx, chainy) && !already_in_rock)
                SKIP_TO_DRAG();
            break;
 
        case 2:
            if (dist2(x, y, uball.ox, uball.oy) === 2
                && dist2(x, y, uchain.ox, uchain.oy) === 4) {
                if (uchain.oy === y)
                    chainx = uball.ox;
                else
                    chainy = uball.oy;
                if (IS_CHAIN_ROCK(chainx, chainy) && !already_in_rock)
                    SKIP_TO_DRAG();
                break;
            }
            // FALLTHROUGH
        case 1:
        case 0:
            if (CHAIN_IN_MIDDLE(uchain.ox, uchain.oy, x, y, uball))
                break;
            if (CHAIN_IN_MIDDLE(u.ux, u.uy, x, y, uball)) {
                chainx = u.ux;
                chainy = u.uy;
                break;
            }
            chainx = x;
            chainy = y;
            break;
 
        default:
            impossible("bad chain movement");
            break;
        }
 
        if (!skip_to_drag) {
            return { result: true, bc_control, ballx, bally, chainx, chainy, cause_delay };
        }
        // fall through to drag
    }
 
    // drag:
    if (near_capacity() > SLT_ENCUMBER && dist2(x, y, u.ux, u.uy) <= 2) {
        await You(`cannot ${game.invent ? "carry all that and also " : ""}drag the heavy iron ball.`);
        nomul(0);
        return { result: false, bc_control, ballx, bally, chainx, chainy, cause_delay };
    }
 
    const chainLoc = levl(uchain.ox, uchain.oy);
    if ((is_pool(uchain.ox, uchain.oy)
         && (chainLoc && chainLoc.typ === POOL
             || !is_pool(uball.ox, uball.oy)
             || (levl(uball.ox, uball.oy) && levl(uball.ox, uball.oy).typ === POOL)))
        || ((t = t_at(uchain.ox, uchain.oy))
            && (is_pit(t.ttyp) || is_hole(t.ttyp)))) {
        if (Levitation()) {
            await You_feel("a tug from the iron ball.");
            if (t) t.tseen = 1;
        } else {
            let victim;
            await You("are jerked back by the iron ball!");
            if ((victim = m_at(uchain.ox, uchain.oy)) !== null) {
                const dieroll = rnd(20);
                let tmp = -2 + (game.u.uluck || 0) + find_mac(victim);
                tmp += omon_adj(victim, uball, true);
                if (tmp >= dieroll)
                    await hmon(victim, uball, HMON_DRAGGED, dieroll);
                else
                    await miss(xname(uball), victim);
            }
            // check again in case mon died
            if (!m_at(uchain.ox, uchain.oy)) {
                u.ux = uchain.ox;
                u.uy = uchain.oy;
                newsym(u.ux0, u.uy0);
            }
            nomul(0);

            bc_control = BC_BALL;
            move_bc(1, bc_control, ballx, bally, chainx, chainy);
            ballx = uchain.ox;
            bally = uchain.oy;
            move_bc(0, bc_control, ballx, bally, chainx, chainy);
            await spoteffects(true);
            return { result: false, bc_control, ballx, bally, chainx, chainy, cause_delay };
        }
    }
 
    bc_control = BC_BALL | BC_CHAIN;
 
    move_bc(1, bc_control, ballx, bally, chainx, chainy);
    if (dist2(x, y, u.ux, u.uy) > 2) {
        // Teleported more than one square — drag both to destination
        ballx = chainx = x;
        bally = chainy = y;
    } else {
        let newchainx = u.ux, newchainy = u.uy;
 
        if (dist2(x, y, uchain.ox, uchain.oy) === 4
            && !IS_CHAIN_ROCK(newchainx, newchainy)) {
            newchainx = Math.trunc((x + uchain.ox) / 2);
            newchainy = Math.trunc((y + uchain.oy) / 2);
            if (IS_CHAIN_ROCK(newchainx, newchainy)) {
                newchainx = u.ux;
                newchainy = u.uy;
            }
        }
 
        ballx = uchain.ox;
        bally = uchain.oy;
        chainx = newchainx;
        chainy = newchainy;
    }
    cause_delay = true;
    return { result: true, bc_control, ballx, bally, chainx, chainy, cause_delay };
}
 
// ── drop_ball ──
// C ref: ball.c:882
export async function drop_ball(x, y) {
    const u = game.u;
    const uball = u.uball;
    const uchain = u.uchain;

    if (Blind()) {
        u.bc_order = bc_order();
        const loc = levl(x, y);
        u.bglyph = u.bc_order ? u.cglyph : (loc ? loc.glyph : -1);
    }

    if (x !== u.ux || y !== u.uy) {
        const pullmsg = "The ball pulls you out of the ";
        let t;
        let side;

        if (u.utrap
            && u.utraptype !== TT_INFLOOR && u.utraptype !== TT_BURIEDBALL) {
            switch (u.utraptype) {
            case TT_PIT:
                await pline(`${pullmsg}pit!`);
                break;
            case TT_WEB:
                await pline(`${pullmsg}web!`);
                Soundeffect(0, 30); // se_destroy_web
                await pline_The("web is destroyed!");
                deltrap(t_at(u.ux, u.uy));
                break;
            case TT_LAVA:
                await pline(`${pullmsg}${hliquid("lava")}!`);
                break;
            case TT_BEARTRAP:
                side = rn2(3) ? LEFT_SIDE : RIGHT_SIDE;
                await pline(`${pullmsg}bear trap!`);
                await set_wounded_legs(side, rn1(1000, 500));
                if (!u.usteed) {
                    await Your(`${side === LEFT_SIDE ? "left" : "right"} ${body_part(LEG)} is severely damaged.`);
                    await losehp(Maybe_Half_Phys(2),
                        "leg damage from being pulled out of a bear trap",
                        KILLED_BY_AN);
                }
                break;
            }
            await reset_utrap(true);
            fill_pit(u.ux, u.uy);
        }

        u.ux0 = u.ux;
        u.uy0 = u.uy;
        if (!Levitation() && !MON_AT(x, y) && !u.utrap
            && (is_pool(x, y)
                || ((t = t_at(x, y))
                    && (is_pit(t.ttyp) || is_hole(t.ttyp))))) {
            u.ux = x;
            u.uy = y;
        } else {
            u.ux = x - u.dx;
            u.uy = y - u.dy;
        }
        game.vision_full_recalc = 1;

        if (Blind()) {
            if (u.bc_felt & BC_CHAIN) {
                const loc = levl(uchain.ox, uchain.oy);
                if (loc) loc.glyph = u.cglyph;
            }
            u.bc_felt = 0;
            const loc = levl(u.ux, u.uy);
            u.cglyph = u.bc_order ? u.bglyph : (loc ? loc.glyph : -1);
        }
        movobj(uchain, u.ux, u.uy);
        if (Blind()) {
            u.bc_order = bc_order();
        }
        newsym(u.ux0, u.uy0);
        if (u.ux0 !== u.ux || u.uy0 !== u.uy) {
            await spoteffects(true);
        }
    }
}
 
// ── litter (static) ──
// C ref: ball.c:964
async function litter() {
    const capacity = weight_cap();
    let otmp = game.invent;
    const uball = game.u.uball;
    while (otmp) {
        const nextobj = otmp.nobj;
        if (otmp !== uball && rnd(capacity) <= (otmp.owt | 0)) {
            if (await canletgo(otmp, "")) {
                await You(`drop ${yname(otmp)} and ${otmp.quan === 1 ? "it" : "they"} ${otense(otmp, "fall")} down the stairs with you.`);
                setnotworn(otmp);
                freeinv(otmp);
                await hitfloor(otmp, false);
            }
        }
        otmp = nextobj;
    }
}
 
// ── drag_down ──
// C ref: ball.c:985
export async function drag_down() {
    const u = game.u;
    const uball = u.uball;
    let dragchance = 3;
 
    const forward = carried(uball) && (u.uwep === uball || !u.uwep || !rn2(3));
 
    if (carried(uball) && !welded(uball))
        await You("lose your grip on the iron ball.");
 
    await cls();
 
    if (forward) {
        if (rn2(6)) {
            await pline_The("iron ball drags you downstairs!");
            await losehp(Maybe_Half_Phys(rnd(6)),
                "dragged downstairs by an iron ball", NO_KILLER_PREFIX);
            await litter();
        }
    } else {
        if (rn2(2)) {
            Soundeffect(0, 25); // se_iron_ball_hits_you
            await pline_The("iron ball smacks into you!");
            await losehp(Maybe_Half_Phys(rnd(20)), "iron ball collision",
                KILLED_BY_AN);
            exercise(A_STR, false);
            dragchance -= 2;
        }
        if (dragchance >= rnd(6)) {
            await pline_The("iron ball drags you downstairs!");
            await losehp(Maybe_Half_Phys(rnd(3)),
                "dragged downstairs by an iron ball", NO_KILLER_PREFIX);
            exercise(A_STR, false);
            await litter();
        }
    }
}
 
// ── bc_sanity_check ──
// C ref: ball.c:1033
export function bc_sanity_check() {
    const u = game.u;
    const uball = u.uball;
    const uchain = u.uchain;

    if (Punished() && (!uball || !uchain)) {
        impossible(`Punished without ${!uball ? "iron ball" : ""}${(!uball && !uchain) ? " and " : ""}${!uchain ? "attached chain" : ""}?`);
    } else if (!Punished() && (uball || uchain)) {
        impossible(`Attached ${uchain ? "chain" : ""}${(uchain && uball) ? " and " : ""}${uball ? "iron ball" : ""} without being Punished?`);
    }

    const freechain = (!uchain || uchain.where === OBJ_FREE);
    const freeball = (!uball || uball.where === OBJ_FREE
        || (freechain && uball.where === OBJ_INVENT));

    if (uball && (uball.otyp !== HEAVY_IRON_BALL
        || (uball.where !== OBJ_FLOOR
            && uball.where !== OBJ_INVENT
            && uball.where !== OBJ_FREE)
        || (freeball !== freechain) // XOR in C: ^ mapped to !==
        || (uball.owornmask & W_BALL) === 0
        || (uball.owornmask & ~(W_BALL | W_WEAPONS)) !== 0)) {
        const otyp = uball.otyp;
        const onam = `otyp ${otyp}`; // TODO: safe_typename when ported
        impossible(`uball: type ${otyp} (${onam}), where ${uball.where}, wornmask=0x${(uball.owornmask >>> 0).toString(16).padStart(8, '0')}`);
    }

    if (uchain && (uchain.otyp !== IRON_CHAIN
        || (uchain.where !== OBJ_FLOOR
            && uchain.where !== OBJ_FREE)
        || (freechain !== freeball)
        || (uchain.owornmask & W_CHAIN) === 0
        || (uchain.owornmask & ~W_CHAIN) !== 0)) {
        const otyp = uchain.otyp;
        const onam = `otyp ${otyp}`; // TODO: safe_typename when ported
        impossible(`uchain: type ${otyp} (${onam}), where ${uchain.where}, wornmask=0x${(uchain.owornmask >>> 0).toString(16).padStart(8, '0')}`);
    }

    if (uball && uchain && !(freeball && freechain)) {
        const cx = uchain.ox, cy = uchain.oy;
        let cdx = cx - u.ux, cdy = cy - u.uy;
        cdx = Math.abs(cdx);
        cdy = Math.abs(cdy);
        let bx, by;
        if (uball.where === OBJ_INVENT) {
            bx = u.ux;
            by = u.uy;
        } else {
            bx = uball.ox;
            by = uball.oy;
        }
        let bdx = bx - cx, bdy = by - cy;
        bdx = Math.abs(bdx);
        bdy = Math.abs(bdy);
        if (cdx > 1 || cdy > 1 || bdx > 1 || bdy > 1)
            impossible(`b&c distance: you@<${u.ux},${u.uy}>, chain@<${cx},${cy}>, ball@<${bx},${by}>`);
    }
}
 
// ── punish: canonical in read.js ──
// C ref: ball.c:punish — full port lives in read.js with seffects().
// Re-exported here for dig.js and other ball.js importers.
export { punish } from './read.js';
 
// ── unpunish: re-exported from read.js ──
 
/*ball.js*/
 
export function init_ball_globals() {
    game.bcrestriction = 0;
}