diff --git a/docs/barrows-tunnels.md b/docs/barrows-tunnels.md new file mode 100644 index 0000000000..f06c8a7e46 --- /dev/null +++ b/docs/barrows-tunnels.md @@ -0,0 +1,91 @@ +# Barrows tunnels and brothers + +How the tunnels, their doors, the brothers and the chest behave, from rsprox captures +(revisions 226-237, [rsprox.net database](https://rsprox.net/database)) and the +[Barrows strategy guide](https://oldschool.runescape.wiki/w/Barrows/Strategies). The plugin is +`server/plugins/minigames/Barrows.plugin.js`; the Prayer drain is in +[barrows-prayer.md](barrows-prayer.md). + +## Doors + +- A click on an open door walks the player to its near side. The next tick is one walk step + through the doorway (no exact move). The step can be diagonal from beside the other leaf, and + ends beyond the leaf that was clicked (227/1000436 tick 10239). +- On the step's tick each leaf becomes `inviswall` (38848) with the leaf's own shape and + rotation. The open leaf (`barrows_door_inactive_l` 20697 / `_r` 20678) is placed on the + wall's outer tile: west, north, east or south of the leaf for rotations 0-3. The left leaf + turns 3 quarters and the right leaf 1 quarter from the door's rotation. Two `synth_sound`s + play: 62, then 41. +- Two ticks later both leaves come back and the open leaves are deleted (236/03929 ticks + 378-380, 227/1000436 ticks 10236-10245, 234/03276). +- The player is not held: a click on the next tick moves them. +- Door varbits 469-484 never change while the player is in the tunnels. +- The chest room's door, still locked: spam "The door is locked with a strange puzzle.", then the + puzzle. A right answer sends "You hear the doors' locking mechanism grind open." and doesn't + cross. The next click does (236/03929 ticks 411-418). + +## Monsters + +- A crossing raises one monster next to the player's new tile on the crossing tick. In 330 + own crossings the monster never waits for the player to stop. + - Live raises only `barrows_rat` 1679, `barrows_bloodworm` 1678 and + `barrows_skeleton_armed` 1687 / `_unarmed` 1685, besides the brothers. + - The Wiki gives the odds: a brother 12/128, then skeleton 52, bloodworm 32 and crypt rat 32. + After the loot, every door raises a remaining brother. + - Ours: the two skeletons are even. + - These monsters persist and roam (227/1000436 #49885, ticks 10236-10710). +- Ours: the monster becomes visible one tick after the step. The world adds queued NPCs on the + next tick. +- The 34 static monsters (`npc-spawns.json`) are separate, as live: low indices present in every + recording, respawning about 21 ticks after death. +- The tunnels are single-way: `multiway_indicator` (4605) is never set there. + +## Brothers + +- The overhead line comes only from a crypt search ("You dare disturb my rest!") or the chest + ("You dare steal from us!"). One raised at a door says nothing (226/01694 tick 9139, 227/00086 + tick 12490). +- A brother's first attack is 3 ticks after he appears. +- **Takeover:** when a brother appears, a crypt monster attacking the player stops facing them, + and it attacks again once he is dead (20 cases, e.g. 227/01885 ticks 12108-12119). The rare + two-attacker tick in 237/04057 (tick 8841) is not reproduced. +- **Leash:** once the player is more than 8 tiles (either axis) from where the brother rose, + his face resets on the next tick and he is deleted the tick after (227/00086 ticks 12498-12500 + and 12507-12509, 227/1000433 ticks 17109-17111). Before that he follows the player through + doors. + - 227/1000433 then shows "We'll finish this later..." and 227/00086 doesn't. Ours: no line in + the tunnels. + - In a crypt the line follows by a tick, per the Wiki's Barrows Trivia ("This message can also + appear if players run too far away from a brother in the crypts"). + - The crypts are too small for the leash: no tile is more than 6 from a crypt's rise tile. +- "We'll finish this later..." also follows: + - a move from a crypt into the tunnels or another crypt with the brother alive, 3 ticks later + (227/1000565 ticks 2829-2832); + - a death (227/1000265 tick 5994). Ours: sent on the death's tick. +- Climbing a crypt's stairs, or teleporting to the surface, removes the brother silently. + +## Chest + +- The loot sends the chest count, jingle 77, one `cam_shake` (0, 5, 0, 0), the reward window, + and closes `barrows_overlay`. +- The Wiki: "Once the chest is looted, the tunnels will shake and start to collapse, causing + occasional damage to the player, and the arrangement of the doors and rooms will shift." The + server re-rolls the layout as the chest is looted. Ours: the collapse hits for 1-4 every 10 ticks + until the player leaves the tunnels; the Wiki gives no numbers. + - **Recorded difference:** 37 loots across 227/01885, 227/1000444, 237/04057, 226/01694, + 227/1000436 and 234/03276 show neither: no damage (one player stayed 135 ticks) and no door + varbit change before leaving. The layout is re-rolled again when the next mound is dug. +- The elite clue goes through Treasure Trails (`treasure-trails:can-receive`, `clue-item`). None + is given when the player can hold no more of the tier. It is a scroll box once X Marks the + Spot unlocks boxes. The Wiki's Scroll box (elite) lists the Barrows chest. + +## Combat Achievements + +| Task | Fails when | Failure line | +| --- | --- | --- | +| Can't Touch Me | A melee brother makes a melee swing, hit or miss (227/00550 tick 28886). The Wiki: "Using Protect from Melee to block damage will not count." | "Dharok the Wretched performed a melee attack." | +| Pray for Success | A brother damages the player (227/00550 tick 29246) | "Ahrim the Blighted damaged you." | +| Faithless Crypt Run | The tick after a brother appears, when the player has had prayer points this run (227/00550 ticks 28262-28263) | "You had more than 0 prayer points." | + +The failure lines go through `combat-achievements:failed`, which applies the player's failure +notification settings. diff --git a/docs/progress/osrs-progress.json b/docs/progress/osrs-progress.json index b922a8d745..878fca64f5 100644 --- a/docs/progress/osrs-progress.json +++ b/docs/progress/osrs-progress.json @@ -21806,7 +21806,8 @@ "devNotes": [ "Implemented end-to-end: the six brothers spawn per-owner in their crypts, region 14231 doors/ladders/chest are derived via RegionBuildingAnalysisUtil, the 3x3 maze randomises one correct puzzle door, and rollRewards (Barrows.plugin.js:455) rolls chest loot from potential + kill count. Prayer drain, strange old lockpick charges and the HUD varps/varbits are wired.", "Likely remaining: no automated check pins the loot table or door layout to OSRS values; re-verify the rollRewards constants against the wiki chest table rather than trusting them.", - "Main 3b61a15a8 (6 November 2026): #2304 Let players cross the West Ardougne wall gate; #2414 Walk through Dragon Slayer's Crandor shortcut wall; #2478 Credit supported Morytania Diary gameplay tasks; #2506 Keep Troll Stronghold's prison door and arena exit shut to locked players; #2534 Implement Ardougne Hard and Elite diary gameplay tasks. Existing completion credit and documented limitations are retained unless explicitly updated below." + "Main 3b61a15a8 (6 November 2026): #2304 Let players cross the West Ardougne wall gate; #2414 Walk through Dragon Slayer's Crandor shortcut wall; #2478 Credit supported Morytania Diary gameplay tasks; #2506 Keep Troll Stronghold's prison door and arena exit shut to locked players; #2534 Implement Ardougne Hard and Elite diary gameplay tasks. Existing completion credit and documented limitations are retained unless explicitly updated below.", + "2026-11-23, branch fix/4407-barrows-alignment (issue #4407): tunnel doors cross in one click with the recorded leaf swap and sounds and raise their monster on the crossing tick; door brothers have no overhead line; brothers chase through the tunnels and leave 8+ tiles from where they rose; a brother takes the player from the crypt monster attacking them, which resumes after he dies; \"We'll finish this later...\" on an unfinished fight; the elite clue follows Treasure Trails (scroll box, capacity); \"Can't Touch Me\" fails on a melee brother's melee swing and the three run tasks send their failure lines. Verified by server/tests/barrows-run.test.cjs and an in-game agent MCP run. Limitations: the crossing monster becomes visible one tick after the step (world add queue); the post-loot collapse damage and layout shift follow the Wiki although 37 captured loots show neither; the leash line's rule in the tunnels and the two skeleton types' odds are Ours (docs/barrows-tunnels.md)." ], "taskDetails": [ { @@ -21860,8 +21861,8 @@ { "name": "Arena mechanics, maze and cleanup", "steps": [ - "Door routing (onObjectRoute) and ForceMovement crossing implement the maze, with randomiseLayout opening all eight outer rooms and exactly one inner puzzle door (Barrows.plugin.js:155, :339).", - "Wrong puzzle answers re-randomise the layout; correct ones set puzzleSolved and cross the door (Barrows.plugin.js:507). Brothers drain Prayer every 30 ticks unless a god hilt is worn; looted tunnels deal collapse damage (Barrows.plugin.js:621).", + "Door routing (onObjectRoute) and a one-step walk through the doorway implement the maze, with randomiseLayout opening all eight outer rooms and exactly one inner puzzle door. A crossing swaps the leaves for an invisible wall and the open leaf for two ticks, with sounds 62 and 41, and raises its monster on the same tick (docs/barrows-tunnels.md).", + "Wrong puzzle answers re-randomise the layout; a correct one sets puzzleSolved and unlocks the door, which the next click crosses. Brothers drain Prayer every 30 ticks unless a god hilt is worn; looting shakes the tunnels, re-rolls the layout and the collapse deals damage until the player leaves (Wiki; 37 captured loots show neither, docs/barrows-tunnels.md).", "removeNpc/cleanupNpcs and processPlayer prune NPCs on plane change, distance, exit and death without leaking queued spawns." ], "acceptanceCriteria": [ diff --git a/server/plugins/minigames/Barrows.plugin.js b/server/plugins/minigames/Barrows.plugin.js index d5fbaaaab5..f7ec566a48 100644 --- a/server/plugins/minigames/Barrows.plugin.js +++ b/server/plugins/minigames/Barrows.plugin.js @@ -12,10 +12,37 @@ const { CacheDefinitions } = require("../../src/main/typescript/elvarg/game/cach const { GameObject } = require("../../src/main/typescript/elvarg/game/entity/impl/object/GameObject"); const { Skill } = require("../../src/main/typescript/elvarg/game/model/Skill"); const { Equipment } = require("../../src/main/typescript/elvarg/game/model/container/impl/Equipment"); -const { HitDamage } = require("../../src/main/typescript/elvarg/game/content/combat/hit/HitDamage"); -const { HitMask } = require("../../src/main/typescript/elvarg/game/content/combat/hit/HitMask"); /** A door's crossing is a walk through its doorway (236/03929): clipping is ignored for that step. */ const IGNORE_CLIPPING_FLAG = "movement:ignore-clipping"; +/** + * The crossing's tick swaps each leaf for an invisible wall and puts the open (inactive) leaf on the + * wall's outer tile, with two sounds; two ticks later the leaves are back (234/03276, 227/1000436 + * ticks 10236-10241 and 10243-10245, 236/03929 ticks 378-380). The player is not held. + */ +const DOOR_OPEN_TICKS = 2; +const DOOR_OPEN_SOUNDS = [62, 41]; +const DOOR_INVISWALL = "inviswall"; +const DOOR_INACTIVE = { l: "barrows_door_inactive_l", r: "barrows_door_inactive_r" }; +/** The chest-room door's puzzle (236/03929 ticks 415 and 417): a solve opens it, another click crosses. */ +const PUZZLE_LOCKED = "The door is locked with a strange puzzle."; +const PUZZLE_SOLVED = "You hear the doors' locking mechanism grind open."; +/** ... with this sound (all six recorded solves: 236/03929 tick 417, 227/01885 tick 12722, 234/03276 ...). */ +const PUZZLE_SOLVED_SOUND = 37; +/** + * A brother gives up once the player is more than this many tiles (either axis) from where he rose: + * his face resets, then he goes the tick after (227/00086 ticks 12498-12500 and 12507-12509, + * 227/1000433 ticks 17109-17111). + */ +const BROTHER_LEASH = 8; +/** "We'll finish this later..." (227/1000565 tick 2832, 227/1000444 tick 33710, 227/1000265 tick 5994). */ +const BROTHER_FAREWELL = "We'll finish this later..."; +/** The line follows a move into the tunnels or another crypt by three ticks (1000565 ticks 2829-2832). */ +const FAREWELL_MOVE_TICKS = 3; +/** ... and a leash despawn by one (1000433 ticks 17111-17112). */ +const FAREWELL_LEASH_TICKS = 1; +/** The brothers chase their target through the tunnels; the leash above is theirs, not the open-world one. */ +const NO_RETREAT_FLAG = "combat:no-retreat"; +const KEEP_TARGET_FLAG = "combat:keep-target"; const { MagicCombatMethod } = require("../../src/main/typescript/elvarg/game/content/combat/method/impl/MagicCombatMethod"); const { CombatSpells } = require("../../src/main/typescript/elvarg/game/content/combat/magic/CombatSpells"); const { MOBILE_CLIENT_ATTRIBUTE } = require("../../src/main/typescript/elvarg/net/protocol/ClientProtocol"); @@ -51,8 +78,17 @@ const CLOSE_INTERFACE_ATTRIBUTE = "interface:close-on-interface-close"; const POTENTIAL_VARBIT = 463; const KILL_COUNT_VARBIT = 464; const CHEST_OPEN_VARBIT = 1394; -/** The tunnels shake (slot, random amplitude) from the looting until the player leaves them. */ +/** + * The tunnels shake (slot, random amplitude) from the looting until the player leaves them. The Wiki + * (Barrows/Strategies): "Once the chest is looted, the tunnels will shake and start to collapse, + * causing occasional damage to the player, and the arrangement of the doors and rooms will shift." + * Recorded difference: 37 loots (227/01885, 227/1000444, 237/04057, 226/01694, 227/1000436, 234/03276) + * show neither the damage nor a door change before leaving. + */ const LOOTED_SHAKE = [0, 5, 0, 0]; +/** Ours: the collapse's "occasional damage" is 1-4 every 10 ticks; the Wiki gives no numbers. */ +const COLLAPSE_TICKS = 10; +const COLLAPSE_DAMAGE = [1, 4]; const LADDER_VISIBLE_VARBIT = 4743; const PRAYER_DRAIN_TICKS = 30; const MINIMAP_STATE_VARBIT = 6719; @@ -222,7 +258,7 @@ function syncMinimap(player, phase) { function session(player) { let value = sessions.get(player); if (!value) { - value = { npcs: new Set(), brother: null, phase: "outside", puzzle: null, dig: null, crossing: null }; + value = { npcs: new Set(), brother: null, phase: "outside", puzzle: null, dig: null, crossing: null, farewell: 0 }; sessions.set(player, value); } return value; @@ -343,27 +379,62 @@ function cleanupNpcs(player, keepDying = false) { } } +/** A live brother, not yet dying: one whose removal ends an unfinished fight. */ +function liveBrother(state) { + const npc = state.brother; + return npc && !npc.isDyingFunction() && npc.getHitpoints() > 0 ? npc : null; +} + +/** The brother's "We'll finish this later..." once `ticks` have passed (processPlayer). */ +function queueFarewell(state, ticks) { + state.farewell = ticks; +} + +/** + * A brother takes the player from the crypt monster fighting them: that monster stops facing them + * the tick he appears, and attacks again once he is dead (20 cases, e.g. 227/01885 ticks 12108-12119, + * 227/1000265 tick 6463). The tunnels are single-way (multiway_indicator is never set there), so the + * monster's hold on the player is released for him. + */ +function takeOver(player, brother) { + for (const npc of session(player).npcs) { + if (npc === brother || npc.getCombat().getTarget() !== player) continue; + npc.getCombat().reset(); + player.getCombat().clearAttackerIf(npc); + npc.__barrowsResume = true; + } +} + function onNpcAdded() { NPC.prototype.onAdd.call(this); const player = this.getOwner(); if (session(player).brother === this) { - // A brother woken in his crypt, or the tunnel's brother rising at the chest (rsprox_transcripts/227/00086.txt:233215, - // and 546 times over the recordings). - this.forceChat(this.__barrowsChest ? "You dare steal from us!" : "You dare disturb my rest!"); + // A brother woken in his crypt says "You dare disturb my rest!", the tunnel's brother rising at the chest + // "You dare steal from us!" (rsprox_transcripts/227/00086.txt:233215, and 546 times over the recordings); + // one met at a tunnel door says nothing (226/01694 tick 9139, 227/00086 tick 12490). + if (this.__barrowsLine) this.forceChat(this.__barrowsLine); + // His first attack is three ticks after he appears (226/01694 ticks 8804-8807, 227/00550 ticks 27406-27409). this.getTimers().extendOrRegister(TimerKey.COMBAT_ATTACK, 3); player.getPacketSender().sendEntityHint(this); + takeOver(player, this); } this.getCombat().attack(player); } -function spawnNpc(player, npcId, location, brother = false) { +function spawnNpc(player, npcId, location, brother = false, line = null) { const npc = new NPC(npcId, location.clone()); npc.setOwner(player); npc.__skipDefaultRespawn = true; npc.onAdd = onNpcAdded; const state = session(player); state.npcs.add(npc); - if (brother) state.brother = npc; + if (brother) { + state.brother = npc; + npc.__barrowsLine = line; + npc.__barrowsRose = location.clone(); + npc.setFlag(NO_RETREAT_FLAG, true); + npc.setFlag(KEEP_TARGET_FLAG, true); + } World.getAddNPCQueue().push(npc); return npc; } @@ -416,6 +487,9 @@ function refuseMoundDig(request) { function enterTunnel(player, run, brother) { if (getRun(player) !== run || player.getLocation().getZ() !== 3 || player.getLocation().getDistance(brother.crypt) > 10) return; + const state = session(player); + // An unfinished crypt fight ends with his line (227/1000565 ticks 2829-2832). + if (liveBrother(state)) queueFarewell(state, FAREWELL_MOVE_TICKS); cleanupNpcs(player, true); player.getPacketSender().sendInterfaceRemoval(); const ladder = getTunnelMap().ladders.find((object) => roomAt(new Location(object.x, object.y)) === run.exitRoom); @@ -447,7 +521,7 @@ function searchCrypt(player, index) { } else { // rsprox_transcripts/226/01694.txt:165522 (then the brother's "You dare disturb my rest!" at :165530). spam(player, "You don't find anything."); - spawnNpc(player, brother.npcId, brother.spawn, true); + spawnNpc(player, brother.npcId, brother.spawn, true, "You dare disturb my rest!"); } } @@ -544,31 +618,96 @@ function useLockpickOnDoor(event) { return true; } +/** A doorway's two leaves: the door and its neighbour on the same varbit. */ +function doorLeaves(door) { + return getTunnelMap().doors.filter((entry) => entry.varbit === door.varbit && + Math.abs(entry.x - door.x) + Math.abs(entry.y - door.y) <= 1); +} + +/** The tile beyond the leaf's wall edge (the west, north, east or south one). */ +function outerTile(leaf) { + const { x, y, orientation } = leaf; + if (orientation === 0) return new Location(x - 1, y); + if (orientation === 1) return new Location(x, y + 1); + if (orientation === 2) return new Location(x + 1, y); + return new Location(x, y - 1); +} + +/** + * The open leaf a crossing shows: on the wall's outer tile, the left one turned three quarters and + * the right one a quarter from the door (1000436: barrows_door_l_r rotation 3 -> inactive_r 0 at + * tick 10239, barrows_door_n_l rotation 2 -> inactive_l 1 at tick 10243). + */ +function openLeaf(leaf) { + const side = /_r$/.test(CacheDefinitions.getLocNames().get(leaf.id) ?? "") ? "r" : "l"; + const rotation = (leaf.orientation + (side === "l" ? 3 : 1)) % 4; + return new GameObject(CacheDefinitions.getLocId(DOOR_INACTIVE[side]), outerTile(leaf), leaf.type, rotation, null); +} + +/** Which way the player stands at a doorway: the index into either leaf's doorSides, or -1. */ +function doorwaySide(leaves, location) { + for (const leaf of leaves) { + const index = doorSides(leaf).findIndex((side) => side.equals(location)); + if (index !== -1) return index; + } + return -1; +} + +/** The crossing's two ticks are up (or another door is opened first): the leaves are back. */ +function shutDoor(player, crossing) { + const sender = player.getPacketSender(); + crossing.leaves.forEach((leaf, i) => { + sender.sendObject(asObject(leaf)); + sender.sendObjectRemoval(crossing.opened[i]); + }); +} + +function endCrossing(player, state, phase = phaseOf(player)) { + const crossing = state.crossing; + if (!crossing) return; + state.crossing = null; + player.removeFlag(IGNORE_CLIPPING_FLAG); + if (phase === "tunnels") shutDoor(player, crossing); +} + function crossDoor(player, door) { const state = session(player); - if (state.crossing || player.getForceMovement()) return; - const sides = doorSides(door); - const from = player.getLocation(); - const index = sides.findIndex((side) => side.equals(from)); + if (player.getForceMovement()) return; + const leaves = doorLeaves(door); + const from = player.getLocation().clone(); + // From either leaf's tile: live steps diagonally past the other leaf to the tile beyond the one + // clicked (227/1000436 tick 10239: (3552,9684) -> (3551,9683) for barrows_door_l_r at 3551,9684). + const index = doorwaySide(leaves, from); if (index === -1) return; - const to = sides[1 - index]; - const leaves = getTunnelMap().doors.filter((entry) => entry.varbit === door.varbit && - Math.abs(entry.x - door.x) + Math.abs(entry.y - door.y) <= 1); - for (const leaf of leaves) player.getPacketSender().sendObjectRemoval(asObject(leaf)); - state.crossing = { leaves, to, ticks: 3 }; + const to = doorSides(door)[1 - index]; + // Clicked again before the step through it: one crossing, one monster. + const pending = state.crossing; + if (pending && pending.from.equals(from) && pending.leaves.includes(door)) return; + endCrossing(player, state); + const sender = player.getPacketSender(); + const inviswall = CacheDefinitions.getLocId(DOOR_INVISWALL); + const opened = leaves.map(openLeaf); + leaves.forEach((leaf, i) => { + sender.sendObject(new GameObject(inviswall, new Location(leaf.x, leaf.y, leaf.z), leaf.type, leaf.orientation, null)); + sender.sendObject(opened[i]); + }); + for (const sound of DOOR_OPEN_SOUNDS) sender.sendSoundEffect(sound, 1, 0); + state.crossing = { leaves, opened, from, to, ticks: DOOR_OPEN_TICKS }; // Live walks through the doorway as the door opens (rsprox_transcripts/236/03929.txt: a // walk/run step across barrows_door_o_l at 3562,9678, no exact move), not a slide. player.setFlag(IGNORE_CLIPPING_FLAG, true); const movement = player.getMovementQueue(); movement.reset(); movement.addSteps(to.clone()); + // The monster rises beside the player on the crossing's own tick, whatever they click next + // (330 crossings: 236/03929 tick 378, 227/1000436 ticks 10236, 10239, 10243). + spawnEncounter(player, roomAt(to), to); } function useDoor(player, door, lockpick = null) { - const state = session(player); - if (state.crossing || player.getForceMovement()) return; + if (player.getForceMovement()) return; const run = getRun(player); - if (!doorSides(door).some((side) => side.equals(player.getLocation()))) return; + if (doorwaySide(doorLeaves(door), player.getLocation()) === -1) return; const centre = DOOR_LINKS.find(([id]) => id === door.varbit).slice(1).includes(4); const picked = (run.pickedDoors ?? []).includes(door.varbit); if (!run.openDoors.includes(door.varbit) && !picked) { @@ -578,6 +717,7 @@ function useDoor(player, door, lockpick = null) { } } else if (centre && !picked && !run.puzzleSolved && roomAt(player.getLocation()) !== 4 && !run.looted) { if (!pickLock(player, run, door, lockpick)) { + spam(player, PUZZLE_LOCKED); showPuzzle(player, door); return; } @@ -585,7 +725,12 @@ function useDoor(player, door, lockpick = null) { crossDoor(player, door); } -function spawnEncounter(player, room) { +/** + * A crossing's monster, beside the tile it leads to (`arrival`). Live's crossings raise only crypt + * rats, bloodworms, and armed and unarmed skeletons (barrows_skeleton_armed 1687, _unarmed 1685), + * besides a brother; the Wiki gives the odds. Ours: the two skeletons are even. + */ +function spawnEncounter(player, room, arrival = player.getLocation()) { if (room < 0) return; const state = session(player); const run = getRun(player); @@ -595,10 +740,10 @@ function spawnEncounter(player, room) { const brother = !state.brother && remaining.length && (run.looted || roll < 12) ? remaining[randomInt(0, remaining.length - 1)] : -1; if (run.looted && brother === -1) return; - const id = brother !== -1 ? BROTHERS[brother].npcId : roll < 64 ? Npcs.SKELETON_17 : roll < 96 ? Npcs.BLOODWORM : Npcs.CRYPT_RAT; + const skeleton = randomInt(0, 1) === 0 ? Npcs.SKELETON_19 : Npcs.SKELETON_17; + const id = brother !== -1 ? BROTHERS[brother].npcId : roll < 64 ? skeleton : roll < 96 ? Npcs.BLOODWORM : Npcs.CRYPT_RAT; // Room bounds overlap the doorway/corridor. An empty tile near the room centre may be // behind the door, so spawn beside the arrival tile and check the actual wall clipping. - const arrival = player.getLocation(); const area = player.getPrivateArea(); for (const [dx, dy] of shuffled([[0, 1], [1, 0], [0, -1], [-1, 0]])) { const location = new Location(arrival.getX() + dx, arrival.getY() + dy, arrival.getZ()); @@ -691,6 +836,23 @@ function chestBoost(player) { }; } +/** + * The chest's elite clue as Treasure Trails hands it out: none while the player can hold no more + * of the tier, and a scroll box once boxes are unlocked (X Marks the Spot). The Wiki's Scroll box + * (elite) lists the Barrows chest as a source. + */ +function eliteClueForm(player, rewards) { + const clue = rewards.find((item) => item.getId() === Items.CLUE_SCROLL_ELITE_); + if (!clue) return rewards; + const allowed = { player, tier: "elite", allowed: null }; + pluginApi.emitCustomEvent("treasure-trails:can-receive", allowed); + if (allowed.allowed === false) return rewards.filter((item) => item !== clue); + const form = { player, itemId: clue.getId(), box: false }; + pluginApi.emitCustomEvent("treasure-trails:clue-item", form); + clue.setId(form.itemId); + return rewards; +} + function showRewards(player, rewards) { player.setAttribute(CLOSE_INTERFACE_ATTRIBUTE, REWARDS_ID); const sender = player.getPacketSender(); @@ -733,8 +895,10 @@ function answerPuzzle(event) { player.sendMessage("Wrong! The passages shift around you."); return; } + // Solved, the door is unlocked: the next click on it crosses (236/03929 ticks 417-418). pending.run.puzzleSolved = true; - crossDoor(player, pending.door); + player.sendMessage(PUZZLE_SOLVED); + player.getPacketSender().sendSoundEffect(PUZZLE_SOLVED_SOUND, 1, 0); } function searchChest(player, clickType) { @@ -756,13 +920,13 @@ function searchChest(player, clickType) { sender.sendSoundEffect(CHEST_OPEN_SOUND, 1, 0); sender.sendVarbit(CHEST_OPEN_VARBIT, 1); if (!run.killed.includes(run.tunnel) && !state.brother) { - spawnNpc(player, BROTHERS[run.tunnel].npcId, new Location(3550, 9694), true).__barrowsChest = true; + spawnNpc(player, BROTHERS[run.tunnel].npcId, new Location(3550, 9694), true, "You dare steal from us!"); } return; } const diary = { player, diary: "morytania", tier: "hard", complete: false }; pluginApi.emitCustomEvent("diary:is-complete", diary); - const rewards = rollRewards(run, diary.complete === true, chestBoost(player)); + const rewards = eliteClueForm(player, rollRewards(run, diary.complete === true, chestBoost(player))); // Other plugins' items join the loot, in its window (His Faithful Servants' strange icon comes // first: BarrowsMiniQuest.bin tick 885, trail_rewardinv's slot 0). pluginApi.emitCustomEvent("barrows:chest-rewards", { player, run, rewards }); @@ -772,6 +936,7 @@ function searchChest(player, clickType) { player.getInventory().forceAdd(player, item); pluginApi.emitCustomEvent("collection-log:obtain", { player, itemId: item.getId(), amount: item.getAmount() }); } + // The Wiki's "the arrangement of the doors and rooms will shift" (see LOOTED_SHAKE). randomiseLayout(run); syncTunnels(player, run); pluginApi.emitCustomEvent("barrows:chest-looted", { player }); @@ -808,14 +973,49 @@ function combatAchievementsAtChest(player, run) { if ([...MELEE_BROTHERS].every((index) => run.killed.includes(index)) && !run.meleeBrotherAttacked) complete("Can't Touch Me"); } -/** A brother's hit on the player, for the run's tasks. */ -function trackBrotherHit({ attacker, target, hit }) { - if (!target?.isPlayer?.() || !attacker?.isNpc?.()) return; +/** "You have failed : " (227/00550 ticks 28886, 29246, 28263), as the player's settings allow. */ +function failTask(player, task, reason) { + pluginApi.emitCustomEvent("combat-achievements:failed", { player, task, reason }); +} + +/** The brother attacking `target` and the target's unlooted run, or null. */ +function brotherAttack(attacker, target) { + if (!target?.isPlayer?.() || !attacker?.isNpc?.()) return null; const index = BROTHERS.findIndex((brother) => brother.npcId === attacker.getId()); const run = index === -1 ? null : target.getAttribute(ATTRIBUTE); - if (!run || run.looted) return; - if (hit.getTotalDamage() > 0) run.brotherDamage = true; - if (MELEE_BROTHERS.has(index) && String(hit.getCombatType?.()) === "MELEE") run.meleeBrotherAttacked = true; + return run && !run.looted ? { index, run, name: attacker.getDefinition().getName() } : null; +} + +/** + * A melee brother's melee swing fails "Can't Touch Me" as it is made, hit or miss: "Using Protect + * from Melee to block damage will not count" (Wiki). 227/00550 tick 28886: "Dharok the Wretched + * performed a melee attack." on the swing's tick, for a 0. + */ +function trackBrotherAttack({ attacker, target, combatType }) { + const attack = brotherAttack(attacker, target); + if (!attack || !MELEE_BROTHERS.has(attack.index) || combatType !== pluginApi.core.CombatType.MELEE) return; + if (attack.run.meleeBrotherAttacked) return; + attack.run.meleeBrotherAttacked = true; + failTask(target, "Can't Touch Me", `${attack.name} performed a melee attack.`); +} + +/** A brother's damage fails "Pray for Success" (227/00550 tick 29246, the tick after Ahrim's 15). */ +function trackBrotherHit({ attacker, target, hit }) { + const attack = brotherAttack(attacker, target); + if (!attack || hit.getTotalDamage() <= 0 || attack.run.brotherDamage) return; + attack.run.brotherDamage = true; + failTask(target, "Pray for Success", `${attack.name} damaged you.`); +} + +/** + * "Faithless Crypt Run" fails the tick after a brother appears to a player who has had prayer + * points this run (227/00550 ticks 28262-28263 and 28974-28975). + */ +function checkFaithless(player, state, run) { + const brother = liveBrother(state); + if (!brother || !brother.isRegistered() || brother.__faithlessChecked || run.looted) return; + brother.__faithlessChecked = true; + if (run.hadPrayer) failTask(player, "Faithless Crypt Run", "You had more than 0 prayer points."); } function answerKillCount({ player, counts }) { @@ -955,27 +1155,64 @@ function processPlayer({ player }) { if (phase === "tunnels") syncTunnels(player, getRun(player)); } } - if (state.crossing && --state.crossing.ticks <= 0) { - const crossing = state.crossing; - state.crossing = null; - player.removeFlag(IGNORE_CLIPPING_FLAG); - if (phase === "tunnels") { - for (const leaf of crossing.leaves) player.getPacketSender().sendObject(asObject(leaf)); - if (player.getLocation().equals(crossing.to)) spawnEncounter(player, roomAt(crossing.to)); - } - } - if (phase === "crypt" || phase === "tunnels") { - if (player.getHitpoints() > 0) drainPrayer(player, getRun(player)); - if (phase === "tunnels" && getRun(player).looted && World.getProcessCycle() % 10 === 0) { - player.getCombat().getHitQueue().addPendingDamage([new HitDamage(randomInt(1, 4), HitMask.RED)]); - } + if (state.crossing) { + // The doorway's clipping is ignored for the step through it only; a click away the next tick + // walks normally (the player is not held: 227/1000436 ticks 10237 and 10240). + if (!player.getLocation().equals(state.crossing.from)) player.removeFlag(IGNORE_CLIPPING_FLAG); + if (--state.crossing.ticks <= 0) endCrossing(player, state, phase); } + if ((phase === "crypt" || phase === "tunnels") && player.getHitpoints() > 0) drainPrayer(player, getRun(player)); + if (phase === "tunnels" && run?.looted && player.getHitpoints() > 0) collapse(player); for (const npc of [...state.npcs]) { // Let a fatal hit finish crediting its owner even if they climb out on the same tick. if (npc.isDyingFunction()) continue; if (phase === "outside" || phase === "surface" || npc.getLocation().getZ() !== player.getLocation().getZ() || - npc.getLocation().getDistance(player.getLocation()) >= 40) removeNpc(player, npc); + npc.getLocation().getDistance(player.getLocation()) >= 40) { + // A brother left behind by a move to another crypt or into the tunnels (a teleport) says his line. + if (npc === liveBrother(state) && (phase === "crypt" || phase === "tunnels")) queueFarewell(state, FAREWELL_MOVE_TICKS); + removeNpc(player, npc); + } else if (npc === state.brother) leashBrother(player, state, npc, phase); + else if (npc.__barrowsResume && !liveBrother(state) && npc.isRegistered()) { + // The monster a brother took the player from attacks again once he is gone (227/01885 tick 12119). + npc.__barrowsResume = false; + if (npc.getCombat().getTarget() == null) npc.getCombat().attack(player); + } + } + if (run) checkFaithless(player, state, run); + if (state.farewell > 0 && --state.farewell === 0 && phase !== "outside" && phase !== "surface") player.sendMessage(BROTHER_FAREWELL); +} + +/** The looted tunnels' collapse: the Wiki's "occasional damage to the player" (see LOOTED_SHAKE). */ +function collapse(player) { + if (World.getProcessCycle() % COLLAPSE_TICKS !== 0) return; + const { HitDamage, HitMask } = pluginApi.core; + player.getCombat().getHitQueue().addPendingDamage([new HitDamage(randomInt(...COLLAPSE_DAMAGE), HitMask.RED)]); +} + +/** + * A brother out of reach of where he rose turns away, then goes the tick after; in a crypt with his + * line (the Wiki's Barrows Trivia: the message "can also appear if players run too far away from a + * brother in the crypts"; 227/1000433 tick 17112 has it in the tunnels, 227/00086 twice without). + * Otherwise he keeps after his owner: a brother whose attack the single-way rules refused tries again. + */ +function leashBrother(player, state, npc, phase) { + if (!npc.isRegistered()) return; + const here = player.getLocation(); + const rose = npc.__barrowsRose ?? npc.getSpawnPosition(); + const away = Math.max(Math.abs(here.getX() - rose.getX()), Math.abs(here.getY() - rose.getY())) > BROTHER_LEASH; + if (!away) { + npc.__barrowsLeaving = false; + if (npc.getCombat().getTarget() == null) npc.getCombat().attack(player); + return; + } + if (!npc.__barrowsLeaving) { + npc.__barrowsLeaving = true; + npc.getCombat().reset(); + npc.setMobileInteraction(null); + return; } + if (phase === "crypt") queueFarewell(state, FAREWELL_LEASH_TICKS); + removeNpc(player, npc); } function cleanupPlayer({ player }) { @@ -1011,7 +1248,11 @@ function crumbleKeptLockpicksOnDeath({ victim: player }) { } function playerDeath(event) { + // A death mid-fight: the brother goes, with his line (227/1000265 ticks 5993-5994, 227/1000565). + // Ours: on the death's tick, as the session ends with it. + const fighting = sessions.has(event.player) && liveBrother(session(event.player)); cleanupPlayer(event); + if (fighting) event.player.sendMessage(BROTHER_FAREWELL); const run = event.player.getAttribute(ATTRIBUTE); if (run?.looted) event.player.setAttribute(ATTRIBUTE, freshRun(run.chests)); } @@ -1119,6 +1360,7 @@ module.exports = { api.onNpcDeath(handleNpcDeath); api.onCustomEvent("collection-log:category-count", chestCount); api.onCustomEvent("combat-achievements:kill-count", answerKillCount); + api.onCombatHitPrepare(trackBrotherAttack); api.onCombatHitResolved(trackBrotherHit); api.onPlayerProcess(processPlayer); api.onPlayerDeath(playerDeath); @@ -1129,5 +1371,6 @@ module.exports = { api.registerNpcCombatMethodProvider(Npcs.AHRIM_THE_BLIGHTED, AhrimCombat); }, _test: { rollRewards, searchChest, searchCrypt, chestCount, phaseOf, syncMinimap, processPlayer, dig, useDoor, doorSides, getTunnelMap, getRun, IGNORE_CLIPPING_FLAG, + answerPuzzle, enterTunnel, doorLeaves, session, trackBrotherAttack, trackBrotherHit, BROTHERS, roomAt, useLockpickOnDoor, inspectLockpick, refuseMoundDig, WARNINGS_ATTRIBUTE, playerDeath, crumbleWarnedLockpickOnDeath, crumbleKeptLockpicksOnDeath }, }; diff --git a/server/tests/barrows-run.test.cjs b/server/tests/barrows-run.test.cjs index cadb633763..18bb2e3797 100644 --- a/server/tests/barrows-run.test.cjs +++ b/server/tests/barrows-run.test.cjs @@ -715,3 +715,359 @@ test("Barrows: a plugin can refuse a mound's Spade dig before it starts; off the assert.equal(eastfloor.refused, false); assert.equal(asked, 1, "asked only for a brother's mound"); }); + +// ------------------------------------------------------------------ Issue #4407: live alignment +// rsprox captures 234/03276, 227/1000436 (ticks 10236-10245), 236/03929 (ticks 378-380 and 411-418), +// 227/00086, 227/1000433, 227/00550, 227/1000565 and 227/1000265. + +/** An open hallway's door this run (not the chest room's) and the tiles either side of it. */ +function openDoor(subject) { + const { getTunnelMap, getRun, doorSides, doorLeaves } = Barrows._test; + arrive(subject, CHEST_ROOM); + const run = getRun(subject); + const door = getTunnelMap().doors.find((entry) => run.openDoors.includes(entry.varbit) && entry.varbit !== run.puzzleDoor); + const [near, far] = doorSides(door); + const other = doorLeaves(door).find((leaf) => leaf !== door); + return { run, door, near, far, other }; +} + +const objectCalls = (subject, key) => subject.sent.calls.filter(([name]) => name === key) + .map(([, object]) => [object.getId(), object.getLocation().getX(), object.getLocation().getY(), object.getType(), object.getFace()]); +const queuedSince = (before) => core.World.getAddNPCQueue().slice(before); + +test("Barrows: a door crossing swaps the leaves, sounds and raises its monster on its own tick; the leaves are back two ticks later", () => { + const subject = player(); + const { door, near, far } = openDoor(subject); + const { useDoor, processPlayer, doorLeaves, IGNORE_CLIPPING_FLAG } = Barrows._test; + subject.setLocation(near.clone()); + processPlayer({ player: subject }); + subject.sent.calls.length = 0; + const queue = core.World.getAddNPCQueue(); + const before = queue.length; + try { + useDoor(subject, door); + useDoor(subject, door); // clicked again before the step: still one crossing + const leaves = doorLeaves(door); + const inviswall = core.CacheDefinitions.getLocId("inviswall"); + const names = core.CacheDefinitions.getLocNames(); + const added = objectCalls(subject, "sendObject"); + assert.equal(added.length, 4, "an invisible wall and an open leaf for each of the two leaves"); + for (const leaf of leaves) { + assert.ok(added.some(([id, x, y, , face]) => id === inviswall && x === leaf.x && y === leaf.y && face === leaf.orientation), + `inviswall on ${leaf.x},${leaf.y}`); + } + const inactive = added.filter(([id]) => id !== inviswall).map(([id]) => names.get(id)).sort(); + assert.deepEqual(inactive, ["barrows_door_inactive_l", "barrows_door_inactive_r"]); + const sounds = subject.sent.calls.filter(([key]) => key === "sendSoundEffect").map(([, id]) => id); + assert.deepEqual(sounds, [62, 41]); + assert.equal(objectCalls(subject, "sendObjectRemoval").length, 0, "the leaves are swapped, not removed"); + assert.equal(queue.length, before + 1, "the monster rises with the crossing"); + const monster = queue.at(-1); + assert.ok(monster.getLocation().getDistance(far) <= 1, `beside the far tile (${monster.getLocation()})`); + assert.ok([1678, 1679, 1685, 1687].includes(monster.getId()) || Barrows._test.BROTHERS.some((b) => b.npcId === monster.getId()), String(monster.getId())); + + // The step, then a click away on the next tick: the player is not held and nothing more spawns. + subject.getMovementQueue().process(); + assert.ok(subject.getLocation().equals(far), `crossed (${subject.getLocation()})`); + processPlayer({ player: subject }); + assert.equal(subject.hasFlag(IGNORE_CLIPPING_FLAG), false, "the doorway's clipping only for its step"); + subject.sent.calls.length = 0; + processPlayer({ player: subject }); + const restored = objectCalls(subject, "sendObject"); + assert.deepEqual(restored.map(([id]) => id).sort(), leaves.map((leaf) => leaf.id).sort(), "the leaves are back on the second tick"); + assert.equal(objectCalls(subject, "sendObjectRemoval").length, 2, "and the open leaves are gone"); + assert.equal(queue.length, before + 1, "one monster per crossing"); + } finally { + queue.length = before; + } +}); + +test("Barrows: a doorway is crossed in one click from beside the other leaf, diagonally (1000436 tick 10239)", () => { + const subject = player(); + const { door, other } = openDoor(subject); + const { useDoor, processPlayer, doorSides } = Barrows._test; + const queue = core.World.getAddNPCQueue(); + const before = queue.length; + try { + const [otherNear] = doorSides(other); + const [, far] = doorSides(door); + subject.setLocation(otherNear.clone()); + processPlayer({ player: subject }); + useDoor(subject, door); + subject.getMovementQueue().process(); + assert.ok(subject.getLocation().equals(far), `beyond the clicked leaf (${subject.getLocation()} vs ${far})`); + } finally { + queue.length = before; + } +}); + +test("Barrows: the chest room's door says it is puzzle-locked; a solve unlocks it, and the next click crosses", () => { + const subject = player(); + const { getTunnelMap, getRun, doorSides, useDoor, answerPuzzle, processPlayer, session } = Barrows._test; + arrive(subject, CHEST_ROOM); + const run = getRun(subject); + // A leaf of the chest room's hallway, from a side outside the chest room (room 4, the centre): there + // the door is puzzle-locked. Room bounds overlap the corridors, so it is the room, not a distance. + const { roomAt } = Barrows._test; + const [door, outside] = getTunnelMap().doors.filter((entry) => entry.varbit === run.puzzleDoor) + .flatMap((entry) => doorSides(entry).map((side) => [entry, side])) + .find(([, side]) => roomAt(side) !== 4); + assert.ok(door, "a puzzle door side outside the chest room"); + subject.setLocation(outside.clone()); + processPlayer({ player: subject }); + useDoor(subject, door); + assert.ok(subject.sent.spam.includes("The door is locked with a strange puzzle."), subject.sent.spam.join(" | ")); + const pending = session(subject).puzzle; + assert.ok(pending, "the puzzle is open"); + const slot = pending.options.indexOf(0); + const queue = core.World.getAddNPCQueue(); + const before = queue.length; + try { + subject.sent.calls.length = 0; + answerPuzzle({ player: subject, buttonId: (25 << 16) | [12, 14, 16][slot] }); + assert.ok(subject.sent.messages.includes("You hear the doors' locking mechanism grind open."), subject.sent.messages.join(" | ")); + assert.deepEqual(subject.sent.calls.filter(([key]) => key === "sendSoundEffect").map(([, id]) => id), [37], "with sound 37"); + assert.equal(session(subject).crossing, null, "solving it does not cross"); + assert.ok(subject.getLocation().equals(outside)); + useDoor(subject, door); + assert.ok(session(subject).crossing, "the next click crosses"); + } finally { + queue.length = before; + } +}); + +test("Barrows: a brother met at a tunnel door says nothing; one woken in his crypt or at the chest has his line", () => { + const subject = player(); + const { door, near } = openDoor(subject); + const { useDoor, processPlayer } = Barrows._test; + subject.setLocation(near.clone()); + processPlayer({ player: subject }); + const queue = core.World.getAddNPCQueue(); + const before = queue.length; + const random = Math.random; + Math.random = () => 0; // the encounter roll is a brother + try { + useDoor(subject, door); + } finally { + Math.random = random; + } + try { + const brother = queue.at(-1); + assert.ok(Barrows._test.BROTHERS.some((b) => b.npcId === brother.getId()), "a brother rose at the door"); + const said = []; + brother.forceChat = (text) => { said.push(text); return brother; }; + try { brother.onAdd(); } catch { /* the fixture world's combat wiring */ } + assert.deepEqual(said, []); + } finally { + queue.length = before; + } +}); + +/** A brother of the player's in the tunnels, registered, his rise tile `rose`. */ +function tunnelBrother(subject, rose) { + const state = Barrows._test.session(subject); + const npc = new core.NPC(Barrows._test.BROTHERS[1].npcId, rose.clone()); + npc.setOwner(subject); + npc.__barrowsRose = rose.clone(); + npc.isRegistered = () => true; + state.npcs.add(npc); + state.brother = npc; + return npc; +} + +test("Barrows: a brother left more than 8 tiles from where he rose turns away, then goes the tick after", () => { + const subject = player(); + arrive(subject, new Location(3552, 9687, 0)); + const { processPlayer, session } = Barrows._test; + const npc = tunnelBrother(subject, new Location(3552, 9687, 0)); + const removed = core.World.getRemoveNPCQueue(); + const before = removed.length; + try { + npc.getCombat().attack = () => {}; + subject.setLocation(new Location(3552 - 8, 9687 - 8, 0)); + processPlayer({ player: subject }); + assert.equal(session(subject).brother, npc, "still after the player at 8 tiles"); + subject.setLocation(new Location(3552 - 9, 9687 - 6, 0)); + processPlayer({ player: subject }); + assert.equal(session(subject).brother, npc, "turns away first"); + processPlayer({ player: subject }); + assert.equal(session(subject).brother, null, "then goes"); + assert.ok(removed.includes(npc)); + processPlayer({ player: subject }); + assert.ok(!subject.sent.messages.includes("We'll finish this later..."), "no line in the tunnels (227/00086)"); + } finally { + removed.length = before; + } +}); + +test("Barrows: an unfinished crypt fight ends with 'We'll finish this later...' three ticks into the tunnels, and on a death", () => { + const subject = player(); + arrive(subject, AHRIM_MOUND); + Barrows._test.dig({ player: subject }); + for (let i = 0; i < 5 && subject.getLocation().getZ() === 0; i++) Barrows._test.processPlayer({ player: subject }); + const run = subject.getAttribute("barrows"); + const crypt = Barrows._test.BROTHERS[run.tunnel]; + subject.setLocation(crypt.crypt.clone()); + const npc = tunnelBrother(subject, crypt.spawn); + npc.setLocation(crypt.spawn.clone()); + const removed = core.World.getRemoveNPCQueue(); + const before = removed.length; + try { + Barrows._test.enterTunnel(subject, run, crypt); + assert.equal(subject.getLocation().getZ(), 0, "in the tunnels"); + const lines = () => subject.sent.messages.filter((m) => m === "We'll finish this later...").length; + for (let i = 0; i < 2; i++) Barrows._test.processPlayer({ player: subject }); + assert.equal(lines(), 0, "not yet"); + Barrows._test.processPlayer({ player: subject }); + assert.equal(lines(), 1, "on the third tick"); + Barrows._test.processPlayer({ player: subject }); + assert.equal(lines(), 1, "once"); + + const dying = player(); + arrive(dying, CHEST_ROOM); + tunnelBrother(dying, CHEST_ROOM); + Barrows._test.playerDeath({ player: dying }); + assert.ok(dying.sent.messages.includes("We'll finish this later...")); + } finally { + removed.length = before; + } +}); + +test("Barrows: a brother takes the player from the crypt monster attacking them", () => { + const subject = player(); + arrive(subject, CHEST_ROOM); + const state = Barrows._test.session(subject); + const rat = new core.NPC(core.NpcIdentifiers.CRYPT_RAT, CHEST_ROOM.clone()); + rat.setOwner(subject); + state.npcs.add(rat); + let reset = 0; + let target = subject; + const attacks = []; + rat.isRegistered = () => true; + rat.getCombat().getTarget = () => target; + rat.getCombat().reset = () => { reset++; target = null; }; + rat.getCombat().attack = (whom) => { attacks.push(whom); target = whom; }; + subject.getCombat().setUnderAttack(rat); + assert.equal(subject.getCombat().getAttacker(), rat); + const queue = core.World.getAddNPCQueue(); + const before = queue.length; + try { + // The tunnel's brother rising at the chest. + Object.assign(subject.getAttribute("barrows"), { killed: [], kills: 0, chestOpen: false }); + Barrows._test.searchChest(subject, 1); + const npc = queue.at(-1); + assert.equal(state.brother, npc); + npc.forceChat = () => npc; + try { npc.onAdd(); } catch { /* the fixture world's combat wiring; the takeover comes first */ } + assert.equal(reset, 1, "the rat stops"); + assert.equal(subject.getCombat().getAttacker(), null, "and no longer holds the player in single-way combat"); + npc.getCombat().attack = () => {}; + npc.isRegistered = () => true; + Barrows._test.processPlayer({ player: subject }); + assert.deepEqual(attacks, [], "not while the brother fights"); + // He dies: the rat is back on the player (227/01885 ticks 12118-12119). + npc.isDyingFunction = () => true; + Barrows._test.processPlayer({ player: subject }); + assert.deepEqual(attacks, [subject]); + } finally { + queue.length = before; + } +}); + +// The Wiki (Barrows/Strategies): "Once the chest is looted, the tunnels will shake and start to collapse, causing +// occasional damage to the player, and the arrangement of the doors and rooms will shift." Recorded difference: +// 37 loots show neither (docs/barrows-tunnels.md). +test("Barrows: looting shifts the doors and rooms, and the collapsing tunnels hurt until left (Wiki)", () => { + const subject = player(); + arrive(subject, CHEST_ROOM); + const run = subject.getAttribute("barrows"); + Object.assign(run, { killed: [0, 1, 2, 3, 4, 5], kills: 6, points: 600, chestOpen: true }); + // The shift re-rolls the layout and sends it: every door varbit goes out again after the loot. + subject.sent.varbits.clear(); + Barrows._test.searchChest(subject, 1); + for (let id = 469; id <= 484; id++) assert.ok(subject.sent.varbits.has(id), `door varbit ${id} re-sent`); + assert.deepEqual([...run.openDoors].filter((id) => subject.sent.varbits.get(id) !== 0), [], "the new layout's open doors"); + const cycle = core.World.getProcessCycle; + const damage = () => (subject.getCombat().getHitQueue().hasPendingWork() ? 1 : 0); + try { + for (let i = 1; i < 10; i++) { + core.World.getProcessCycle = () => i; + Barrows._test.processPlayer({ player: subject }); + } + assert.equal(damage(), 0, "between the collapse's ticks"); + core.World.getProcessCycle = () => 10; + Barrows._test.processPlayer({ player: subject }); + assert.equal(damage(), 1, "a collapse hit every 10 ticks"); + const left = player(); + arrive(left, CHEST_ROOM); + Object.assign(left.getAttribute("barrows"), { killed: [0], kills: 1, points: 100, chestOpen: true }); + Barrows._test.searchChest(left, 1); + arrive(left, SURFACE); + core.World.getProcessCycle = () => 20; + Barrows._test.processPlayer({ player: left }); + assert.equal(left.getCombat().getHitQueue().hasPendingWork(), false, "none once out of the tunnels"); + } finally { + core.World.getProcessCycle = cycle; + } +}); + +test("Barrows: the chest's elite clue is a scroll box once boxes are unlocked, and none when the player can hold no more", () => { + const clueEvents = (subject, { box, full }) => { + diaryApi.onCustomEvent("treasure-trails:can-receive", (request) => { if (request.player === subject) request.allowed = !full; }); + diaryApi.onCustomEvent("treasure-trails:clue-item", (request) => { + if (request.player === subject && box) request.itemId = core.ItemIdentifiers.SCROLL_BOX_ELITE_; + }); + }; + const loot = (options) => { + const subject = player(); + clueEvents(subject, options); + arrive(subject, CHEST_ROOM); + Object.assign(subject.getAttribute("barrows"), { killed: [0], kills: 1, points: 100, chestOpen: true }); + const random = Math.random; + Math.random = () => 0; // every roll: the equipment piece, then the clue + try { Barrows._test.searchChest(subject, 1); } finally { Math.random = random; } + return subject.collected.map(([id]) => id); + }; + const items = core.ItemIdentifiers; + assert.ok(loot({ box: true, full: false }).includes(items.SCROLL_BOX_ELITE_)); + assert.ok(!loot({ box: true, full: false }).includes(items.CLUE_SCROLL_ELITE_)); + assert.ok(loot({ box: false, full: false }).includes(items.CLUE_SCROLL_ELITE_)); + const full = loot({ box: true, full: true }); + assert.ok(!full.includes(items.SCROLL_BOX_ELITE_) && !full.includes(items.CLUE_SCROLL_ELITE_), String(full)); +}); + +test("Barrows: Can't Touch Me fails on a melee brother's melee swing, hit or miss, and not on Ahrim's or Karil's attacks", () => { + const failed = []; + diaryApi.onCustomEvent("combat-achievements:failed", (request) => failed.push([request.player, request.task, request.reason])); + const completed = []; + diaryApi.onCustomEvent("combat-achievements:complete", (request) => completed.push([request.player, request.task])); + const { trackBrotherAttack, trackBrotherHit, BROTHERS } = Barrows._test; + const brother = (index) => new core.NPC(BROTHERS[index].npcId, CHEST_ROOM.clone()); + const melee = core.CombatType.MELEE; + + const clean = player(); + arrive(clean, CHEST_ROOM); + trackBrotherAttack({ attacker: brother(0), target: clean, combatType: core.CombatType.MAGIC }); + trackBrotherAttack({ attacker: brother(3), target: clean, combatType: core.CombatType.RANGED }); + Object.assign(clean.getAttribute("barrows"), { killed: [0, 1, 2, 3, 4, 5], kills: 6, points: 600, chestOpen: true }); + Barrows._test.searchChest(clean, 1); + assert.ok(completed.some(([p, task]) => p === clean && task === "Can't Touch Me"), "ranged and magic don't count"); + + const hit = player(); + arrive(hit, CHEST_ROOM); + trackBrotherAttack({ attacker: brother(1), target: hit, combatType: melee }); + trackBrotherAttack({ attacker: brother(1), target: hit, combatType: melee }); + assert.deepEqual(failed.filter(([p]) => p === hit).map(([, task, reason]) => [task, reason]), + [["Can't Touch Me", "Dharok the Wretched performed a melee attack."]], "on the swing, once"); + Object.assign(hit.getAttribute("barrows"), { killed: [0, 1, 2, 3, 4, 5], kills: 6, points: 600, chestOpen: true }); + Barrows._test.searchChest(hit, 1); + assert.ok(!completed.some(([p, task]) => p === hit && task === "Can't Touch Me"), "not awarded after a melee swing"); + + const damaged = player(); + arrive(damaged, CHEST_ROOM); + trackBrotherHit({ attacker: brother(0), target: damaged, hit: { getTotalDamage: () => 0 } }); + trackBrotherHit({ attacker: brother(0), target: damaged, hit: { getTotalDamage: () => 15 } }); + trackBrotherHit({ attacker: brother(0), target: damaged, hit: { getTotalDamage: () => 15 } }); + assert.deepEqual(failed.filter(([p]) => p === damaged).map(([, task, reason]) => [task, reason]), + [["Pray for Success", "Ahrim the Blighted damaged you."]]); +});