@kradle/challenges-sdk 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/actions.js CHANGED
@@ -33,6 +33,65 @@ exports.Actions = {
33
33
  announce: ({ message }) => {
34
34
  (0, sandstone_1.tellraw)("@a", ["\n", { text: constants_1.DISPLAY_TAG, color: "aqua" }, " | ", message, "\n"]);
35
35
  },
36
+ /**
37
+ * Pick `count` random participants and tag them. Used to assign hidden
38
+ * roles in social-deduction challenges — combine with `Actions.tellraw` to
39
+ * privately notify each tagged participant of their assignment.
40
+ *
41
+ * Uses Minecraft's `sort=random,limit=N` selector behavior. The selection
42
+ * happens at command time (typically `start_challenge`), so it's stable
43
+ * for the rest of the run.
44
+ *
45
+ * @example Saboteur assignment in a 4-player game:
46
+ * ```ts
47
+ * start_challenge: () => {
48
+ * Actions.assignRandomTag({ tag: "saboteur", count: 1 });
49
+ * // Then DM each tagged participant their secret role:
50
+ * Actions.tellraw({
51
+ * target: Selector("@a", { tag: "saboteur" }),
52
+ * message: [{ text: "🔪 You're the saboteur. Stop the miners.", color: "red" }],
53
+ * });
54
+ * }
55
+ * ```
56
+ *
57
+ * `count` is capped to the number of participants — over-asking just tags
58
+ * everyone available.
59
+ */
60
+ assignRandomTag: ({ tag: tagName, count }) => {
61
+ sandstone_1.execute.as((0, sandstone_1.Selector)("@a", { tag: constants_1.KRADLE_PARTICIPANT_TAG, sort: "random", limit: count })).run(() => {
62
+ (0, sandstone_1.tag)("@s").add(tagName);
63
+ });
64
+ },
65
+ /**
66
+ * Pick a uniform random integer in `[min, max]` (both inclusive) and
67
+ * return it as an anonymous `Score`. Wraps Minecraft's `random value`
68
+ * command, which Sandstone does not expose as a typed primitive — this
69
+ * helper is the abstraction so that user code never has to write `raw`
70
+ * for randomness.
71
+ *
72
+ * Use to randomize challenge state at `start_challenge` (which goal block
73
+ * is "the" goal, which player a saboteur is paired with for a side-quest,
74
+ * etc.) so behavior isn't gameable across runs.
75
+ *
76
+ * @example Pick one of 4 goal directions per run:
77
+ * ```ts
78
+ * goal_index: { type: "global", default: 0 },
79
+ *
80
+ * start_challenge: () => {
81
+ * variables.goal_index.score.set(Actions.randomInt({ min: 0, max: 3 }));
82
+ * // Then branch: _.if(goal_index.equalTo(0), () => place at N), etc.
83
+ * }
84
+ * ```
85
+ */
86
+ randomInt: ({ min, max }) => {
87
+ const result = (0, sandstone_1.Variable)(0);
88
+ // Sandstone has no typed wrapper for `random value <min>..<max>`.
89
+ // This is the single legitimate `raw` in the SDK — encapsulating it
90
+ // here means user code never has to. Once Sandstone gains the
91
+ // command, swap the body for `execute.store.result.score(result).run.random.value(...)`.
92
+ (0, sandstone_1.raw)(`execute store result score ${result.target} ${result.objective.name} run random value ${min}..${max}`);
93
+ return result;
94
+ },
36
95
  /**
37
96
  * Clear the inventory of a target.
38
97
  * @param {TargetNames} target - The target to clear the inventory of.
@@ -165,6 +224,34 @@ exports.Actions = {
165
224
  kill: ({ selector }) => {
166
225
  (0, sandstone_1.kill)(mapTarget(selector));
167
226
  },
227
+ /**
228
+ * Set the gamemode of a target. Useful for moving an eliminated player
229
+ * to spectator without killing them (preserves the entity, lets them
230
+ * watch the rest of the run).
231
+ *
232
+ * @example
233
+ * Actions.setGamemode({ target: "self", mode: "spectator" });
234
+ * Actions.setGamemode({ target: "all", mode: "adventure" });
235
+ */
236
+ setGamemode: ({ target, mode, }) => {
237
+ (0, sandstone_1.gamemode)(mode, mapTarget(target));
238
+ },
239
+ /**
240
+ * Eliminate a participant from the active round: switch them to
241
+ * spectator mode (so they can still observe but can't act). Sister
242
+ * helper to `kill`, intended for vote-out / king-of-the-hill / battle
243
+ * royale style games where elimination shouldn't end the agent's
244
+ * connection.
245
+ *
246
+ * Note: this only flips gamemode. The challenge author is responsible
247
+ * for any per-player tracking variable (e.g. `is_alive`).
248
+ *
249
+ * @example
250
+ * Actions.eliminate({ target: "self" });
251
+ */
252
+ eliminate: ({ target }) => {
253
+ (0, sandstone_1.gamemode)("spectator", mapTarget(target));
254
+ },
168
255
  /**
169
256
  * Set an attribute for a target.
170
257
  * @param {ATTRIBUTES} attribute_ - The attribute to set.
@@ -207,6 +294,50 @@ exports.Actions = {
207
294
  }
208
295
  sandstone_1.data.modify.storage(constants_1.KRADLE_STORAGE, constants_1.END_STATE_KEY).set.value(endState);
209
296
  },
297
+ /**
298
+ * For each `(name, condition)` pair, emit `_.if(condition, () =>
299
+ * setEndState(name))` at the current codegen location. Where (and how
300
+ * often) those checks run is up to the caller — `events.on_tick` for a
301
+ * per-tick check, `custom_events.actions` for a single fire, etc.
302
+ *
303
+ * Returns a `ConditionType` that is true when at least one of the input
304
+ * conditions is true (i.e. an end-state was applied). Hand it to
305
+ * `.end_condition()` if you want the game to end as soon as any end-state
306
+ * has been set; ignore it if the game's end is gated on something else
307
+ * (timer, separate condition).
308
+ *
309
+ * Note: conditions are evaluated in whatever execution context the caller
310
+ * is in. From `on_tick` that's the server entity, where per-player score
311
+ * reads silently fail — see `Actions.maxPlayerScore` for the per-player →
312
+ * global bridge.
313
+ *
314
+ * @example
315
+ * let endReached: ConditionType | undefined;
316
+ * const challenge = createChallenge({...});
317
+ * challenge
318
+ * .events((vars) => ({
319
+ * on_tick: () => {
320
+ * endReached = Actions.setEndStates({
321
+ * winner_found: vars.top_kills.greaterOrEqualThan(20),
322
+ * all_dead: vars.alive_players.equalTo(0),
323
+ * });
324
+ * },
325
+ * }))
326
+ * .end_condition(() => endReached!); // game ends as soon as any branch fires
327
+ */
328
+ setEndStates: (endStates) => {
329
+ const entries = Object.entries(endStates);
330
+ if (entries.length === 0) {
331
+ throw new Error("Actions.setEndStates: at least one end-state must be provided.");
332
+ }
333
+ for (const [name, condition] of entries) {
334
+ sandstone_1._.if(condition, () => {
335
+ exports.Actions.setEndState({ endState: name });
336
+ });
337
+ }
338
+ const conditions = entries.map(([, condition]) => condition);
339
+ return conditions.length === 1 ? conditions[0] : sandstone_1._.or(...conditions);
340
+ },
210
341
  /**
211
342
  * Set a block at a specific location.
212
343
  */
@@ -265,6 +396,47 @@ exports.Actions = {
265
396
  set: ({ variable, value }) => {
266
397
  variable.set(value);
267
398
  },
399
+ /**
400
+ * Selector that matches `@s` only when standing on the block at the
401
+ * given absolute coordinate. Use this anywhere you'd otherwise have
402
+ * written `Selector("@s", { x, y, z })` — that bare form does NOT
403
+ * constrain position (Minecraft treats x/y/z as the selector origin
404
+ * for distance math, not as a position filter), so the condition
405
+ * silently passes for everyone. This helper bakes in the right
406
+ * `dx: 0, dy: 1, dz: 0` volume covering the block above and the
407
+ * head space, so the selector matches only when the player's feet
408
+ * are inside the 1×1×1 column at (x, y+1, z).
409
+ *
410
+ * @param {number} x - X of the block being stood on.
411
+ * @param {number} y - Y of the block being stood on (the player's feet are at y+1).
412
+ * @param {number} z - Z of the block being stood on.
413
+ * @param {string} [role] - Optional role tag the player must also have.
414
+ *
415
+ * @example
416
+ * // Trigger alice_shared when Alice steps on her pad block.
417
+ * alice_shared: {
418
+ * type: "global",
419
+ * default: 0,
420
+ * updater: (value) => {
421
+ * _.if(value.equalTo(0), () => {
422
+ * forEveryPlayer(() => {
423
+ * _.if(Actions.standingOnBlock({ x: ALICE_PAD.x, y: ALICE_PAD.y, z: ALICE_PAD.z, role: "alice" }), () => {
424
+ * value.set(1);
425
+ * });
426
+ * });
427
+ * });
428
+ * },
429
+ * },
430
+ */
431
+ standingOnBlock: ({ x, y, z, role }) => (0, sandstone_1.Selector)("@s", {
432
+ ...(role ? { tag: role } : {}),
433
+ x,
434
+ y: y + 1,
435
+ z,
436
+ dx: 0,
437
+ dy: 1,
438
+ dz: 0,
439
+ }),
268
440
  /**
269
441
  * log a message with the watcher
270
442
  * @param {string} message - The message to send.
@@ -284,8 +456,8 @@ exports.Actions = {
284
456
  * @param {boolean} absolute - Whether the coordinates are absolute or relative.
285
457
  */
286
458
  summonItem: ({ item, x, y, z, absolute }) => {
287
- const abs = absolute ? "" : "~";
288
- (0, sandstone_1.raw)(`summon item ${abs}${x} ${abs}${y} ${abs}${z} {Item:{id:"${item}",Count:1b}}`);
459
+ const pos = absolute ? (0, sandstone_1.abs)(x, y, z) : (0, sandstone_1.rel)(x, y, z);
460
+ (0, sandstone_1.summon)("minecraft:item", pos, { Item: { id: item, Count: sandstone_1.NBT.byte(1) } });
289
461
  },
290
462
  /**
291
463
  * Count the number of a specific item in a target's inventory.
@@ -299,6 +471,219 @@ exports.Actions = {
299
471
  sandstone_1.execute.store.result.score(variable).run.clear(mapTarget(target), item, 0);
300
472
  return variable;
301
473
  },
474
+ /**
475
+ * Compute the maximum value of an individual score across all
476
+ * participants and store it in a global Variable. Returns the variable.
477
+ *
478
+ * Why this helper exists: end-state and end-condition checks evaluated
479
+ * from `events.on_tick` run in server context (the caller is a non-player
480
+ * entity), so an `if score @s X matches Y` check on a per-player score
481
+ * silently fails because @s has no entry on the per-player objective.
482
+ * Wrapping the comparison in this helper materializes a global "max
483
+ * across players" value that IS safe to reference from those checks.
484
+ *
485
+ * @param {Score} score - The per-player score to aggregate.
486
+ * @param {number} [min=0] - Lower bound to seed the result with. Pass a
487
+ * negative value if your per-player score can go below 0 (e.g. climb's
488
+ * `current_height` defaulting to -1000); otherwise the default `0`
489
+ * would mask negative actual maxes.
490
+ * @returns {Score} An anonymous Score containing the max.
491
+ *
492
+ * @example
493
+ * // In a custom_variables global updater:
494
+ * max_diamonds: {
495
+ * type: "global",
496
+ * default: 0,
497
+ * updater: (value, { diamonds }) => {
498
+ * value.set(Actions.maxPlayerScore({ score: diamonds }));
499
+ * },
500
+ * },
501
+ *
502
+ * // Then end-states can reference the global:
503
+ * .events(({ max_diamonds }) => ({
504
+ * on_tick: () => Actions.setEndStates({
505
+ * winner_found: max_diamonds.greaterOrEqualThan(5),
506
+ * }),
507
+ * }))
508
+ *
509
+ * @example
510
+ * // Climb's max_height — y can go below 0:
511
+ * max_height_global: {
512
+ * type: "global",
513
+ * default: -1000,
514
+ * updater: (value, { max_height }) => {
515
+ * value.set(Actions.maxPlayerScore({ score: max_height, min: -1000 }));
516
+ * },
517
+ * },
518
+ */
519
+ maxPlayerScore: ({ score, min = 0 }) => {
520
+ const result = (0, sandstone_1.Variable)(min);
521
+ // Iterate over participants; for each, if their `score` exceeds the
522
+ // running max, copy it in. Same pattern an author would write by
523
+ // hand with forEveryPlayer + _.if(score.greaterThan(result), ...).
524
+ sandstone_1.execute.as(constants_1.ALL).run(() => {
525
+ sandstone_1._.if(score.greaterThan(result), () => {
526
+ result.set(score);
527
+ });
528
+ });
529
+ return result;
530
+ },
531
+ /**
532
+ * Returns a Sandstone condition that's true when the executing player
533
+ * (in `as @s` context) is standing on `block`. The default is a
534
+ * single-cell check (block at `~ ~-1 ~`), but `slop` widens the check
535
+ * to a `(2*slop+1)×(2*slop+1)` patch around the player's foot position
536
+ * — useful when the agent's pathfinder leaves them slightly off-center
537
+ * from a target block (e.g. mineflayer's `goToNearestBlock` reports
538
+ * success once within ~1.5 blocks of the target, so the agent is
539
+ * commonly off by a fractional block in x/z).
540
+ *
541
+ * Compiles to: `block ~ ~-1 ~ <block>` for slop=0, or an `_.or(...)` of
542
+ * 9 / 25 / etc. cell checks for slop=1 / 2 / etc.
543
+ *
544
+ * @example
545
+ * // PD-style "did the agent step on the cooperate pad?" check
546
+ * choice: {
547
+ * type: "individual",
548
+ * default: 0,
549
+ * updater: (value) => {
550
+ * _.if(Actions.isStandingOn({ block: "minecraft:lime_wool", slop: 1 }), () => {
551
+ * value.set(COOPERATE);
552
+ * });
553
+ * },
554
+ * },
555
+ */
556
+ isStandingOn: ({ block, slop = 0 }) => {
557
+ if (slop < 0 || !Number.isInteger(slop)) {
558
+ throw new Error(`Actions.isStandingOn: slop must be a non-negative integer, got ${slop}`);
559
+ }
560
+ if (slop === 0) {
561
+ return sandstone_1._.block((0, sandstone_1.rel)(0, -1, 0), block);
562
+ }
563
+ const conditions = [];
564
+ for (let dx = -slop; dx <= slop; dx++) {
565
+ for (let dz = -slop; dz <= slop; dz++) {
566
+ conditions.push(sandstone_1._.block((0, sandstone_1.rel)(dx, -1, dz), block));
567
+ }
568
+ }
569
+ return sandstone_1._.or(...conditions);
570
+ },
571
+ /**
572
+ * Count instances of a block within an axis-aligned region. Useful for
573
+ * detecting agent-built structures without pinning detection to a single
574
+ * coordinate (which breaks the moment the agent moves before building).
575
+ *
576
+ * Implementation note: emits one `execute if block` check per cell in the
577
+ * region at codegen time, so the region is hard-capped at 4096 cells
578
+ * (~64×8×8) to keep the generated datapack reasonable.
579
+ *
580
+ * @param block The block ID to count (e.g. "minecraft:cobblestone").
581
+ * @param from First corner of the region (inclusive).
582
+ * @param to Opposite corner (inclusive).
583
+ * @param absolute Whether `from` / `to` are absolute world coordinates.
584
+ * @returns A Sandstone `Score` containing the count.
585
+ *
586
+ * @example
587
+ * // Detect any 5+ cobblestone block tower built within a 12×6×12 zone:
588
+ * const count = Actions.countBlocksInRegion({
589
+ * block: "minecraft:cobblestone",
590
+ * from: { x: -6, y: -60, z: -6 },
591
+ * to: { x: 6, y: -55, z: 6 },
592
+ * absolute: true,
593
+ * });
594
+ * _.if(count.greaterOrEqualThan(5), () => Actions.announce({ message: "Tower built!" }));
595
+ */
596
+ countBlocksInRegion: ({ block, from, to, absolute, }) => {
597
+ const x1 = Math.min(from.x, to.x);
598
+ const x2 = Math.max(from.x, to.x);
599
+ const y1 = Math.min(from.y, to.y);
600
+ const y2 = Math.max(from.y, to.y);
601
+ const z1 = Math.min(from.z, to.z);
602
+ const z2 = Math.max(from.z, to.z);
603
+ const cellCount = (x2 - x1 + 1) * (y2 - y1 + 1) * (z2 - z1 + 1);
604
+ const MAX_CELLS = 4096;
605
+ if (cellCount > MAX_CELLS) {
606
+ throw new Error(`Actions.countBlocksInRegion: region has ${cellCount} cells, exceeding the safety cap of ${MAX_CELLS}. ` +
607
+ `Reduce the bounding box or use a smaller scan area.`);
608
+ }
609
+ const counter = (0, sandstone_1.Variable)();
610
+ counter.set(0);
611
+ for (let x = x1; x <= x2; x++) {
612
+ for (let y = y1; y <= y2; y++) {
613
+ for (let z = z1; z <= z2; z++) {
614
+ const coords = absolute ? (0, sandstone_1.abs)(x, y, z) : (0, sandstone_1.rel)(x, y, z);
615
+ sandstone_1.execute.if.block(coords, block).run(() => {
616
+ counter.add(1);
617
+ });
618
+ }
619
+ }
620
+ }
621
+ return counter;
622
+ },
623
+ /**
624
+ * Count instances of a block in a region centered on a target. Same idea
625
+ * as `countBlocksInRegion` but the bounds are *relative to the target's
626
+ * current position* — useful when the region of interest moves with a
627
+ * player (e.g. "how many X blocks are around the agent right now").
628
+ *
629
+ * What this is NOT: it does not verify a structure (the matches don't
630
+ * have to be contiguous), and it does not prove the target placed them.
631
+ * Treat the result as "presence count in a volume." Turn it into "the
632
+ * agent placed N of these" only when the block type doesn't spawn
633
+ * naturally in your world (and your arena init didn't pre-place any), or
634
+ * by clearing the volume first and counting the delta.
635
+ *
636
+ * Implementation note: emits one `execute as <target> at @s if block`
637
+ * check per cell at codegen time, so the region is hard-capped at 4096
638
+ * cells just like `countBlocksInRegion`.
639
+ *
640
+ * @example
641
+ * // Count diamond_block instances within 6 blocks of the agent. Diamond
642
+ * // blocks don't generate naturally, so in a flat-world challenge whose
643
+ * // arena init doesn't pre-place any, this is equivalently the count of
644
+ * // diamond blocks the agent has placed within reach.
645
+ * diamond_blocks_nearby: {
646
+ * type: "individual",
647
+ * default: 0,
648
+ * updater: (value) => {
649
+ * value.set(Actions.countBlocksRelativeTo({
650
+ * target: "self",
651
+ * block: "minecraft:diamond_block",
652
+ * dxRange: [-6, 6],
653
+ * dyRange: [-2, 4],
654
+ * dzRange: [-6, 6],
655
+ * }));
656
+ * },
657
+ * }
658
+ */
659
+ countBlocksRelativeTo: ({ target, block, dxRange, dyRange, dzRange, }) => {
660
+ const [dx1, dx2] = [Math.min(...dxRange), Math.max(...dxRange)];
661
+ const [dy1, dy2] = [Math.min(...dyRange), Math.max(...dyRange)];
662
+ const [dz1, dz2] = [Math.min(...dzRange), Math.max(...dzRange)];
663
+ const cellCount = (dx2 - dx1 + 1) * (dy2 - dy1 + 1) * (dz2 - dz1 + 1);
664
+ const MAX_CELLS = 4096;
665
+ if (cellCount > MAX_CELLS) {
666
+ throw new Error(`Actions.countBlocksRelativeTo: region has ${cellCount} cells, exceeding the safety cap of ${MAX_CELLS}. ` +
667
+ `Reduce dx/dy/dzRange or scan in slices.`);
668
+ }
669
+ const counter = (0, sandstone_1.Variable)();
670
+ counter.set(0);
671
+ sandstone_1.execute
672
+ .as(mapTarget(target))
673
+ .at("@s")
674
+ .run(() => {
675
+ for (let dx = dx1; dx <= dx2; dx++) {
676
+ for (let dy = dy1; dy <= dy2; dy++) {
677
+ for (let dz = dz1; dz <= dz2; dz++) {
678
+ sandstone_1.execute.if.block((0, sandstone_1.rel)(dx, dy, dz), block).run(() => {
679
+ counter.add(1);
680
+ });
681
+ }
682
+ }
683
+ }
684
+ });
685
+ return counter;
686
+ },
302
687
  /**
303
688
  * Get the current player's position as x, y, z Score variables.
304
689
  * Must be called in a player context (e.g., inside forEveryPlayer or when @s is a player).
@@ -333,5 +718,296 @@ exports.Actions = {
333
718
  }
334
719
  return (0, sandstone_1.Selector)("@e", { type: "minecraft:marker", tag: `kradle.location.${name}`, limit: 1 });
335
720
  },
721
+ /**
722
+ * Build a box (4 walls + optional floor/roof) in a single call. Replaces
723
+ * the typical 5+ `Actions.fill` calls per arena.
724
+ *
725
+ * @param block The wall block (e.g. "minecraft:stone").
726
+ * @param from First corner (inclusive).
727
+ * @param to Opposite corner (inclusive).
728
+ * @param absolute Whether coordinates are absolute or player-relative.
729
+ * @param hollow When true (default), only walls are placed; the interior is left untouched.
730
+ * When false, the entire volume is filled with `block`.
731
+ * @param floor Optional block to fill the floor with (overrides `block` for floor only).
732
+ * @param roof Optional block to fill the roof with.
733
+ * @param clearInside When true and `hollow=true`, the interior volume is set to air
734
+ * (useful for clearing existing terrain inside the new box).
735
+ *
736
+ * @example
737
+ * // 13x13x5 stone arena with a stone-bricks floor, no roof, interior cleared
738
+ * Actions.box({
739
+ * block: "minecraft:stone",
740
+ * from: { x: -6, y: -60, z: -6 },
741
+ * to: { x: 6, y: -55, z: 6 },
742
+ * absolute: true,
743
+ * hollow: true,
744
+ * floor: "minecraft:stone_bricks",
745
+ * clearInside: true,
746
+ * });
747
+ */
748
+ box: ({ block, from, to, absolute, hollow = true, floor, roof, clearInside = false, }) => {
749
+ const x1 = Math.min(from.x, to.x);
750
+ const x2 = Math.max(from.x, to.x);
751
+ const y1 = Math.min(from.y, to.y);
752
+ const y2 = Math.max(from.y, to.y);
753
+ const z1 = Math.min(from.z, to.z);
754
+ const z2 = Math.max(from.z, to.z);
755
+ const fillRegion = (b, ax, ay, az, bx, by, bz) => {
756
+ const c1 = absolute ? (0, sandstone_1.abs)(ax, ay, az) : (0, sandstone_1.rel)(ax, ay, az);
757
+ const c2 = absolute ? (0, sandstone_1.abs)(bx, by, bz) : (0, sandstone_1.rel)(bx, by, bz);
758
+ (0, sandstone_1.fill)(c1, c2, b);
759
+ };
760
+ if (!hollow) {
761
+ fillRegion(block, x1, y1, z1, x2, y2, z2);
762
+ if (floor)
763
+ fillRegion(floor, x1, y1, z1, x2, y1, z2);
764
+ if (roof)
765
+ fillRegion(roof, x1, y2, z1, x2, y2, z2);
766
+ return;
767
+ }
768
+ // Walls: two pairs of opposite faces.
769
+ // North/south
770
+ fillRegion(block, x1, y1, z1, x2, y2, z1);
771
+ fillRegion(block, x1, y1, z2, x2, y2, z2);
772
+ // East/west
773
+ fillRegion(block, x1, y1, z1, x1, y2, z2);
774
+ fillRegion(block, x2, y1, z1, x2, y2, z2);
775
+ if (floor)
776
+ fillRegion(floor, x1, y1, z1, x2, y1, z2);
777
+ if (roof)
778
+ fillRegion(roof, x1, y2, z1, x2, y2, z2);
779
+ if (clearInside) {
780
+ const interiorBlock = clearInside === true ? "minecraft:air" : clearInside;
781
+ // Only fill the interior if there's actually room (>= 3 in each axis).
782
+ if (x2 - x1 >= 2 && y2 - y1 >= 2 && z2 - z1 >= 2) {
783
+ fillRegion(interiorBlock, x1 + 1, y1 + 1, z1 + 1, x2 - 1, y2 - 1, z2 - 1);
784
+ }
785
+ }
786
+ },
787
+ /**
788
+ * Give every participant a list of items in one call. Replaces the
789
+ * sequence of `Actions.give({ target: "all", item: …, count: … })` calls
790
+ * that opens nearly every multi-player init_participants (castle-ctf has
791
+ * six of them for the iron-sword + 4 armor pieces + food loadout).
792
+ *
793
+ * @example PvP standard kit:
794
+ * ```ts
795
+ * Actions.giveAll([
796
+ * { item: "minecraft:iron_sword" },
797
+ * { item: "minecraft:iron_helmet" },
798
+ * { item: "minecraft:iron_chestplate" },
799
+ * { item: "minecraft:iron_leggings" },
800
+ * { item: "minecraft:iron_boots" },
801
+ * { item: "minecraft:cooked_beef", count: 5 },
802
+ * ]);
803
+ * ```
804
+ *
805
+ * `count` defaults to 1. For role-specific equipment, use plain
806
+ * `Actions.give({ target: roleName, … })`.
807
+ */
808
+ giveAll: (items) => {
809
+ for (const it of items) {
810
+ (0, sandstone_1.give)(mapTarget("all"), it.item, it.count ?? 1);
811
+ }
812
+ },
813
+ /**
814
+ * "When the block at this absolute coordinate stops being `expected`, set
815
+ * `into` to 1." The standard goal_broken / flag_broken global-variable
816
+ * updater idiom. Latches at 1 — once tripped, stays tripped (so the
817
+ * end_state fires consistently even if the block is later replaced).
818
+ *
819
+ * Replaces the 4-line `_.if(_.not(_.block(abs(...), ...)), () => value.set(1))`
820
+ * pattern that appears in ~10 challenges' custom_variable updaters
821
+ * (castle-ctf×2, castle-siege×4, defender-striker, beanstalk, tower-trio,
822
+ * tunnel-rush, sky-walker, …). Removes the need to import `abs` from
823
+ * sandstone for this purpose.
824
+ *
825
+ * For multi-block checks ("all N landmarks broken" — diamond-hunt,
826
+ * return-home), keep using the manual `_.if(_.and(...conditions), …)`
827
+ * pattern — this helper is single-block only.
828
+ *
829
+ * @example castle-ctf red flag (latching — once broken, stays broken):
830
+ * ```ts
831
+ * red_flag_broken: {
832
+ * type: "global",
833
+ * default: 0,
834
+ * updater: (value) => {
835
+ * // Latch: only flip 0→1, never reset to 0. The returned Score is
836
+ * // itself a Condition (truthy = non-zero), so no `.equalTo(1)` needed.
837
+ * _.if(Actions.detectBlockMissing({
838
+ * at: { x: RED_BASE.x, y: RED_BASE.y + 1, z: RED_BASE.z },
839
+ * expected: "minecraft:red_wool",
840
+ * }), () => value.set(1));
841
+ * },
842
+ * }
843
+ * ```
844
+ *
845
+ * @returns {Score} An anonymous Score: 1 if the block at `at` is NOT
846
+ * `expected`, 0 if it is. Non-latching — recomputed every call. Wrap in
847
+ * `_.if(missing, () => value.set(1))` (the Score is itself a Condition,
848
+ * truthy = non-zero) for the latching "once broken, stays broken" pattern.
849
+ */
850
+ detectBlockMissing: ({ at, expected }) => {
851
+ const result = (0, sandstone_1.Variable)(0);
852
+ sandstone_1._.if(sandstone_1._.not(sandstone_1._.block((0, sandstone_1.abs)(at.x, at.y, at.z), expected)), () => {
853
+ result.set(1);
854
+ });
855
+ return result;
856
+ },
857
+ /**
858
+ * Summon a single configurable entity with optional health, attack damage,
859
+ * movement speed, and tags. Uses Sandstone's typed `summon` + NBT helpers
860
+ * (`NBT.byte`, `NBT.float`) so that booleans and NBT primitives serialize
861
+ * correctly — sandstone otherwise emits JS `true` as `{}` (an invalid NBT
862
+ * token), which broke boss-brawl's `CustomNameVisible: true` summon early on.
863
+ *
864
+ * For boss-style configured mobs (boss-solo, boss-brawl). Use
865
+ * `Actions.summonMultiple` for plain entities without stat overrides.
866
+ *
867
+ * @example A 60-HP fast-moving boss zombie:
868
+ * ```ts
869
+ * Actions.summonEntityWithStats({
870
+ * entity: "minecraft:zombie",
871
+ * x: 0, y: -60, z: 0, absolute: true,
872
+ * health: 60,
873
+ * attackDamage: 6,
874
+ * movementSpeed: 0.18,
875
+ * tags: ["boss"], // for `Actions.countEntities({ tag: "boss", … })`
876
+ * });
877
+ * ```
878
+ */
879
+ summonEntityWithStats: ({ entity, x, y, z, absolute, health, attackDamage, movementSpeed, tags, }) => {
880
+ const attributes = [];
881
+ if (health !== undefined)
882
+ attributes.push({ Name: "generic.max_health", Base: health });
883
+ if (attackDamage !== undefined)
884
+ attributes.push({ Name: "generic.attack_damage", Base: attackDamage });
885
+ if (movementSpeed !== undefined)
886
+ attributes.push({ Name: "generic.movement_speed", Base: movementSpeed });
887
+ const nbt = {};
888
+ if (health !== undefined)
889
+ nbt.Health = sandstone_1.NBT.float(health);
890
+ if (attributes.length > 0)
891
+ nbt.Attributes = attributes;
892
+ if (tags !== undefined && tags.length > 0)
893
+ nbt.Tags = tags;
894
+ const pos = absolute ? (0, sandstone_1.abs)(x, y, z) : (0, sandstone_1.rel)(x, y, z);
895
+ (0, sandstone_1.summon)(entity, pos, nbt);
896
+ },
897
+ /**
898
+ * Count entities matching any combination of `entity` type, `tag`, and/or
899
+ * `volume`, returning the count as an anonymous `Score`. At least one
900
+ * filter must be provided (counting "every entity in the world" is almost
901
+ * always a bug — guarded at runtime).
902
+ *
903
+ * Use this in a global custom_variable updater whose value tracks "how
904
+ * many Xs are currently in the world", e.g. boss alive (zombie count),
905
+ * chickens left, sheep in a pen.
906
+ *
907
+ * @param entity Optional entity type (e.g. `"minecraft:zombie"`).
908
+ * @param tag Optional tag filter (Minecraft `@e[tag=…]`). Used by e.g.
909
+ * boss-brawl, which counts zombies tagged `"boss"` to ignore wave-spawned mooks.
910
+ * @param volume Optional bounding box (Minecraft-style: corner + dx/dy/dz
911
+ * extents, absolute coords). Omit to count anywhere in the world.
912
+ * @returns {Score} An anonymous Score holding the count.
913
+ *
914
+ * @example boss_alive — counts zombies anywhere
915
+ * ```ts
916
+ * boss_alive: {
917
+ * type: "global",
918
+ * default: 1,
919
+ * updater: (value) => {
920
+ * value.set(Actions.countEntities({ entity: "minecraft:zombie" }));
921
+ * },
922
+ * }
923
+ * ```
924
+ *
925
+ * @example boss-brawl — count only the tagged boss zombies
926
+ * ```ts
927
+ * value.set(Actions.countEntities({ entity: "minecraft:zombie", tag: "boss" }));
928
+ * ```
929
+ *
930
+ * @example sheep_in_pen — counts sheep inside a 3×1×3 box
931
+ * ```ts
932
+ * value.set(Actions.countEntities({
933
+ * entity: "minecraft:sheep",
934
+ * volume: { x: 14, y: -59, z: -1, dx: 2, dy: 1, dz: 2 },
935
+ * }));
936
+ * ```
937
+ */
938
+ countEntities: ({ entity, tag, volume, }) => {
939
+ if (!entity && !tag && !volume) {
940
+ throw new Error("Actions.countEntities requires at least one of `entity`, `tag`, or `volume` — counting every entity in the world is almost always a bug.");
941
+ }
942
+ const result = (0, sandstone_1.Variable)(0);
943
+ const selectorParams = {};
944
+ if (entity)
945
+ selectorParams.type = entity;
946
+ if (tag)
947
+ selectorParams.tag = tag;
948
+ if (volume) {
949
+ selectorParams.x = volume.x;
950
+ selectorParams.y = volume.y;
951
+ selectorParams.z = volume.z;
952
+ selectorParams.dx = volume.dx;
953
+ selectorParams.dy = volume.dy;
954
+ selectorParams.dz = volume.dz;
955
+ }
956
+ sandstone_1.execute.as((0, sandstone_1.Selector)("@e", selectorParams)).run(() => {
957
+ result.add(1);
958
+ });
959
+ return result;
960
+ },
961
+ /**
962
+ * Build a flat open arena: a single-block-thick floor at `center.y` with
963
+ * cleared airspace above up to `headroom` blocks tall. The "no walls,
964
+ * just open ground for things to move on" pattern shared by sumo-arena,
965
+ * boss-brawl, wave-survival, stalker, and one half of defender-striker.
966
+ *
967
+ * For arenas with walls, use `Actions.box({ hollow: true, floor: … })`.
968
+ *
969
+ * @example
970
+ * Actions.flatArena({
971
+ * block: "minecraft:stone",
972
+ * center: { x: 0, y: -60, z: 0 },
973
+ * radius: 10, // 21×21 footprint
974
+ * headroom: 4, // 4 blocks of air above the floor (default 4)
975
+ * });
976
+ */
977
+ flatArena: ({ block, center, radius, headroom = 4, }) => {
978
+ const x_min = center.x - radius;
979
+ const x_max = center.x + radius;
980
+ const z_min = center.z - radius;
981
+ const z_max = center.z + radius;
982
+ // Floor at center.y.
983
+ (0, sandstone_1.fill)((0, sandstone_1.abs)(x_min, center.y, z_min), (0, sandstone_1.abs)(x_max, center.y, z_max), block);
984
+ // Clear air above (skip if headroom <= 0).
985
+ if (headroom > 0) {
986
+ (0, sandstone_1.fill)((0, sandstone_1.abs)(x_min, center.y + 1, z_min), (0, sandstone_1.abs)(x_max, center.y + headroom, z_max), "minecraft:air");
987
+ }
988
+ },
989
+ /**
990
+ * Apply a non-lethal knockback / displacement to a target via Minecraft's
991
+ * `effect` command. The default effect is a brief levitation (lifts the
992
+ * target straight up without dealing damage).
993
+ *
994
+ * Use `mode: "slowfall"` to combine levitation with slow falling so the
995
+ * target doesn't take fall damage on landing.
996
+ *
997
+ * @example
998
+ * // Periodic knockback in King-of-the-Hill style:
999
+ * Actions.knockbackWithLevitation({ target: "all", durationSeconds: 2, amplifier: 6 });
1000
+ *
1001
+ * // Knock with slow-fall for safe landing:
1002
+ * Actions.knockbackWithLevitation({ target: "self", mode: "slowfall", durationSeconds: 3 });
1003
+ */
1004
+ knockbackWithLevitation: ({ target, durationSeconds = 1, amplifier = 5, mode = "levitation", }) => {
1005
+ const t = mapTarget(target);
1006
+ sandstone_1.effect.give(t, "minecraft:levitation", durationSeconds, amplifier, true);
1007
+ if (mode === "slowfall") {
1008
+ // 8s of slow-falling — covers most levitation falls without damage.
1009
+ sandstone_1.effect.give(t, "minecraft:slow_falling", durationSeconds + 8, 0, true);
1010
+ }
1011
+ },
336
1012
  };
337
1013
  //# sourceMappingURL=actions.js.map