diff --git "a/environments/games/prototype/bossbench/mc4d.py" "b/environments/games/prototype/bossbench/mc4d.py" new file mode 100644--- /dev/null +++ "b/environments/games/prototype/bossbench/mc4d.py" @@ -0,0 +1,2346 @@ +"""3D Minecraft 1v1 v2: one voxel arena, seven boss cases, one shared rig. + + 3d/minecraft_iron_golem ground melee: telegraphed slam that flings, knockback immune, walks around walls + 3d/minecraft_zombie fast light melee, relentless pressure (legacy case) + 3d/minecraft_ender_dragon aerial phases: circling, fireball strafes, perching with breath; healing end crystals + 3d/minecraft_wither hovering artillery: three heads of skulls, spawn blast, arrow-proof armor at half health + 3d/minecraft_warden blind juggernaut of the deep dark: crushing melee, darkness, a sonic boom for out-of-reach + targets that ignores armor and walls + 3d/minecraft_skeleton strafing archer: telegraphed bow draws, inaccurate arrows, line of sight behind ruins + 3d/minecraft_zombie_leader a leader zombie whose hits call reinforcements: a horde to manage at night + +Rules stay on the Java-edition numbers the prototype already used (attack cooldown multiplier, +crit conditions, 10-tick hurt immunity, armor, mob melee reach, knockback, mob auto-jump, fall +damage, friction/gravity). Those numbers are per vanilla tick (20 Hz): TABLE speeds are blocks/tick, +cooldowns are ticks. The simulation runs at core.FPS (60 Hz) and converts at use (per_vt / ticks / decay / +gain below), so a fight lasts the same seconds and covers the same blocks at any tick rate. Every knob is interpolated by the single scalar d, and every boss runs +the same 4-state machine so the observation vector keeps one layout across mobs. + +Rendering is a skin: boxes come from bossbench.rig, which the simulation poses once per tick; +textures, per-state poses, particles, renderer and HUD all live in bossbench.mcskin. + +Replay compatibility is tracked by the RULES identifier. +""" +from __future__ import annotations + +import math + +import gymnasium as gym +import numpy as np + +from .core import FPS, RES, Arena, Body, Boss, BossBenchEnv, Case +from . import mcskin +from .rig import Rigged + +RULES = "minecraft-arena@7" +# Public difficulty tiers: every TABLE row below is (easy, normal, hard), so a tier +# reads exactly one knot of each row. The continuous d in [0, 1] still interpolates between them for fine control. +TIERS = {"easy": 0.0, "normal": 0.5, "hard": 1.0} +S = 34 # arena side in blocks +MID = S / 2 # arena centre line (z of both spawns) +AREA_K = (S - 2) ** 2 / 22 ** 2 # obstacle counts scale with floor area so density matches the 24 layout +VT = 20 / FPS # one simulation tick in vanilla Minecraft ticks +TURNS = np.radians([-30, -10, 0, 10, 30]) * VT # native turn action, per vanilla tick + + +def per_vt(x): + """A per-vanilla-tick velocity, step or rate -> per simulation tick.""" + return x * VT + + +def ticks(n): + """A duration in vanilla ticks -> simulation ticks.""" + return int(round(n / VT)) + + +def decay(f): + """A per-vanilla-tick multiplier (friction, drag) -> per simulation tick, same decay per second.""" + return f ** VT + + +def push(v, f): + """A one-off vanilla impulse (b/t) decaying under per-vanilla-tick friction f -> the per-sim-tick + impulse that carries the body the same distance.""" + F = decay(f) + return v * f / (1 - f) * (1 - F) / F + + +def gain(k): + """A per-vanilla-tick approach fraction (lerp toward a target) -> per simulation tick.""" + return 1 - (1 - k) ** VT + + +# Per simulation tick, chosen so that every third 60 Hz tick lands exactly on the vanilla 20 Hz trajectory: +# ground friction keeps vanilla's terminal speed (= accel b/t) and time constant, air drag keeps the terminal +# 0.02 / 0.09 b/t, gravity the terminal fall 3.92 b/t. +GROUND_F, AIR_F, FALL_F = decay(0.546), decay(0.91), decay(0.98) +AIR_A = 0.02 / 0.09 * (1 - AIR_F) * VT +V_FALL = -0.08 * 0.98 / 0.02 # vanilla terminal fall speed (b/t) +GRAVITY = -V_FALL * VT * (1 - FALL_F) / FALL_F + + +def vy_sim(v): + """A vanilla vertical velocity set at a tick (jump, fling) -> the sim-tick value giving the same arc.""" + return V_FALL * VT + (v - V_FALL) * (1 - FALL_F) / (1 - 0.98) + + +def vy_vanilla(u): + """Inverse of vy_sim.""" + return V_FALL + (u - V_FALL * VT) * (1 - 0.98) / (1 - FALL_F) + + +JUMP = vy_sim(0.42) +# sprint-jump boost: vanilla decays it once by ground friction (the take-off tick), then by air drag; +# the sim value travels the same distance under one sim tick of ground friction, then air drag +SPRINT_JUMP = 0.2 * 0.546 / (1 - 0.91) * (1 - AIR_F) / GROUND_F +PLAYER_W, PLAYER_H, EYE = 0.6, 1.8, 1.62 +PLAYER_REACH = 3.0 +WALL_CAP = 8 +# SPEED_NOTE (minecraft-arena@5): a Java mob's ground speed scales with the *square* of (movement_speed attribute x its +# goal's speed modifier): MoveControl sets the forward input to that value and LivingEntity.travel scales the input by the +# same speed again; the player's input is 0.98 at attribute 0.1. Relative to the walking player (0.216 b/t here): +# v = 0.216 x (attribute x modifier)^2 / 0.098. Zombie 0.23 -> 0.117 b/t (2.3 m/s, the commonly measured value), +# skeleton 0.25 -> 0.138, warden 0.3 x its 1.2 fight modifier -> 0.286 (a sprinting player's 0.281: it cannot be +# outrun). The new scenes use these (the leader zombie 0.117); the @4 bosses, the formal zombie included, keep their +# tuned values. + +WEAPONS = ('sword', 'bow') +BOW_RULES = { + 'version': 'bossbench/minecraft-bow@2', + 'draw_seconds': 1.0, 'minimum_power': 0.1, + 'maximum_speed_blocks_per_vanilla_tick': 3.0, + 'gravity_blocks_per_vanilla_tick_squared': 0.05, + 'drag_per_vanilla_tick': 0.99, 'base_damage_per_speed': 2.0, + 'maximum_life_seconds': 60.0, 'ammunition': 'unlimited', + 'aim_assist': False, 'arrow_radius_blocks': 0.025, +} + + +def _weapon(value): + if not isinstance(value, str) or value not in WEAPONS: + raise ValueError(f'weapon must be one of {WEAPONS}, got {value!r}') + return value + + +def _camera(value): + if value not in ('first', 'third'): + raise ValueError("camera must be 'first' or 'third'") + return value + + +def _segment_box(start, end, low, high): + """First intersection fraction of a swept arrow segment and an AABB.""" + lower, upper = 0.0, 1.0 + direction = end - start + for axis in range(3): + if abs(direction[axis]) < 1e-12: + if start[axis] < low[axis] or start[axis] > high[axis]: + return None + continue + a = (low[axis] - start[axis]) / direction[axis] + b = (high[axis] - start[axis]) / direction[axis] + lower, upper = max(lower, min(a, b)), min(upper, max(a, b)) + if lower > upper: + return None + return lower + + +class Entity: + def __init__(self, x, y, z, yaw, w, h): + self.pos, self.vel = np.array([x, y, z], float), np.zeros(3) + self.yaw, self.w, self.h, self.on_ground, self.fall_from = yaw, w, h, True, 0.0 + self.pitch = 0.0 # bow aiming; positive pitch looks up + + @property + def fwd(self): + return np.array([math.cos(self.yaw), 0.0, math.sin(self.yaw)]) + + @property + def right(self): + return np.array([-math.sin(self.yaw), 0.0, math.cos(self.yaw)]) + + +# ---------------------------------------------------------------- arena +class VoxelArena(Arena): + """Layouts. 'field' is the ground fight (low cover, one climbable pillar); 'towers' adds tall columns so an aerial + boss can be broken off and its line of sight cut. minecraft-arena@5 adds three themed layouts that draw the field's + cover first (same random stream, so a seed gives the same base layout) and then their own pieces: + 'night' (no extra pieces: the field at night, for the leader zombie and its reinforcements), 'deep_dark' + (deepslate pillars 3-4 high: tempting perches that the warden answers with its sonic boom) and 'ruins' + (broken stone-brick walls 2-3 high that stop arrows both ways: cover for a bow duel).""" + TABLE = {"cover_clusters": (8, 5, 2), # 1-high blocks: jumpable, block a ground mob's path + "safe_pillars": (2, 1, 0), # 3-high pillars: the classic "pillar up" cheese + "towers": (2, 3, 4), # tall columns, towers layout only + "dark_pillars": (3, 3, 3), # deep_dark only (minecraft-arena@5) + "ruin_walls": (6, 6, 6)} # ruins only (minecraft-arena@5) + + def __init__(self, style="field"): + self.style = style + + def reset(self, case): + super().reset(case) + rng, H = case.rng, np.zeros((S, S), np.int8) + H[0, :] = H[-1, :] = H[:, 0] = H[:, -1] = WALL_CAP # arena wall + for _ in range(int(round(self.k.cover_clusters * AREA_K))): + x, z = rng.integers(3, S - 4, 2) + H[x:x + rng.integers(1, 3), z:z + rng.integers(1, 3)] = 1 + for _ in range(int(round(self.k.safe_pillars * AREA_K))): + x, z = rng.integers(4, S - 4, 2) + H[x, z] = 3 + H[x + 1, z] = max(H[x + 1, z], 1) + H[x + 1, z + 1] = max(H[x + 1, z + 1], 2) + if self.style == "towers": + for _ in range(int(round(self.k.towers * AREA_K))): + x, z = rng.integers(3, S - 5, 2) + H[x, z] = 4 + int(rng.integers(0, 3)) + H[x, z + 1] = max(H[x, z + 1], 1) + H[x + 1, z] = max(H[x + 1, z], int(H[x, z]) - 1) + elif self.style == "deep_dark": + for _ in range(int(round(self.k.dark_pillars * AREA_K))): + x, z = (int(v) for v in rng.integers(5, S - 5, 2)) + h = 3 + int(rng.integers(0, 2)) + H[x:x + 2, z:z + 2] = h # 2x2 deepslate column + for i in range(1, h): # a staircase: the top can be reached + H[x - i, z] = max(H[x - i, z], h - i) + elif self.style == "ruins": + for _ in range(int(round(self.k.ruin_walls * AREA_K))): + x, z = (int(v) for v in rng.integers(4, S - 9, 2)) + n, h = int(rng.integers(3, 7)), 2 + int(rng.integers(0, 2)) + gap = int(rng.integers(1, n - 1)) # a breach somewhere along the wall + for i in range(n): + if i == gap: + continue + if rng.random() < 0.5: + H[x + i, z] = max(H[x + i, z], h) + else: + H[x, z + i] = max(H[x, z + i], h) + m = int(MID) + H[m - 8:m - 3, m - 2:m + 2] = H[m + 3:m + 8, m - 2:m + 2] = 0 # spawn pads + self.H = H + + def ground(self, p, w): + h = w / 2 - 1e-6 + x0, x1, z0, z1 = int(p[0] - h), int(p[0] + h), int(p[2] - h), int(p[2] + h) + if p[0] - h < 0 or p[2] - h < 0 or x1 >= S or z1 >= S: + return 99.0 + return float(self.H[x0:x1 + 1, z0:z1 + 1].max()) + + def los(self, a, b, eye_h=1.5): + """Coarse line of sight: sampled columns between two entity centres.""" + a, b = np.asarray(a, float), np.asarray(b, float) + n = min(int(np.hypot(*(b - a)[[0, 2]]) * 2) + 1, 32) + for u in np.linspace(0.06, 0.94, n): + p = a + (b - a) * u + ix, iz = int(p[0]), int(p[2]) + if not (0 <= ix < S and 0 <= iz < S): + continue + if self.H[ix, iz] > p[1] + eye_h: + return False + return True + + +def physics(case, e, wish, accel, step=0.6, vertical=True): + """Minecraft-style integration: ground friction 0.546, air drag 0.91, gravity (per vanilla tick, converted + to the simulation tick); per-axis collision. accel is the vanilla walk speed in b/t; e.vel is per sim tick.""" + A = case.arena + if e.on_ground: + e.vel[[0, 2]] = e.vel[[0, 2]] * GROUND_F + wish[[0, 2]] * per_vt(accel) * (1 - GROUND_F) + else: + e.vel[[0, 2]] = e.vel[[0, 2]] * AIR_F + wish[[0, 2]] * AIR_A + blocked = False + for ax in (0, 2): + new = e.pos.copy() + new[ax] += e.vel[ax] + if A.ground(new, e.w) > e.pos[1] + step: + e.vel[ax], blocked = 0.0, True + else: + e.pos = new + landed_from = None + if not vertical: + return blocked, landed_from + e.pos[1] += e.vel[1] + e.vel[1] = (e.vel[1] - GRAVITY) * FALL_F + g = A.ground(e.pos, e.w) + if e.pos[1] <= g: + if not e.on_ground: + landed_from = e.fall_from - g + e.pos[1], e.vel[1], e.on_ground = g, 0.0, True + e.fall_from = g + else: + if e.on_ground: + e.fall_from = e.pos[1] + e.fall_from = max(e.fall_from, e.pos[1]) + e.on_ground = False + return blocked, landed_from + + +def armor_reduce(dmg, armor, tough): + return dmg * (1 - min(20.0, max(armor / 5, armor - 4 * dmg / (tough + 8))) / 25) + + +# ---------------------------------------------------------------- ground navigation (minecraft-arena@4) +# Pure functions of the arena heights, cached by their bytes: shared by every clone the scripted controller makes +# and by the live case, so a lookahead never pays twice for the same field. +_NAV_CACHE: dict = {} +_STEPS = ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)) + + +def _cached(key, make): + hit = _NAV_CACHE.get(key) + if hit is None: + if len(_NAV_CACHE) > 512: + _NAV_CACHE.clear() + hit = _NAV_CACHE[key] = make() + return hit + + +def nav_free(H, r, step): + """Cells whose centre a mob of grid radius r (0: 0.6 wide, 1: 1.4 wide) can stand on: no column taller than + `step` (the auto-jump height) within r cells, and not the arena wall.""" + def make(): + wall = H > step + grown = wall.copy() + for dx in range(-r, r + 1): + for dz in range(-r, r + 1): + grown |= np.roll(np.roll(wall, dx, 0), dz, 1) + grown[[0, -1], :] = True + grown[:, [0, -1]] = True + return ~grown + return _cached(("free", H.tobytes(), r, step), make) + + +def _steps(free, cell): + """8-connected moves from cell onto free cells, without cutting a wall corner.""" + x, z = cell + for dx, dz in _STEPS: + a, b = x + dx, z + dz + if not (0 < a < S - 1 and 0 < b < S - 1) or not free[a, b]: + continue + if dx and dz and not (free[x + dx, z] and free[x, z + dz]): + continue + yield a, b + + +def nav_field(H, r, step, goal): + """Breadth-first step counts from every free cell to the goal cell (10**6 where unreachable).""" + def make(): + free = nav_free(H, r, step) + dist = np.full(free.shape, 10 ** 6, np.int32) + dist[goal] = 0 + frontier, n = [goal], 0 + while frontier: + n += 1 + nxt = [] + for cell in frontier: + for a, b in _steps(free, cell): + if dist[a, b] > n: + dist[a, b] = n + nxt.append((a, b)) + frontier = nxt + return dist + return _cached(("field", H.tobytes(), r, step, goal), make) + + +def _walkable(free, start, seg, own, goal): + """True when every cell the straight segment crosses (except the two end cells) is free.""" + length = math.hypot(seg[0], seg[2]) + k = int(length / 0.35) + 2 + x0, z0, sx, sz = float(start[0]), float(start[2]), float(seg[0]) / (k - 1), float(seg[2]) / (k - 1) + for i in range(1, k - 1): + c = (min(max(int(x0 + sx * i), 0), S - 1), min(max(int(z0 + sz * i), 0), S - 1)) + if c != own and c != goal and not free[c]: + return False + return True + + +# ---------------------------------------------------------------- body +# The player's loadout is part of a scene, identical on every tier (minecraft-arena@5): (sword attack damage, armor points, +# armor toughness). Diamond against the end-game bosses (iron golem, ender dragon, wither, warden) and on the formal +# zombie case (its @4 kit), iron against the overworld night mobs (leader zombie horde, skeleton archer): Java iron +# sword 6, iron armor 15 / 0; diamond sword 7, 20 / 8. +KITS = {"diamond": (7.0, 20.0, 8.0), "iron": (6.0, 15.0, 0.0)} +SCENE_KIT = {"iron_golem": "diamond", "zombie": "diamond", "ender_dragon": "diamond", "wither": "diamond", + "warden": "diamond", "skeleton": "iron", "zombie_leader": "iron"} + + +class Steve(Body, Rigged): + # One fixed loadout per scene on every tier (only the boss scales with the tier): the TABLE is the @4 diamond kit, + # replaced at reset by the scene's KITS entry (identical floats for the diamond scenes). + TABLE = {"sword_dmg": (7, 7, 7), + "armor": (20, 20, 20), + "toughness": (8, 8, 8)} + MOVES = ("none", "forward", "back", "left", "right") + action_space = gym.spaces.MultiDiscrete([5, 5, 2, 2, 2]) # move, turn, jump, attack, sprint + max_hp = 20.0 + T_ATTACK = FPS / 1.6 # ticks to a full attack charge (sword attack speed 1.6 -> 12.5 vanilla ticks) + T_FIST = FPS / 4.0 # empty hand / bow in hand: attack speed 4 -> 5 vanilla ticks + CRIT_CHARGE = 0.9 # Java: f2 > 0.9, i.e. the 84.8 % damage multiplier + HOTBAR = ('sword', 'bow') + + def __init__(self, weapon='sword'): + self.weapon = _weapon(weapon) + self.rig = None + self.ph = 0.0 + + def reset(self, case): + super().reset(case) + self.kit = SCENE_KIT.get(getattr(case, "mob_name", ""), "diamond") + self.k.sword_dmg, self.k.armor, self.k.toughness = KITS[self.kit] + self.e = Entity(MID - 5.5, 0.0, MID, 0.0, PLAYER_W, PLAYER_H) + self.hp, self.since_swing, self.iframes, self.sprinting = self.max_hp, 5 * FPS, 0, False + self.last_hurt, self.wither_t = 0.0, 0 + self.ph, self.swing_t = 0.0, -5 * FPS + self.bow_draw_ticks, self.bow_drawing = 0, False + self.arrows_fired, self.arrows_hit, self.arrow_damage = 0, 0, 0.0 + self.wheel, self.notches, self.switches, self.melee_damage = 0.0, 0, 0, 0.0 + self._build_rig() + + # -- rig --------------------------------------------------------------- + def _build_rig(self): + self.rig = mcskin.steve_rig() + + def pose(self, case): + mcskin.pose_steve(self, case) + + def noop(self): + return np.array([0, 2, 0, 0, 0]) + + MOUSE_DEG = 0.15 # camera yaw/pitch per mouse unit (dx = 200 in one packet turns 30 deg) + MANUAL = ( + "W forward, S back, A strafe left, D strafe right (one direction at a time; W > S > A > D)", + "mouse dx turns right and dy looks down, 0.15 deg per unit (dx 200 = 30 deg); pitch is limited to +-89 deg; " + "there is no aim assist for any weapon (since rules minecraft-arena@2)", + "Space jump (while held, whenever on the ground); Shift sprint (only while holding W)", + "hotbar: slot 1 sword (diamond against the end-game bosses, iron against the night mobs), slot 2 bow; mouse " + "wheel dz switches slots (each notch one slot); " + "switching resets the attack cooldown and cancels a bow draw", + "sword in hand: LMB or J swings once per press, 3 blocks reach along the view ray; damage scales with the " + "attack-cooldown charge (1.6 swings/s); a falling hit with charge > 90 %, not sprinting, is a crit (x1.5); " + "a sprinting hit at > 90 % adds knockback", + "bow in hand: hold RMB to draw across packets, release to fire (1 s = full draw, critical arrow); drawing " + "slows movement and stops sprinting; arrows fall with gravity and stop on terrain; LMB/J punch for 1", + "every hit gives 10 vanilla ticks (0.5 s) of damage immunity; a stronger hit inside it deals only the difference", + ) + SWORD_MANUAL = MANUAL # kept for older imports + + @property + def manual(self): + return self.MANUAL + + def keys(self, case, held, pressed, mouse): + self.e.yaw = (self.e.yaw + math.radians(mouse[0] * self.MOUSE_DEG)) % (2 * math.pi) + self.e.pitch = float(np.clip(self.e.pitch - math.radians(mouse[1] * self.MOUSE_DEG), + math.radians(-89), math.radians(89))) + if len(mouse) > 2 and mouse[2]: + # The packet's wheel motion is spread over its ticks; a notch lands on the first tick that starts it. + self.wheel += mouse[2] + a = self.wheel + target = math.ceil(a - 1e-6) if a > 1e-6 else (-math.ceil(-a - 1e-6) if a < -1e-6 else 0) + while self.notches != target: + step = 1 if target > self.notches else -1 + self.notches += step + self.select(case, self.HOTBAR[(self.HOTBAR.index(self.weapon) + step) % len(self.HOTBAR)]) + move = next((i for i, k in ((1, "W"), (2, "S"), (3, "A"), (4, "D")) if k in held), 0) + swing = bool(pressed & {"LMB", "J"}) + if self.weapon == 'bow': + return np.array([move, 2, "Space" in held, 'RMB' in held, "Shift" in held, swing]) + return np.array([move, 2, "Space" in held, swing, "Shift" in held, 0]) + + def select(self, case, weapon): + """Hotbar switch: Java resets the attack strength ticker whenever the held item changes.""" + if weapon == self.weapon: + return + if self.bow_drawing: + case.events.append('bow_cancel') + self.weapon, self.since_swing = weapon, 0 + self.bow_drawing, self.bow_draw_ticks = False, 0 + self.switches += 1 + case.events.append(('hotbar', weapon)) + + def parse(self, text): + w = set(text.lower().replace(",", "+").replace(" ", "+").split("+")) + move = next((i for i, m in enumerate(self.MOVES) if m in w), 0) + turn = 0 if "turn_left_big" in w else 1 if "turn_left" in w else 4 if "turn_right_big" in w else \ + 3 if "turn_right" in w else 2 + return np.array([move, turn, "jump" in w, "attack" in w, "sprint" in w]) + + @property + def attack_charge(self): + """Java attack strength scale f2 = clamp((t + 0.5) / T) for the item in hand.""" + return min(1.0, (self.since_swing + 0.5) / (self.T_ATTACK if self.weapon == 'sword' else self.T_FIST)) + + @property + def charge(self): + if self.weapon == 'bow': + return self.bow_charge + return self.attack_charge + + @property + def bow_charge(self): + return min(1.0, self.bow_draw_ticks / (FPS * BOW_RULES['draw_seconds'])) + + def apply(self, case, action): + move, turn, jump, attack, sprint = (int(a) for a in action[:5]) + punch = len(action) > 5 and bool(action[5]) + e = self.e + self.iframes, self.since_swing = max(self.iframes - 1, 0), self.since_swing + 1 + e.yaw = (e.yaw + TURNS[turn]) % (2 * math.pi) + wish = {0: 0 * e.fwd, 1: e.fwd, 2: -e.fwd, 3: -e.right, 4: e.right}[move] + drawing = self.weapon == 'bow' and bool(attack) + self.sprinting = bool(sprint) and move == 1 and not drawing + if jump and e.on_ground: + e.vel[1] = JUMP + if self.sprinting: + e.vel += e.fwd * SPRINT_JUMP + speed = 0.281 if self.sprinting else 0.216 + if drawing: + wish = wish * 0.2 + _, fell = physics(case, e, wish, speed) + if fell and fell > 3: + case.hurt_player(fell - 3, armor=False) + case.events.append("fall_damage") + if self.wither_t > 0: # Wither II: 1 damage per 20 vanilla ticks, ignores armor + self.wither_t -= 1 + if self.wither_t % ticks(20) == 0: + case.hurt_player(1.0, armor=False) + case.events.append("wither_effect") + if self.weapon == 'bow': + self._update_bow(case, bool(attack)) + if punch: + self._swing(case) + elif attack: + self._swing(case) + + def _update_bow(self, case, held): + if held: + if not self.bow_drawing: + case.events.append('bow_draw') + self.bow_drawing = True + self.bow_draw_ticks += 1 + return + if not self.bow_drawing: + return + charge = self.bow_charge + power = min(1.0, (charge * charge + 2.0 * charge) / 3.0) + self.bow_drawing, self.bow_draw_ticks = False, 0 + if power < BOW_RULES['minimum_power']: + case.events.append('bow_cancel') + return + e = self.e + direction = self.look() + speed = BOW_RULES['maximum_speed_blocks_per_vanilla_tick'] * power + self.arrows_fired += 1 + case.arrows.append({'id': self.arrows_fired, + 'pos': e.pos + [0, EYE, 0] + direction * 0.1, + 'vel': direction * per_vt(speed), 'age': 0, + 'damage': float(math.ceil(speed * BOW_RULES['base_damage_per_speed'])), + 'critical': power >= 1.0}) + case.events.append(('bow_release', self.arrows_fired, round(power, 4))) + + def look(self): + e = self.e + return np.array([math.cos(e.yaw) * math.cos(e.pitch), math.sin(e.pitch), + math.sin(e.yaw) * math.cos(e.pitch)]) + + def ray_hit(self, case): + """Nearest target box along the view ray within the 3 block attack range: (distance, kind, payload) or + None. Terrain in front of the target blocks the swing.""" + eye = self.e.pos + [0, EYE, 0] + ray = self.look() + best = None + for kind, lo, hi, payload in case._targets(): + with np.errstate(divide="ignore", invalid="ignore"): + t1, t2 = (lo - eye) / ray, (hi - eye) / ray + tn, tf = np.nanmax(np.minimum(t1, t2)), np.nanmin(np.maximum(t1, t2)) + if tn <= tf and tf >= 0 and tn <= PLAYER_REACH and (best is None or tn < best[0]): + best = (max(float(tn), 0.0), kind, payload) + if best is not None and best[0] > 0.05: + wall, _ = case._arrow_world_hit(eye, eye + ray * best[0]) + if wall is not None and wall < 0.999: + return None + return best + + def _swing(self, case): + """Ray vs the mob hitbox along the player's own yaw and pitch (no aim assist since minecraft-arena@2).""" + g, e = case.boss, self.e + charge, self.since_swing = self.attack_charge, 0 + self.swing_t = case.t + target = self.ray_hit(case) + if target is None: + case.events.append("miss") + return + base = self.k.sword_dmg if self.weapon == 'sword' else 1.0 + mult = 0.2 + min(charge, 1.0) ** 2 * 0.8 + strong = charge > self.CRIT_CHARGE + living = target[1] in ("boss", "minion") and not hasattr(g, "hitboxes") # Java: crits need a LivingEntity + crit = strong and living and not e.on_ground and e.vel[1] < 0 and not self.sprinting + sprint_hit = strong and self.sprinting + dmg = base * mult * (1.5 if crit else 1.0) + self.melee_damage += case._damage(target[1], target[2], dmg, "crit" if crit else "normal", + bonus_knockback=0.5 if sprint_hit else 0.0) + if sprint_hit: # Java: the attacker stops sprinting, keeps 60 % speed + e.vel[[0, 2]] *= 0.6 + self.sprinting = False + case.events.append("sprint_hit") + + +# ---------------------------------------------------------------- mobs +class Mob(Boss, Rigged): + """Shared machinery: hitboxes, knockback, hit flash, hit posing, rig bookkeeping.""" + STATES = ("chase", "windup", "swing", "recover") + aim_h = 1.35 # where the player's aim assist points + half = (0.7, 0.7) # hitbox half extents in x/z + knockback = 1.0 # 0 = knockback immune (vanilla iron golem) + hover = False + armor = 0.0 # natural armor points (Java: zombie 2, wither 4) + hit_event = "boss_hit" # event name a landed hit records ("minion_hit" for zombie reinforcements, @5) + last_hurt = 0.0 + + def __init__(self): + self.rig = None + self.tint_t = 0 + + def reset(self, case): + super().reset(case) + self._steer_t, self._steer_dir = -9, np.zeros(3) # steer() memo: last vanilla-tick plan + + # -- geometry ---------------------------------------------------------- + def hit_lo(self): + return self.e.pos - [self.half[0], 0.0 if not self.hover else 0.75, self.half[1]] + + def hit_hi(self): + return self.e.pos + [self.half[0], self.height if not self.hover else -0.75, self.half[1]] + + def dist_to(self, case): + return case.body.e.pos - self.e.pos + + ATTACK_INFLATE = math.sqrt(2.04) - 0.6 # Java 1.20.2+: attack box = collision box + 0.828 horizontally + + def in_reach(self, case): + """Java 1.20.2+ mob melee: the collision box expanded horizontally by 0.828 must intersect the + target's box, with line of sight (no hits through walls). Replaces the pre-1.20.2 reach^2 test.""" + p, r = case.body.e, self.ATTACK_INFLATE + lo = self.e.pos - [self.half[0] + r, 0.0, self.half[1] + r] + hi = self.e.pos + [self.half[0] + r, self.height, self.half[1] + r] + plo, phi = p.pos - [PLAYER_W / 2, 0.0, PLAYER_W / 2], p.pos + [PLAYER_W / 2, PLAYER_H, PLAYER_W / 2] + if not (np.all(lo <= phi) and np.all(plo <= hi)): + return False + return case.arena.los(self.e.pos + [0, 1.0, 0], p.pos + [0, 1.0, 0], eye_h=0.0) + + def immune(self, case, kind): + """Hits this mob ignores outright (wither spawn charge, wither armor vs arrows).""" + return False + + # -- ground pathing (minecraft-arena@4) ---------------------------------------------------------------- + NAV_STEP = 1 # columns up to this height are walkable (auto-jump); taller ones are walls + + def steer(self, case): + """Unit xz walking direction toward the player. Straight while the line to the player is walkable (Java + mobs walk at a visible target); around walls along the step field otherwise (Java mobs path-find; without it + a pillar between the two pinned the mob in place forever: a soft-lock, found 2026-11-02). Re-planned once + per vanilla tick, like Java's 20 Hz mob AI; the two sim ticks in between keep the last direction.""" + if case.t % 3 and case.t - 2 <= getattr(self, "_steer_t", -9) <= case.t: + return self._steer_dir + self._steer_t, self._steer_dir = case.t, self._plan_steer(case) + return self._steer_dir + + def _plan_steer(self, case): + e, p = self.e, case.body.e + to = p.pos - e.pos + to[1] = 0.0 + n = math.hypot(to[0], to[2]) + if n < 1e-6: + return to + H = case.arena.H + r = int(math.ceil(self.half[0] - 0.5 - 1e-9)) + free = nav_free(H, r, self.NAV_STEP) + own = (int(e.pos[0]), int(e.pos[2])) + goal = (min(max(int(p.pos[0]), 1), S - 2), min(max(int(p.pos[2]), 1), S - 2)) + if _walkable(free, e.pos, to, own, goal): + return to / n + dist = nav_field(H, r, self.NAV_STEP, goal) + cell, path = own, [] + for _ in range(4): # follow the field downhill a few cells + here = dist[cell] if free[cell] else 10 ** 6 + best = None + for a, b in _steps(free, cell): + if dist[a, b] < here and (best is None or dist[a, b] < dist[best]): + best = (a, b) + if best is None: + break + path.append(best) + cell = best + if dist[cell] == 0: + break + if not path: + return to / n # nowhere better: lean on the wall toward the target + aim = np.array([path[0][0] + 0.5, 0.0, path[0][1] + 0.5]) + for c in reversed(path[1:]): # string-pull to the farthest cell in a straight line + target = np.array([c[0] + 0.5, 0.0, c[1] + 0.5]) + seg = target - e.pos + seg[1] = 0.0 + if _walkable(free, e.pos, seg, own, c): + aim = target + break + d = aim - e.pos + d[1] = 0.0 + return d / (float(np.linalg.norm(d)) + 1e-9) + + def on_hurt(self, case, amount, kind): + pass + + def take_hit(self, case, dmg, kind="normal", bonus_knockback=0.0): + """Java LivingEntity.hurt: a hit starts 10 vanilla ticks of immunity; inside the window only a stronger + hit lands and deals the difference (no knockback, no new window). Armor applies to what lands.""" + if self.immune(case, kind): + case.events.append(("boss_immune", kind)) + return 0.0 + fresh = self.iframes <= 0 + if fresh: + amount, self.last_hurt = dmg, dmg + self.iframes = ticks(10) + self.tint_t = ticks(8) + elif dmg > self.last_hurt: + amount, self.last_hurt = dmg - self.last_hurt, dmg + else: + return 0.0 + if self.armor: + amount = armor_reduce(amount, self.armor, 0.0) + amount = amount * (1.0 - float(getattr(self, "guard", 0.0))) + self.hp -= amount + if fresh and self.knockback > 0 and not self.hover: + d = self.e.pos - case.body.e.pos + n = float(np.linalg.norm(d[[0, 2]])) + 1e-6 + self.e.vel[[0, 2]] += d[[0, 2]] / n * push(0.4 + bonus_knockback, 0.546) * self.knockback + case.events.append((self.hit_event, round(amount, 2), kind)) + self.on_hurt(case, amount, kind) + return amount + + def hurt_player(self, case, dmg, fling=0.0, iframes=True, share=1.0, armor=True, origin=None, lift=0.0): + """Damage the player; a fresh (non-immune) hit knocks the player away from origin (default: this mob). + Java knockback: horizontal velocity halved plus the push; on the ground vy = min(0.4, vy / 2 + 0.4); + lift adds the iron golem's extra +0.4 b/t launch.""" + p = case.body.e + landed = case.hurt_player(dmg, armor=armor, iframes=iframes, share=share) + if not landed: + return False + if fling and landed == "fresh": + d = p.pos - (self.e.pos if origin is None else np.asarray(origin, float)) + n = float(np.linalg.norm(d[[0, 2]])) + 1e-6 + p.vel[[0, 2]] = p.vel[[0, 2]] / 2 + d[[0, 2]] / n * push(fling, 0.546 if self.hover else 0.91) + if not self.hover or lift: + p.vel[1] = vy_sim(min(0.4, vy_vanilla(p.vel[1]) / 2 + 0.4) + lift) + p.on_ground = False + return True + + # -- rig --------------------------------------------------------------- + def rigs(self): + return [self.rig] if self.rig is not None else [] + + def extra(self, case): + """Transient hazard visuals owned by the simulation (skulls), drawn as world-axis boxes.""" + return [] + + def fx(self, case): + """Particle visuals. Uses case.fxrng, never case.rng: rendering must not consume the + gameplay random stream.""" + return [] + + +class IronGolem(Mob): + TABLE = { # (easy, normal, hard) = TIERS + "hp": (380, 1000, 2700), # TIER calibration for ~25 s / 1 min / 3 min (Java: 100 on every difficulty) + "speed": (0.11, 0.13, 0.15), # vanilla b/t chase, below the player's 0.216 walk (Java ~0.14) + "dmg_min": (4.75, 7.5, 11.25), # Java easy / normal / hard + "dmg_max": (11.75, 21.5, 32.25), + "cooldown": (30, 24, 20), # vanilla ticks between slams (Java 20) + "windup": (0.60, 0.45, 0.35), # EXT seconds of raised arms before the hit + "jitter": (0.0, 0.05, 0.10), # EXT tempo variance + } + MOVES = {"swing": {"atoms": ["melee_area", "grab/fling"], "telegraph": "both arms raised", + "damage": "U[dmg_min, dmg_max] then armor", "range": "reach^2=(2*1.4)^2+0.6", + "punish": "cooldown (vanilla ticks) after each swing; cannot reach targets >=2.75 above"}} + SKILLS = ("spacing", "attack_timing", "crit_jump", "kiting", "terrain_use", "reaction") + name = "iron_golem" + height, aim_h, reach, reach_up = 2.7, 1.35, 2.9, 2.75 + half = (0.7, 0.7) + knockback = 0.0 + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.e = Entity(MID + 5.5, 0.0, MID, math.pi, 1.4, self.height) + self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0 + self.ph, self.tint_t, self.arm = 0.0, 0, 0.0 + self.rig = golem_rig() + + @property + def enraged(self): + return False # the @1-@3 below-half-HP enrage is not Java; dropped in @4 + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0) + self.tint_t = max(self.tint_t - 1, 0) + self.timer -= 1 / FPS + to = p.pos - e.pos + wish = self.steer(case) + e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw + speed = k.speed + if self.state == "chase": + if self.cd == 0 and self.in_reach(case): + self.state = "windup" + self.timer = max(0.05, k.windup + case.rng.uniform(-k.jitter, k.jitter)) + case.events.append("golem_windup") + elif self.state == "windup": + speed *= 0.3 + if self.timer <= 0: + self.state, self.timer = "swing", 0.15 + if self.in_reach(case): + if self.hurt_player(case, case.rng.uniform(k.dmg_min, k.dmg_max), fling=0.4, lift=0.4): + case.events.append(("golem_hit",)) + else: + case.events.append("golem_whiff") + elif self.state == "swing": + speed = 0.0 + if self.timer <= 0: + self.state, self.cd = "recover", ticks(k.cooldown) + elif self.state == "recover" and self.cd == 0: + self.state = "chase" + if np.hypot(to[0], to[2]) < 0.75: + wish = 0 * wish + blocked, _ = physics(case, e, wish, speed, step=0.0) + if blocked and e.on_ground: + e.vel[1] = JUMP # mobs auto-jump 1-block steps + self.ph = (self.ph + float(np.hypot(e.vel[0], e.vel[2])) * 0.75) % 1.0 + self.pose(case) + + def pose(self, case): + mcskin.pose_golem(self, case) + + + +class Zombie(Mob): + TABLE = { + "hp": (14, 20, 26), + "speed": (0.13, 0.19, 0.26), + "dmg_min": (2.5, 3.0, 4.5), # Java easy / normal / hard (fixed per difficulty) + "dmg_max": (2.5, 3.0, 4.5), + "cooldown": (30, 20, 14), + "windup": (0.45, 0.28, 0.10), + "jitter": (0.0, 0.12, 0.3), + "enrage_speed": (1.0, 1.0, 1.3), # EXT: below half hp + "flail": (0.0, 0.0, 0.0), # EXT follow-up swipe, disabled since minecraft-arena@2 (not in Java) + } + MOVES = {"swipe": {"atoms": ["melee_single"], "telegraph": "arm cocked back", + "damage": "Java 2.5 / 3 / 4.5 then armor", "range": "reach 2.4", + "punish": "short cooldown; takes knockback on every hit; natural armor 2"}} + SKILLS = ("spacing", "attack_timing", "kiting", "target_priority", "reaction") + name = "zombie" + height, aim_h, reach, reach_up = 1.95, 1.05, 2.4, 2.6 + half = (0.3, 0.3) + knockback = 1.0 + armor = 2.0 + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.e = Entity(MID + 2.0, 0.0, MID, math.pi, 0.6, self.height) + self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0 + self.ph, self.tint_t, self.swipes = 0.0, 0, 0 + self.rig = zombie_rig() + + @property + def enraged(self): + return self.hp <= self.max_hp / 2 + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0) + self.tint_t = max(self.tint_t - 1, 0) + self.timer -= 1 / FPS + to = p.pos - e.pos + wish = self.steer(case) + e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw + speed = k.speed * (k.enrage_speed if self.enraged else 1.0) + if self.state == "chase": + if self.cd == 0 and self.in_reach(case): + self.state = "windup" + self.timer = max(0.05, k.windup + case.rng.uniform(-k.jitter, k.jitter)) + case.events.append("zombie_windup") + elif self.state == "windup": + speed *= 0.35 + if self.timer <= 0: + self.state, self.timer, self.swipes = "swing", 0.1, 0 + if self.in_reach(case): + self.hurt_player(case, case.rng.uniform(k.dmg_min, k.dmg_max), fling=0.4) + self.swipes = 1 + int(case.rng.random() < k.flail * 0.5) + else: + case.events.append("zombie_whiff") + elif self.state == "swing": + speed = 0.0 + if self.timer <= 0: + self.swipes -= 1 + if self.swipes > 0 and self.in_reach(case): + self.hurt_player(case, case.rng.uniform(k.dmg_min, k.dmg_max) * 0.7, fling=0.4) + self.timer = 0.1 + case.events.append("zombie_flail") + else: + self.state, self.cd = "recover", ticks(k.cooldown) + elif self.state == "recover" and self.cd == 0: + self.state = "chase" + if np.hypot(to[0], to[2]) < 0.45: + wish = 0 * wish + blocked, _ = physics(case, e, wish, speed, step=0.0) + if blocked and e.on_ground: + e.vel[1] = JUMP + self.ph = (self.ph + float(np.hypot(e.vel[0], e.vel[2])) * 1.1) % 1.0 + self.pose(case) + + def pose(self, case): + mcskin.pose_zombie(self, case) + + + +class ZombieLeader(Mob): + """Java Edition 1.21 *leader zombie* as a boss fight (minecraft.wiki/w/Zombie, read 2026-11-02; Java: + up to 5 % spawn on Normal / Hard, max health x2-5, reinforcement chance +50-75 %) on a night field. Every hit it takes + may call a reinforcement: a plain zombie (20 HP, armor 2, 0.23 speed attribute) spawned 7-12 blocks away, out of + the player's reach, that joins the chase at once; the leader's chance drops 5 % per summon, as in Java. The case is won + by killing the leader; reinforcements only add pressure (their hits on the player, their bodies blocking the way). + + Its own case since minecraft-arena@6 (3d/minecraft_zombie_leader): @5 had put it under 3d/minecraft_zombie, a + FORMAL_CASES scene that keeps its @4 rules (class Zombie above). + + Deliberate deviations (minecraft-arena@5): reinforcements are on every tier (Java: Hard only), with the chance and the + number alive scaled by tier, because a public tier must be the same fight paced differently; the spawn search is the + arena's free floor 7-12 blocks from the player instead of Java's 0 / +-7-40 blocks in darkness. + """ + TABLE = { # (easy, normal, hard) = TIERS + "hp": (215, 520, 1650), # TIER calibration (Java leader: 40-100 = 2-5x a zombie's 20) + "speed": (0.105, 0.117, 0.135), # vanilla b/t chase; Java 0.117 (see SPEED_NOTE), slower than a walk + "dmg_min": (2.5, 3.0, 4.5), # Java easy / normal / hard (fixed per difficulty) + "dmg_max": (2.5, 3.0, 4.5), + "cooldown": (30, 20, 20), # vanilla ticks between swings (Java 20) + "windup": (0.45, 0.30, 0.20), # EXT seconds of raised arms before the hit + "jitter": (0.0, 0.10, 0.15), # EXT tempo variance + "reinforce": (0.55, 0.60, 0.70), # leader's chance to call a reinforcement when hurt (Java +50-75 %) + "minions": (2, 3, 4), # reinforcements alive at once (EXT cap) + "minion_hp": (20, 20, 20), # Java zombie + "minion_dmg": (2.5, 3.0, 4.5), # Java easy / normal / hard + } + MOVES = {"swipe": {"atoms": ["melee_single"], "telegraph": "arms raised high, a lunge", + "damage": "Java 2.5 / 3 / 4.5 then armor", "range": "attack box 0.83 around its body", + "punish": "20-tick cooldown; takes knockback on every hit; natural armor 2"}, + "reinforcements": {"atoms": ["summon_adds"], "telegraph": "smoke where a helper climbs out of the ground", + "damage": "each reinforcement swipes like its caller", + "range": "spawns 7-12 blocks from you", "punish": "kill the caller: the adds stay, the fight ends"}} + SKILLS = ("spacing", "attack_timing", "kiting", "target_priority", "crowd_control", "reaction") + name = "zombie_leader" + height, aim_h, reach, reach_up = 1.95, 1.05, 2.4, 2.6 + half = (0.3, 0.3) + knockback = 1.0 + armor = 2.0 + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.e = Entity(MID + 4.0, 0.0, MID, math.pi, 0.6, self.height) + self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0 + self.ph, self.tint_t, self.swipes = 0.0, 0, 0 + self.chance = float(self.k.reinforce) + self.minions, self.summoned = [], 0 + self.rig = zombie_rig(leader=True) + + @property + def enraged(self): + return False # the @1-@4 below-half-HP speed-up is not Java; dropped in @5 + + def update(self, case): + self.melee(case, self.k.dmg_min, self.k.dmg_max) + self.minions = [z for z in self.minions if z.hp > 0] # the dead leave the fight (their puff is an event) + for z in self.minions: + z.update(case) + self.pose(case) + + def melee(self, case, dmg_min, dmg_max): + """One tick of the zombie melee AI (shared by the leader and its reinforcements).""" + k, e, p = self.k, self.e, case.body.e + self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0) + self.tint_t = max(self.tint_t - 1, 0) + self.timer -= 1 / FPS + to = p.pos - e.pos + wish = self.steer(case) + e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw + speed = k.speed + if self.state == "chase": + if self.cd == 0 and self.in_reach(case): + self.state = "windup" + self.timer = max(0.05, k.windup + case.rng.uniform(-k.jitter, k.jitter)) + case.events.append("zombie_windup") + elif self.state == "windup": + speed *= 0.35 + if self.timer <= 0: + self.state, self.timer = "swing", 0.1 + if self.in_reach(case): + self.hurt_player(case, case.rng.uniform(dmg_min, dmg_max), fling=0.4) + else: + case.events.append("zombie_whiff") + elif self.state == "swing": + speed = 0.0 + if self.timer <= 0: + self.state, self.cd = "recover", ticks(k.cooldown) + elif self.state == "recover" and self.cd == 0: + self.state = "chase" + if np.hypot(to[0], to[2]) < 0.45: + wish = 0 * wish + blocked, _ = physics(case, e, wish, speed, step=0.0) + if blocked and e.on_ground: + e.vel[1] = JUMP + self.ph = (self.ph + float(np.hypot(e.vel[0], e.vel[2])) * 1.1) % 1.0 + + def on_hurt(self, case, amount, kind): + """Java hurt(): a hurt mob may call a reinforcement; each summon lowers its own chance by 5 %.""" + alive = [z for z in self.minions if z.hp > 0] + if self.hp > 0 and len(alive) < int(round(self.k.minions)) and case.rng.random() < self.chance: + spot = self._reinforcement_spot(case) + if spot is not None: + self.chance = max(0.0, self.chance - 0.05) + self.summoned += 1 + z = Reinforcement(self, spot, self.summoned) + z.reset(case) + self.minions = alive + [z] + case.events.append(("zombie_reinforce", self.summoned, [round(float(v), 2) for v in spot])) + + def _reinforcement_spot(self, case): + """A free floor cell 7-12 blocks from the player (Java: 7-40 blocks away, never within 7 of a player).""" + H, p = case.arena.H, case.body.e.pos + for _ in range(24): + ang = case.rng.uniform(0.0, 2.0 * math.pi) + r = case.rng.uniform(7.0, 12.0) + x, z = p[0] + math.cos(ang) * r, p[2] + math.sin(ang) * r + if not (2.0 <= x <= S - 2.0 and 2.0 <= z <= S - 2.0): + continue + ix, iz = int(x), int(z) + if H[ix - 1:ix + 2, iz - 1:iz + 2].max() > 0: + continue + return np.array([ix + 0.5, 0.0, iz + 0.5]) + return None + + def rigs(self): + return [self.rig] + [z.rig for z in self.minions if z.rig is not None] + + def pose(self, case): + mcskin.pose_zombie(self, case) + + def pose_child(self, case, z): + """Posing of a reinforcement goes through its leader, so a lookahead clone can switch all posing off at once.""" + mcskin.pose_zombie(z, case) + + +class Reinforcement(ZombieLeader): + """A plain Java zombie called by the leader: 20 HP, armor 2, Java damage, the same melee AI. It climbs out of the + ground for 0.8 s (cannot move or attack), then joins the chase. It takes the player's hits through MobFight._targets + (kind "minion") and leaves the fight at 0 HP; it never calls reinforcements itself (Java's summoned zombie keeps a + 5 %-lower chance: two generations would flood a one-on-one arena).""" + hit_event = "minion_hit" + CLIMB = 16 # vanilla ticks climbing out of the ground + + def __init__(self, leader, spot, n): + super().__init__() + self.leader, self.spot, self.n = leader, np.asarray(spot, float), int(n) + + def reset(self, case): + Mob.reset(self, case) + self.k = self.leader.k + self.max_hp = self.hp = float(self.k.minion_hp) + to = case.body.e.pos - self.spot + self.e = Entity(self.spot[0], 0.0, self.spot[2], math.atan2(to[2], to[0]), 0.6, self.height) + self.state, self.timer, self.cd, self.iframes = "chase", 0.0, 0, 0 + self.ph, self.tint_t, self.swipes, self.summoned, self.minions = 0.0, 0, 0, 0, [] + self.born = case.t + self.rig = zombie_rig() + + def update(self, case): + if self.hp <= 0: + return + if case.t - self.born < ticks(self.CLIMB): + self.iframes, self.tint_t = max(self.iframes - 1, 0), max(self.tint_t - 1, 0) + else: + self.melee(case, self.k.minion_dmg, self.k.minion_dmg) + self.leader.pose_child(case, self) + + def on_hurt(self, case, amount, kind): + if self.hp <= 0: + case.events.append(("minion_killed", self.n, [round(float(v), 2) for v in self.e.pos])) + + + +class EnderDragon(Mob): + """Java Edition 1.21 ender dragon phases (minecraft.wiki/w/Ender_Dragon, read 2026-11-01), at arena scale. + + holding circles the portal; every `decide` vanilla ticks it lands with chance 1 / (3 + crystals alive), + otherwise strafes the player with chance 1/2 + strafe flies at the player; lined up with line of sight it charges a fireball for `windup` and fires + (also right after an end crystal is destroyed); the fireball leaves a dragon's breath cloud + landing descends onto the portal at the arena centre + scanning perched: turns to the player; a player within 20 blocks after 1.25 s -> roar (2 s) -> flaming + (3 s breath cloud under its head, Harming I); after 4 flames, or > 50 damage taken while perched, it + takes off; nobody within 20 blocks for 5 s -> charge + charge rushes the player's position, then returns to holding + Hits to the head deal full damage, body/wing hits damage / 4 + min(damage, 1); arrows bounce off a perched + dragon. The nearest end crystal heals 1 HP every 10 vanilla ticks; destroying the healing crystal deals 10. + Contact: the head deals ram_dmg, the wings wing_dmg and a shove, only while the dragon was not hurt within + the last 10 vanilla ticks. The model, arena and clouds are scaled down (34-block arena instead of the island). + """ + TABLE = { + "hp": (150, 320, 1350), # TIER calibration for ~25 s / 1 min / 3 min (Java: 200 on every difficulty) + "speed": (0.40, 0.50, 0.60), # vanilla b/t cruise + "turn": (1.6, 2.2, 3.0), # rad/s + "ram_dmg": (6.0, 10.0, 15.0), # Java head contact easy / normal / hard + "wing_dmg": (3.5, 5.0, 7.5), # Java wing contact + "breath_dmg": (3.0, 3.0, 3.0), # Harming I per 20 vanilla ticks inside the perched breath + "cloud_dmg": (6.0, 6.0, 6.0), # Harming II per 20 vanilla ticks inside a fireball cloud + "cloud_s": (8.0, 10.0, 12.0), # APPROX fireball cloud life (Java 30 s, growing radius 3 -> 7) + "decide": (70, 50, 34), # vanilla ticks between holding-pattern decisions (path nodes) + "altitude": (9.0, 8.5, 8.0), # holding height above the floor + "windup": (0.55, 0.40, 0.25), # EXT fireball telegraph (Java fireball charge 5 ticks) + "bank": (24.0, 40.0, 58.0), # EXT roll into turns + "crystals": (2, 6, 8), # end crystals on the tallest towers (Java 10 on the island) + "crystal_blast": (43.5, 85.0, 127.5), # power-6 explosion peak damage (easy / normal / hard) + "land_base": (1.5, 3.0, 3.0), # landing chance per decision 1 / (land_base + crystals alive); Java 3 + "fire_min": (12.0, 10.0, 8.0), # APPROX nearest fireball shot, blocks from mouth to chest + } + MOVES = {"fireball": {"atoms": ["projectile_linear", "area_cloud"], "telegraph": "lines up on you, mouth glows", + "damage": "cloud_dmg per second inside the purple cloud (magic: armor does not help)", + "range": "fired from up to 20 blocks with line of sight", + "punish": "after firing it returns to circling"}, + "perch": {"atoms": ["phase_land", "cone_dot"], "telegraph": "lands on the portal, roars for 2 s", + "damage": "breath_dmg per second in the cloud under its head", + "range": "breath under the head, about 2 blocks around", + "punish": "arrows bounce off, but sword hits on the head deal full damage; > 50 damage makes it take off"}, + "charge": {"atoms": ["charge_ram"], "telegraph": "after 5 s perched with nobody close it lifts and rushes", + "damage": "ram_dmg head contact, wing_dmg + shove from the wings", + "range": "body contact", "punish": "it flies past and climbs back to circling"}, + "crystals": {"atoms": ["heal_source"], "telegraph": "a white beam from the nearest crystal", + "damage": "the crystal explodes when hit (power 6)", + "range": "on top of the towers", "punish": "breaking the healing crystal deals 10 to the flyer"}} + SKILLS = ("aim_tracking", "target_priority", "weapon_switch", "dodge_dive", "dps_windows", "reaction") + STATES = ("circle", "strafe", "perch", "charge") + COARSE = {"holding": "circle", "takeoff": "circle", "strafe": "strafe", "landing": "perch", + "scanning": "perch", "roar": "perch", "flaming": "perch", "charge": "charge"} + SITTING = ("scanning", "roar", "flaming") + name = "ender_dragon" + height = 1.6 + hover = True + knockback = 0.0 + half = (1.25, 1.25) + PERCH_Y = 1.7 # body centre above the portal floor while perched + + @property + def aim_h(self): + return 0.0 # pos is already the body centre + + def hit_lo(self): + return self.e.pos - [1.25, 0.6, 1.25] + + def hit_hi(self): + return self.e.pos + [1.25, 0.6, 1.25] + + def head_center(self): + drop = -0.95 if self.phase in self.SITTING else 0.25 + return self.e.pos + self.e.fwd * 3.2 + [0.0, drop, 0.0] + + def hitboxes(self): + h = self.head_center() + return [("head", h - [0.55, 0.45, 0.55], h + [0.55, 0.45, 0.55]), + ("body", self.hit_lo(), self.hit_hi())] + + def in_reach(self, case): + return bool(np.linalg.norm(self.dist_to(case)) <= 3.4) + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.e = Entity(MID + 5.0, float(self.k.altitude), MID, math.pi, 2.6, self.height) + self.phase, self.state, self.timer, self.cd, self.iframes = "holding", "circle", 0.0, ticks(self.k.decide), 0 + self.flap, self.bank, self.tint_t, self.hurt_t = 0.0, 0.0, 0, 0 + self.phase_t, self.flames, self.sit_damage, self.orbit = 0, 0, 0.0, 1.0 + self.fireballs, self.clouds, self.goal = [], [], None + self.heal_from, self.last_hurt = None, 0.0 + self.crystals = self._place_crystals(case) + self.rig = dragon_rig() + + def _place_crystals(self, case): + """End crystals on the tallest tower tops (deterministic from the seeded layout; no RNG).""" + H, tops = case.arena.H, [] + for x in range(1, S - 1): + for z in range(1, S - 1): + h = int(H[x, z]) + if h >= 4 and h >= H[x - 1:x + 2, z - 1:z + 2].max(): + if all(abs(x - a) > 1 or abs(z - b) > 1 for a, b, _ in tops): + tops.append((x, z, h)) + tops.sort(key=lambda t: (-t[2], t[0], t[1])) + return [{"id": i, "pos": np.array([x + 0.5, h + 1.0, z + 0.5]), "alive": True} + for i, (x, z, h) in enumerate(tops[:int(round(self.k.crystals))])] + + @property + def crystals_alive(self): + return sum(c["alive"] for c in self.crystals) + + @property + def enraged(self): + return self.crystals_alive == 0 + + def _go(self, case, phase, timer=0.0): + self.phase, self.state, self.timer, self.phase_t = phase, self.COARSE[phase], timer, 0 + case.events.append(("dragon_phase", phase)) + + # -- damage -------------------------------------------------------------------------------------------- + def take_hit(self, case, dmg, kind="normal", bonus_knockback=0.0, part="body"): + if kind.startswith("arrow") and self.phase in self.SITTING: + case.events.append("arrow_deflected") + return 0.0 + if part != "head": + dmg = dmg / 4.0 + min(dmg, 1.0) + before = self.hp + amount = super().take_hit(case, dmg, kind if part == "head" else kind + "_body") + if amount > 0: + self.hurt_t = ticks(10) + if self.phase in self.SITTING: + self.sit_damage += before - self.hp + if self.sit_damage > 0.25 * self.max_hp: + self.sit_damage = 0.0 + self._go(case, "takeoff", 2.0) + return amount + + def crystal_destroyed(self, case, crystal): + crystal["alive"] = False + case.events.append(("crystal_destroyed", crystal["id"])) + p = case.body.e + r = float(np.linalg.norm(p.pos + [0, PLAYER_H / 2, 0] - crystal["pos"])) + impact = 1.0 - r / 12.0 + if impact > 0: + exposure = 1.0 if case.arena.los(crystal["pos"], p.pos + [0, 1.0, 0], eye_h=0.0) else 0.25 + dmg = self.k.crystal_blast * ((impact * impact + impact) / 2 * 84 + 1) / 85 * exposure + self.hurt_player(case, dmg, fling=0.5 * impact, origin=crystal["pos"]) + if self.heal_from is crystal: + self.heal_from = None + super().take_hit(case, 10.0, "crystal") + self.hurt_t = ticks(10) + if self.phase == "holding": + self._go(case, "strafe", 6.0) + + # -- flight ---------------------------------------------------------------------------------------------- + def _fly(self, case, goal, speed, rate): + e = self.e + to = goal - e.pos + want = math.atan2(to[2], to[0]) + d = (want - e.yaw + math.pi) % (2 * math.pi) - math.pi + turn = float(np.clip(d, -rate, rate)) + e.yaw = (e.yaw + turn) % (2 * math.pi) + self.bank = float(np.clip(-math.degrees(turn * FPS) * 45 / 400, -self.k.bank, self.k.bank)) + horiz = np.hypot(to[0], to[2]) + step = e.fwd * min(speed, horiz + 0.02) if horiz > 0.05 else np.zeros(3) + e.vel[1] = float(np.clip(to[1] * gain(0.12), per_vt(-0.45), per_vt(0.45))) + new = e.pos + step + if case.arena.ground(new, 2.2) > new[1] - 0.6 and self.phase not in ("landing",) + self.SITTING: + e.vel[1] = per_vt(0.45) # climb over a tower instead of flying through it + new = e.pos.copy() + e.pos[[0, 2]] = new[[0, 2]] + e.pos[1] = float(np.clip(e.pos[1] + e.vel[1], 1.0, 16.0)) + return float(np.linalg.norm(goal - e.pos)), abs(d) + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.tint_t = max(self.iframes - 1, 0), max(self.tint_t - 1, 0) + self.hurt_t = max(self.hurt_t - 1, 0) + self.cd = max(self.cd - 1, 0) + self.timer -= 1 / FPS + self.phase_t += 1 + rate, speed = k.turn / FPS, per_vt(k.speed) + centre = np.array([MID, 0.0, MID]) + self._heal(case) + self._projectiles(case) + if self.phase == "holding": + radial = e.pos - centre + radial[1] = 0.0 + ang = math.atan2(radial[2], radial[0]) + 0.9 * self.orbit + goal = centre + [math.cos(ang) * 10.5, k.altitude, math.sin(ang) * 10.5] + self._fly(case, goal, speed, rate) + if self.cd == 0: + self.cd = ticks(k.decide) + # Java: nextInt(3 + crystals alive) == 0 lands; land_base is that 3 (BossBench easy perches sooner) + if case.rng.random() * (k.land_base + self.crystals_alive) < 1.0: + self._go(case, "landing", 8.0) + elif case.rng.random() < 0.5: + self._go(case, "strafe", 6.0) + elif self.phase == "strafe": + goal = p.pos + [0.0, 5.0, 0.0] + dist, err = self._fly(case, goal, speed, rate * 1.2) + flat = float(np.hypot(*(p.pos - e.pos)[[0, 2]])) + aim = math.atan2((p.pos - e.pos)[2], (p.pos - e.pos)[0]) + facing = abs((aim - e.yaw + math.pi) % (2 * math.pi) - math.pi) < math.radians(15) + mouth = e.pos + e.fwd * 3.6 + if facing and flat < 20.0 and case.arena.los(mouth, p.pos + [0, 1.0, 0], eye_h=0.0): + if self.goal is None: + self.goal = case.t + ticks(20 * k.windup) + case.events.append("dragon_lineup") + elif case.t >= self.goal: + if float(np.linalg.norm(p.pos + [0, 0.9, 0] - mouth)) >= k.fire_min: + self._fireball(case, mouth, p.pos + [0, 0.9, 0]) + self.goal = None + self._go(case, "holding") + self.orbit = -self.orbit + else: + # Java's dragon breaks off a strafe within 10 blocks of its target, so its fireballs come + # from across the island. The scaled arena would let it fire point-blank (a cloud nobody can + # outrun: found 2026-11-02), so a too-close shot is called off and the lineup starts over. + self.goal = None + case.events.append("dragon_hold_fire") + if self.phase == "strafe" and (self.timer <= 0 or flat < 3.0): + self.goal = None + self._go(case, "holding") + elif self.phase == "landing": + perch = centre + [0.0, self.PERCH_Y, 0.0] + flat = float(np.hypot(*(perch - e.pos)[[0, 2]])) + goal = perch + [0.0, min(6.0, flat * 0.5), 0.0] + self._fly(case, goal, speed * (0.6 if flat < 6 else 1.0), rate * 1.5) + if flat < 0.6 and e.pos[1] - perch[1] < 0.4 or self.timer <= 0: + e.pos[:] = perch + e.vel[:] = 0.0 + self.flames, self.sit_damage = 0, 0.0 + self._go(case, "scanning") + elif self.phase in self.SITTING: + to = p.pos - e.pos + want = math.atan2(to[2], to[0]) + d = (want - e.yaw + math.pi) % (2 * math.pi) - math.pi + e.yaw = (e.yaw + float(np.clip(d, -rate * 0.6, rate * 0.6))) % (2 * math.pi) + self.bank = 0.0 + near = float(np.hypot(*(p.pos - centre)[[0, 2]])) <= 20.0 + if self.phase == "scanning": + if near and self.phase_t >= ticks(25) and abs(d) < math.radians(20): + self._go(case, "roar") + case.events.append("dragon_roar") + elif self.phase_t >= ticks(100): + self.goal = p.pos.copy() + [0, 1.0, 0] + self._go(case, "charge", 4.0) + elif self.phase == "roar" and self.phase_t >= ticks(40): + self._go(case, "flaming") + c = self.head_center() + g = case.arena.ground(c, 0.6) + self.clouds.append({"pos": np.array([c[0], g, c[2]]) + self.e.fwd * 1.2, "r": 2.0, "dmg": k.breath_dmg, + "life": 3.0, "life0": 3.0, "kind": "breath", "next": {}}) + elif self.phase == "flaming" and self.phase_t >= ticks(60): + self.flames += 1 + if self.flames >= 4: + self._go(case, "takeoff", 2.5) + else: + self._go(case, "scanning") + elif self.phase == "takeoff": + out = e.pos - centre + out[1] = 0.0 + out = out / (np.linalg.norm(out) + 1e-6) if np.linalg.norm(out) > 0.5 else e.fwd + goal = centre + out * 10.0 + [0, k.altitude, 0] + self._fly(case, goal, speed * 0.7, rate) + if self.timer <= 0: + self.cd = ticks(k.decide) + self._go(case, "holding") + elif self.phase == "charge": + dist, _ = self._fly(case, self.goal, speed * 1.8, rate * 2.0) + if dist < 1.5 or self.timer <= 0: + self.goal = None + self.cd = ticks(k.decide) + self._go(case, "holding") + self._contact(case) + self.flap = (self.flap + (per_vt(0.35) + speed) * 0.55 * (0.2 if self.phase in self.SITTING else 1.0)) % 1.0 + self.pose(case) + + def _heal(self, case): + alive = [c for c in self.crystals if c["alive"]] + if self.heal_from is not None and not self.heal_from["alive"]: + self.heal_from = None + if self.heal_from is None and alive and case.rng.random() < 1 - 0.9 ** VT: + self.heal_from = min(alive, key=lambda c: float(np.linalg.norm(c["pos"] - self.e.pos))) + if self.heal_from is not None and case.t % ticks(10) == 0 and self.hp < self.max_hp: + self.hp = min(self.max_hp, self.hp + 1.0) + + def _contact(self, case): + """Java aiStep: head/neck hurt and wing shove, only while hurtTime == 0.""" + if self.hurt_t > 0: + return + p = case.body.e + lo, hi = p.pos - [0.3, 0.0, 0.3], p.pos + [0.3, PLAYER_H, 0.3] + h = self.head_center() + if np.all(hi >= h - 1.55) and np.all(lo <= h + 1.55): + if self.hurt_player(case, self.k.ram_dmg, fling=0.6, origin=h): + case.events.append("dragon_ram") + return + if self.phase in self.SITTING: + return + b = self.e.pos + flat = float(np.hypot(*(p.pos - b)[[0, 2]])) + if flat < 3.2 and -2.5 < p.pos[1] + 0.9 - b[1] < 1.0: + if self.hurt_player(case, self.k.wing_dmg, fling=1.0, origin=b): + p.vel[1] = vy_sim(0.2 + 0.2) + p.on_ground = False + case.events.append("dragon_wing") + + # -- fireballs and clouds -------------------------------------------------------------------------------- + def _fireball(self, case, start, target): + direction = np.asarray(target, float) - start + direction /= float(np.linalg.norm(direction)) + 1e-9 + self.fireballs.append({"pos": start.copy(), "vel": direction * per_vt(0.1), "dir": direction, "life": 8.0}) + case.events.append("dragon_fireball") + + def _projectiles(self, case): + p, keep = case.body.e, [] + lo, hi = p.pos - [0.45, 0.15, 0.45], p.pos + [0.45, PLAYER_H + 0.15, 0.45] + F = decay(0.95) + for f in self.fireballs: + f["vel"] = f["vel"] * F + f["dir"] * per_vt(1.9) * (1 - F) + start, end = f["pos"], f["pos"] + f["vel"] + f["life"] -= 1 / FPS + hp_ = _segment_box(start, end, lo, hi) + hw, _ = case._arrow_world_hit(start, end) + if hp_ is not None or hw is not None or f["life"] <= 0: + u = min(x for x in (hp_, hw, 1.0) if x is not None) + at = start + (end - start) * u + g = case.arena.ground(at, 0.2) + self.clouds.append({"pos": np.array([at[0], g, at[2]]), "r": 3.0, "dmg": self.k.cloud_dmg, + "life": self.k.cloud_s, "life0": self.k.cloud_s, "kind": "fireball", "next": {}}) + case.events.append("dragon_cloud") + continue + f["pos"] = end + keep.append(f) + self.fireballs = keep + alive = [] + for c in self.clouds: + c["life"] -= 1 / FPS + if c["kind"] == "fireball": + c["r"] = 3.0 + 1.0 * (1 - c["life"] / c["life0"]) + if c["life"] <= 0: + continue + inside = float(np.hypot(*(p.pos - c["pos"])[[0, 2]])) <= c["r"] and -0.5 < p.pos[1] - c["pos"][1] < 1.5 + if inside and case.t >= c["next"].get("p", 0): + c["next"]["p"] = case.t + ticks(20) + if self.hurt_player(case, c["dmg"], armor=False): + case.events.append("dragon_breath") + alive.append(c) + self.clouds = alive + + def extra(self, case): + return [] + + def pose(self, case): + mcskin.pose_dragon(self, case) + + def fx(self, case): + return [] # breath and ender particles: mcskin.fx_ambient + + +class Wither(Mob): + """Java Edition 1.21 wither (minecraft.wiki/w/Wither, read 2026-11-01). + + spawn 220 vanilla ticks of invulnerable charging (health bar fills), then a power-7 blast at its body + hover above half health: keeps its feet 5 blocks over the target and flies to within 3 blocks + horizontally; the main head fires a wither skull every 40 vanilla ticks with line of sight, each + side head 40-59 ticks after its last shot; an idle side head (counter > 15, +3 per hit taken, + Normal/Hard) lobs a slow blue skull at a random spot + armored at or below half health: wither armor makes it immune to arrows and it comes down to the + target's height (melee range); the armor goes away if it regenerates above half + nolos no line of sight from the main head: it stops firing and closes in + Regenerates 1 HP every 20 vanilla ticks; a damaged wither breaks the blocks of a 3x4x3 box around itself + 20 ticks later (the arena wall is immune). There is no dash in Java (the dash is Bedrock-only). + Black skulls accelerate 0.1 b/t^2 with inertia 0.95 (terminal 1.9 b/t), blue skulls inertia 0.73 + (terminal 0.27 b/t). A hit deals skull_dmg (armor applies) and Wither II; the power-1 explosion + deals up to blast_dmg within 2 blocks. + """ + TABLE = { + "hp": (100, 250, 600), # TIER calibration for ~25 s / 1 min / 3 min (Java: 300 on every difficulty) + "regen": (0.5, 1.0, 1.0), # HP per 20 vanilla ticks (Java 1) + "altitude": (4.0, 5.0, 5.0), # phase 1: feet above the target's feet (Java 5) + "speed": (0.30, 0.43, 0.43), # vanilla b/t approach when > 3 blocks away (Java ~0.43 steady) + "skull_dmg": (5.0, 8.0, 12.0), # Java Easy / Normal / Hard + "blast_dmg": (3.5, 5.0, 7.5), # power-1 skull explosion at its centre (scaled with the skull) + "wither_s": (0.0, 10.0, 40.0), # Wither II seconds (Java Easy none, Normal 10, Hard 40) + "cd_main": (60, 40, 40), # vanilla ticks between main-head skulls (Java 40; easy slower) + "cd_side": (100, 40, 40), # side head pause after a shot, + 0-19 (Java 40-59; easy slower) + "blue_idle": (1e9, 15, 15), # side-head idle counter limit for blue skulls (Normal/Hard only) + "spawn_blast": (35.5, 69.0, 103.5), # power-7 spawn explosion peak damage (Java easy / normal / hard) + } + MOVES = {"shell": {"atoms": ["projectile_linear", "explosion_small", "dot_drain"], + "telegraph": "a head turns to the player; black shells fly fast, blue shells slowly", + "damage": "shell damage (armor) + black-heart drain; explosion up to blast damage within 2 blocks", + "range": "main head 40 ticks, side heads 40-59 ticks, line of sight needed", + "punish": "break line of sight with cover; it stops firing"}, + "spawn": {"atoms": ["charge_invulnerable", "explosion_large"], + "telegraph": "11 s of flickering blue while its health bar fills", + "damage": "spawn_blast at the centre, falling to 0 at 14 blocks (armor applies)", + "range": "power 7 (14 blocks)", "punish": "run far away before the blast"}, + "armor": {"atoms": ["phase_shield"], "telegraph": "a translucent armor shell at half health", + "damage": "-", "range": "arrows bounce off; it descends to melee height", + "punish": "switch to the sword (hotbar) and fight it on the ground"}} + SKILLS = ("projectile_dodge", "cover_use", "weapon_switch", "aim_tracking", "spacing", "reaction") + STATES = ("spawn", "hover", "armored", "nolos") + name = "wither" + height, reach, reach_up, aim_h = 3.5, 3.0, 3.0, 0.0 + half = (0.45, 0.45) + hover = True + knockback = 0.0 + armor = 4.0 + FEET = 1.5 # pos is the chest: hitbox [pos - 1.5, pos + 2.0], 0.9 wide + SPAWN_TICKS = 220 # vanilla ticks + + def reset(self, case): + super().reset(case) + self.max_hp = float(self.k.hp) + self.hp = self.max_hp / 3 # Java: the bar fills during the spawn charge + p = case.body.e + self.e = Entity(MID + 4.0, self.FEET + 0.0, MID, math.pi, 0.9, self.height) + self.state, self.timer, self.cd, self.iframes = "spawn", self.SPAWN_TICKS / 20, ticks(self.k.cd_main), 0 + self.side_next, self.idle = [ticks(20), ticks(30)], [0, 0] + self.skulls, self.tint_t, self.tilt, self.guard = [], 0, 0.0, 0.0 + self.blocks_t, self.shots, self.blue_shots, self.last_hurt = -1, 0, 0, 0.0 + self.armored = False + self.rig = wither_rig() + + @property + def enraged(self): + return self.armored + + def hit_lo(self): + return self.e.pos - [self.half[0], self.FEET, self.half[1]] + + def hit_hi(self): + return self.e.pos + [self.half[0], self.height - self.FEET, self.half[1]] + + def in_reach(self, case): + return bool(np.linalg.norm(self.dist_to(case)) <= 3.6) + + def immune(self, case, kind): + if self.state == "spawn": + return True + return self.armored and kind.startswith("arrow") + + def on_hurt(self, case, amount, kind): + self.idle = [i + 3 for i in self.idle] + if self.blocks_t < 0: + self.blocks_t = ticks(20) + + def head_pos(self, i): + side = (0.0, -0.85, 0.85)[i] + return self.e.pos + [0.0, 1.05 - (0.1 if i else 0.0), 0.0] + self.e.right * side + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.tint_t = max(self.iframes - 1, 0), max(self.tint_t - 1, 0) + self.cd = max(self.cd - 1, 0) + self.timer = max(self.timer - 1 / FPS, 0.0) + self._skulls(case) + flat = np.array([p.pos[0] - e.pos[0], 0.0, p.pos[2] - e.pos[2]]) + dist = float(np.linalg.norm(flat)) + e.yaw = math.atan2(flat[2], flat[0]) + if self.state == "spawn": + self.hp = min(self.max_hp, self.hp + self.max_hp * 2 / 3 / ticks(self.SPAWN_TICKS)) + e.vel[:] = 0.0 + if self.timer <= 0: + self.hp = self.max_hp + self._explode(case, e.pos, 7.0, k.spawn_blast, fling=1.2, name="wither_spawn_blast") + self.state = "hover" + self.pose(case) + return + if case.t % ticks(20) == 0 and self.hp < self.max_hp: + self.hp = min(self.max_hp, self.hp + k.regen) + if self.blocks_t >= 0: + self.blocks_t -= 1 + if self.blocks_t < 0: + self._break_blocks(case) + self.armored = self.hp <= self.max_hp / 2 + main = self.head_pos(0) + target = p.pos + [0, PLAYER_H * 0.45, 0] + sees = case.arena.los(main, target, eye_h=0.0) + self.state = "armored" if self.armored else "hover" + if not sees: + self.state = "nolos" + # -- movement: Java WitherBoss.aiStep, per vanilla tick converted to the simulation tick ---------- + feet, goal = e.pos[1] - self.FEET, p.pos[1] + (0.0 if self.armored else k.altitude) + if feet < goal: + e.vel[1] = max(e.vel[1], 0.0) + e.vel[1] += (per_vt(0.3) - e.vel[1]) * gain(0.6) + elif self.armored and feet > goal + 0.25: + e.vel[1] += (per_vt(-0.15) - e.vel[1]) * gain(0.4) + else: + e.vel[1] *= decay(0.546) + if dist > 3.0 or (not sees and dist > 1.0): + e.vel[[0, 2]] += (flat[[0, 2]] / (dist + 1e-6) * per_vt(k.speed) - e.vel[[0, 2]]) * gain(0.636) + else: + e.vel[[0, 2]] *= decay(0.91) + new = e.pos + e.vel + if case.arena.ground(new, e.w) <= new[1] - self.FEET + 0.05: + e.pos[[0, 2]] = new[[0, 2]] + else: # flying pathing: rise over the column instead of stalling at it + e.vel[[0, 2]] *= decay(0.5) + e.vel[1] = max(e.vel[1], per_vt(0.3)) + new[1] = e.pos[1] + e.vel[1] + floor = case.arena.ground(e.pos, e.w) + self.FEET + e.pos[1] = float(np.clip(new[1], floor, 16.0)) + # -- heads ------------------------------------------------------------------------------------------- + if sees and self.cd == 0 and float(np.linalg.norm(target - main)) <= 20.0: + self._fire(case, 0, target, blue=bool(case.rng.random() < 0.001)) + self.cd = ticks(k.cd_main) + for i in (0, 1): + if case.t < self.side_next[i]: + continue + self.side_next[i] = case.t + ticks(10 + int(case.rng.integers(0, 10))) + if k.blue_idle < 1e8: + count, self.idle[i] = self.idle[i], self.idle[i] + 1 + if count > k.blue_idle: + spot = np.array([e.pos[0] + case.rng.normal(0, 6.0), 0.0, e.pos[2] + case.rng.normal(0, 6.0)]) + self._fire(case, i + 1, spot, blue=True) + self.idle[i] = 0 + head = self.head_pos(i + 1) + if case.arena.los(head, target, eye_h=0.0) and float(np.linalg.norm(target - head)) <= 30.0: + self._fire(case, i + 1, target) + self.side_next[i] = case.t + ticks(k.cd_side + int(case.rng.integers(0, 20))) + self.idle[i] = 0 + self.pose(case) + + # -- projectiles and explosions --------------------------------------------------------------------- + def _fire(self, case, head, target, blue=False): + start = self.head_pos(head) + aim = np.asarray(target, float) - start + direction = aim / (float(np.linalg.norm(aim)) + 1e-9) + self.shots += 1 + self.skulls.append({"pos": start + direction * 0.4, "vel": direction * per_vt(0.1), "dir": direction, + "blue": bool(blue), "life": 12.0, "head": int(head), "n": self.shots}) + self.blue_shots += int(blue) + case.events.append(("wither_fire", int(head), "blue" if blue else "black")) + + def _explode(self, case, at, power, peak, fling=0.0, name="explosion"): + """Java explosion falloff (impact = 1 - r / 2 power) scaled so the centre deals `peak`; armor applies.""" + p = case.body.e + r = float(np.linalg.norm(p.pos + [0, PLAYER_H / 2, 0] - at)) + impact = 1.0 - r / (2.0 * power) + case.events.append((name, round(r, 2), [round(float(v), 2) for v in at])) + if impact <= 0: + return False + dmg = peak * ((impact * impact + impact) / 2 * 7 * 2 * power + 1) / (7 * 2 * power + 1) + return self.hurt_player(case, dmg, fling=fling * impact, origin=at) + + def _skulls(self, case): + p, keep = case.body.e, [] + lo, hi = p.pos - [PLAYER_W / 2 + 0.16, 0.16, PLAYER_W / 2 + 0.16], p.pos + [PLAYER_W / 2 + 0.16, PLAYER_H + 0.16, PLAYER_W / 2 + 0.16] + for s in self.skulls: + inertia = 0.73 if s["blue"] else 0.95 + F = decay(inertia) + s["vel"] = s["vel"] * F + s["dir"] * per_vt(0.1 * inertia / (1 - inertia)) * (1 - F) + start, end = s["pos"], s["pos"] + s["vel"] + s["life"] -= 1 / FPS + hit_player = _segment_box(start, end, lo, hi) + hit_world, reason = case._arrow_world_hit(start, end) + if hit_player is not None and (hit_world is None or hit_player <= hit_world): + at = start + (end - start) * hit_player + if self.hurt_player(case, self.k.skull_dmg, fling=0.3, origin=at): + if self.k.wither_s > 0: + case.body.wither_t = max(case.body.wither_t, ticks(20 * self.k.wither_s)) + case.events.append("skull_hit") + self._explode(case, at, 1.0, self.k.blast_dmg, name="skull_blast") + continue + if hit_world is not None: + at = start + (end - start) * hit_world + case.events.append(("skull_ground", reason)) + self._explode(case, at, 1.0, self.k.blast_dmg, name="skull_blast") + continue + s["pos"] = end + if s["life"] <= 0 or end[1] > 30: + continue + keep.append(s) + self.skulls = keep + + def _break_blocks(self, case): + """Java: 20 ticks after damage, blocks in x/z +-1, y floor(feet)..+3 around the wither break (not the wall).""" + H, e = case.arena.H, self.e + base = int(math.floor(e.pos[1] - self.FEET)) + broke = 0 + for x in range(int(e.pos[0]) - 1, int(e.pos[0]) + 2): + for z in range(int(e.pos[2]) - 1, int(e.pos[2]) + 2): + if not (1 <= x < S - 1 and 1 <= z < S - 1): + continue # the arena wall is wither-immune (bedrock-like) + if base < H[x, z] <= base + 4: + H[x, z] = max(base, 0) + broke += 1 + if broke: + case.events.append(("wither_break", broke)) + + def extra(self, case): + return [{"pos": s["pos"], "size": (0.32, 0.32, 0.32), "color": (0.2, 0.18, 0.22), "blue": s["blue"]} + for s in self.skulls] + + def fx(self, case): + return [] # skull smoke and aura: mcskin.fx_ambient + + def pose(self, case): + mcskin.pose_wither(self, case) + + +class Warden(Mob): + """Java Edition 1.21 warden (minecraft.wiki/w/Warden, read 2026-11-02), as a fight in the deep dark. + + emerge it climbs out of the floor (Java ~6.7 s; arena 3 s), invulnerable except to /kill + roar 4.2 s roar before the chase (Java: when anger reaches 80; skipped when attacked from within 5 blocks) + chase melee: Java 16 / 30 / 45 per hit (armor applies), 36-tick cooldown, disables a raised shield; a warden + is never knocked back. It walks at a player's pace, so out-walking it is not an option, but it + pivots slowly after a missed swing (the 'opening'). + boom sonic boom when it cannot reach its target (Java: a pillar perch or across a gap): 1.7 s charge, then a + hit that ignores armor, shields and walls (Java 6 / 10 / 15) with knockback; 1.3 s recovery; in Java it + needs 5 s since its last attack. Range 15 horizontal / 20 vertical. + darkness every 6 s, 13 s of Darkness within 20 blocks (Java; visual only here: the screen dims in pulses) + Java's anger and sniffing decide *who* it hunts; a one-on-one arena gives it the player from the start. + + BossBench deviations (minecraft-arena@5): health per tier (Java 500 on every difficulty); the sonic boom also fires + when the player has merely stayed out of melee reach for boom_every seconds (Java: when the target is unreachable, + 5 s after its last attack), so kiting in the open is answered as Java answers a pillar perch. The tiers span Java + Easy to Java *Normal* damage: Java Hard's 45-damage smash leaves 29 after unenchanted diamond armor, more than a + full 20-HP bar, so a three-minute hard tier would be a single-mistake test (Java players fight wardens in enchanted + netherite, which this arena does not model). Hard keeps every other Java Hard trait: 36-tick cooldown, 4.2 s roar. + """ + TABLE = { # (easy, normal, hard) = TIERS + "hp": (260, 820, 2100), # TIER calibration (Java 500 on every difficulty) + "speed": (0.22, 0.26, 0.286), # vanilla b/t chase; Java 0.286 = attribute 0.3 x 1.2 (SPEED_NOTE), + # a sprinting player's pace (walk 0.216, sprint 0.281) + "dmg": (16.0, 23.0, 30.0), # melee before armor: Java Easy 16, midway, Java Normal 30 (see below) + "cooldown": (44, 40, 36), # vanilla ticks between swings (Java 36) + "windup": (0.80, 0.65, 0.55), # EXT raised-arms telegraph: long enough to back out of its attack box + # from contact range (it out-walks a backpedalling player) + "boom_dmg": (6.0, 8.0, 10.0), # sonic boom, ignores armor: Java Easy 6, midway, Java Normal 10 + "boom_every": (9.0, 7.0, 5.0), # seconds out of reach before a boom (Java: 5 s since the last attack) + "emerge_s": (3.0, 3.0, 3.0), # APPROX (Java ~6.7 s) + "roar_s": (2.0, 3.0, 4.2), # EXT on easy / normal (Java 4.2 s) + } + MOVES = {"smash": {"atoms": ["melee_single"], "telegraph": "arms raised, chest glowing", + "damage": "16 / 23 / 30 then armor (Java 16 / 30 / 45)", "range": "attack box 0.83 around its body", + "punish": "36-44 tick cooldown; it keeps walking, so back off between swings"}, + "shockwave": {"atoms": ["ranged_hitscan"], "telegraph": "1.7 s charge: chest lights, rings gather", + "damage": "6 / 8 / 10 (Java 6 / 10 / 15), ignores armor and walls, knocks back", + "range": "15 blocks horizontally, 20 vertically", + "punish": "1.3 s recovery after the boom; the timer only runs while you stay out of reach"}, + "vision_dim": {"atoms": ["vision_dot"], "telegraph": "a heartbeat pulse", "damage": "-", + "range": "20 blocks", "punish": "-"}} + SKILLS = ("spacing", "attack_timing", "reaction", "resource_management", "terrain_use") + STATES = ("emerge", "chase", "windup", "boom") + name = "warden" + height, aim_h = 2.9, 1.45 + half = (0.45, 0.45) + knockback = 0.0 + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.e = Entity(MID + 6.0, 0.0, MID, math.pi, 0.9, self.height) + self.state, self.timer, self.cd, self.iframes = "emerge", float(self.k.emerge_s), 0, 0 + self.phase = "emerge" + self.ph, self.tint_t = 0.0, 0 + self.out_of_reach = 0 # sim ticks the player has spent out of melee reach + self.boom_cd = 0 + self.dark_t = 0 + self.booms = 0 + self.rig = warden_rig() + + @property + def enraged(self): + return False + + def in_reach(self, case): + """Java 1.20.2+ attack box, plus the warden's vertical reach of 2 blocks (22w16a lowered it from 3): a player + standing more than 2 blocks above its feet is out of reach even while it jumps against the block below - the + perch its sonic boom exists for. APPROX: measured feet to feet.""" + if case.body.e.pos[1] - self.e.pos[1] > 2.0: + return False + return super().in_reach(case) + + def immune(self, case, kind): + return self.phase == "emerge" # Java: only /kill hurts an emerging warden + + def on_hurt(self, case, amount, kind): + if self.phase == "roar" and float(np.linalg.norm(case.body.e.pos - self.e.pos)) <= 5.0: + self._go(case, "chase") # Java: attacked from within 5 blocks, it skips the roar + + def _go(self, case, phase, timer=0.0): + self.phase, self.timer = phase, timer + self.state = {"emerge": "emerge", "roar": "emerge", "chase": "chase", "windup": "windup", + "smash": "windup", "recover": "chase", "boom": "boom", "boom_recover": "boom"}[phase] + case.events.append(("warden_phase", phase)) + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0) + self.boom_cd = max(self.boom_cd - 1, 0) + self.tint_t = max(self.tint_t - 1, 0) + self.timer -= 1 / FPS + if case.t % ticks(120) == 0: # Java: Darkness to players within 20 blocks every 6 s + if float(np.linalg.norm(p.pos - e.pos)) <= 20.0: + self.dark_t = ticks(260) + case.events.append("warden_darkness") + self.dark_t = max(self.dark_t - 1, 0) + to = p.pos - e.pos + flat = float(math.hypot(to[0], to[2])) + wish, speed = np.zeros(3), 0.0 + reach = self.in_reach(case) + if self.phase == "emerge": + if self.timer <= 0: + self._go(case, "roar", float(k.roar_s)) + case.events.append("warden_roar") + elif self.phase == "roar": + e.yaw = math.atan2(to[2], to[0]) + if self.timer <= 0: + self._go(case, "chase") + elif self.phase in ("chase", "recover"): + wish = self.steer(case) + e.yaw = math.atan2(wish[2], wish[0]) if wish.any() else e.yaw + speed = k.speed * (0.45 if self.phase == "recover" else 1.0) + self.out_of_reach = 0 if reach else self.out_of_reach + 1 + if self.phase == "recover" and self.timer <= 0: + self.phase = "chase" + if self.cd == 0 and reach: + self._go(case, "windup", max(0.05, float(k.windup))) + case.events.append("warden_windup") + elif (self.boom_cd == 0 and self.out_of_reach >= ticks(20 * k.boom_every) + and flat <= 15.0 and abs(to[1]) <= 20.0): + self._go(case, "boom", 1.7) + case.events.append("warden_boom_charge") + elif self.phase == "windup": + e.yaw = math.atan2(to[2], to[0]) + speed = k.speed * 0.2 + wish = e.fwd + if self.timer <= 0: + if self.in_reach(case): + if self.hurt_player(case, k.dmg, fling=0.5): + case.events.append("warden_smash") + else: + case.events.append("warden_whiff") + self.cd = ticks(k.cooldown) + self.out_of_reach = 0 + self._go(case, "recover", 0.6) # turns slowly after a swing: the opening + elif self.phase == "boom": + e.yaw = math.atan2(to[2], to[0]) + if self.timer <= 0: + self.booms += 1 + if flat <= 15.0 and abs(to[1]) <= 20.0: + # Java: lands at once if the target is still in range; ignores armor, shields and walls + if self.hurt_player(case, k.boom_dmg, fling=1.2, armor=False, lift=0.1): + case.events.append("warden_boom_hit") + else: + case.events.append("warden_boom_miss") + self.out_of_reach, self.boom_cd = 0, ticks(20 * 5) + self._go(case, "boom_recover", 1.3) + elif self.phase == "boom_recover": + if self.timer <= 0: + self._go(case, "chase") + if flat < 0.6: + wish = 0 * wish + blocked, _ = physics(case, e, wish, speed, step=0.0) + if blocked and e.on_ground: + e.vel[1] = JUMP + self.ph = (self.ph + float(math.hypot(e.vel[0], e.vel[2])) * 0.7) % 1.0 + self.pose(case) + + def pose(self, case): + mcskin.pose_warden(self, case) + + +class Skeleton(Mob): + """Java Edition 1.21 skeleton (minecraft.wiki/w/Skeleton, read 2026-11-02) as a boss: an armoured archer in ruins. + + It keeps its distance and circles: it backs off when the player comes within 4 blocks, strafes around at mid range + (switching direction now and then) and closes in when the player is 14+ blocks away. With line of sight within + 15 blocks it draws (visible: bow up, string back) and fires; Java fires every 3 s on Easy / Normal and every 2 s on + Hard, aims 0.2 blocks higher per block of range and has an arrow 'error' of 10 / 6 / 2 (the player's is 1). + Arrows are real projectiles (gravity, drag, stopped by terrain): side-stepping and cover work. Java arrow damage + 2-4 / 3-5 / 4-8. It has no melee while it holds its bow. + + BossBench deviations (minecraft-arena@5): health per tier (Java 20); it wears armor (iron on easy / normal pieces, + Java's armor-spawn chances made certain) so that the fight lasts; its draw time is a telegraph knob. + """ + TABLE = { # (easy, normal, hard) = TIERS + "hp": (200, 500, 1050), # TIER calibration (Java 20) + "speed": (0.12, 0.138, 0.16), # vanilla b/t; Java 0.138 = attribute 0.25 (SPEED_NOTE); strafes at half + "interval": (60, 60, 40), # vanilla ticks between shots (Java 3 s / 3 s / 2 s) + "draw": (1.0, 0.85, 0.7), # EXT seconds of visible draw before the release + "error": (10.0, 6.0, 2.0), # Java arrow inaccuracy (player 1) + "arrow_min": (2.0, 3.0, 4.0), # Java arrow damage range per difficulty + "arrow_max": (4.0, 5.0, 8.0), + "armor": (8.0, 12.0, 15.0), # worn iron pieces (Java armor-spawn chance made certain): helmet + + # chestplate / + leggings / full set + } + MOVES = {"arrow": {"atoms": ["projectile_arc"], "telegraph": "bow raised and drawn back for most of a second", + "damage": "Java 2-4 / 3-5 / 4-8 then armor", "range": "up to 15 blocks with line of sight", + "punish": "3 s (2 s on hard) between shots; arrows fly in an arc and stop on walls"}, + "kite": {"atoms": ["retreat", "strafe"], "telegraph": "-", "damage": "-", + "range": "backs off inside 4 blocks, closes in beyond 14", + "punish": "corner it against the ruins or the arena wall"}} + SKILLS = ("projectile_dodge", "cover_use", "aim_tracking", "chase", "weapon_switch") + STATES = ("chase", "windup", "swing", "recover") + name = "skeleton" + height, aim_h = 1.99, 1.0 + half = (0.3, 0.3) + knockback = 1.0 + + def reset(self, case): + super().reset(case) + self.max_hp = self.hp = self.k.hp + self.armor = float(self.k.armor) + self.e = Entity(MID + 8.0, 0.0, MID, math.pi, 0.6, self.height) + self.state, self.timer, self.cd, self.iframes = "chase", 0.0, ticks(40), 0 + self.ph, self.tint_t = 0.0, 0 + self.strafe_dir, self.strafe_t = 1.0, 0 + self.draw_t, self.shots, self.arrows = 0.0, 0, [] + self.rig = skeleton_rig() + + @property + def enraged(self): + return False + + def sees(self, case): + eye = self.e.pos + [0, 1.74, 0] + return case.arena.los(eye, case.body.e.pos + [0, 1.2, 0], eye_h=0.0) + + def update(self, case): + k, e, p = self.k, self.e, case.body.e + self.iframes, self.cd = max(self.iframes - 1, 0), max(self.cd - 1, 0) + self.tint_t = max(self.tint_t - 1, 0) + self.timer -= 1 / FPS + self._arrows(case) + to = p.pos - e.pos + flat = float(math.hypot(to[0], to[2])) + e.yaw = math.atan2(to[2], to[0]) + sees = self.sees(case) + # -- movement (Java RangedBowAttackGoal: approach beyond range, back off inside 4 blocks, strafe otherwise) -- + self.strafe_t -= 1 + if self.strafe_t <= 0: + self.strafe_t = ticks(20 + int(case.rng.integers(0, 40))) + if case.rng.random() < 0.3: + self.strafe_dir = -self.strafe_dir + if not sees or flat >= 14.0: + wish, speed = self.steer(case), k.speed + elif flat < 4.0: + wish = -e.fwd + e.right * self.strafe_dir * 0.5 + speed = k.speed + else: + wish, speed = e.right * self.strafe_dir, k.speed * 0.5 + n = float(math.hypot(wish[0], wish[2])) + wish = wish / n if n > 1e-9 else wish + # -- bow -- + if self.state == "chase": + if self.cd == 0 and sees and flat <= 15.0: + self.state, self.timer = "windup", float(k.draw) + case.events.append("skeleton_draw") + elif self.state == "windup": + speed *= 0.5 + if not sees or flat > 16.0: # lost sight: keeps the bow drawn, fires when it sees again (Java) + self.timer = max(self.timer, 1 / FPS) + elif self.timer <= 0: + self._shoot(case) + self.state, self.timer = "swing", 0.15 + elif self.state == "swing": + if self.timer <= 0: + self.state, self.cd = "recover", ticks(k.interval - 20 * k.draw) + elif self.state == "recover" and self.cd == 0: + self.state = "chase" + blocked, _ = physics(case, e, wish, speed, step=0.0) + if blocked and e.on_ground: + e.vel[1] = JUMP + self.strafe_dir = -self.strafe_dir # cornered against cover: strafe the other way + self.ph = (self.ph + float(math.hypot(e.vel[0], e.vel[2])) * 1.1) % 1.0 + self.pose(case) + + def _shoot(self, case): + """Java AbstractSkeleton.performRangedAttack: aims at a third of the target's height, 0.2 blocks higher per block + of horizontal range, speed 1.6 b/t, inaccuracy 14 - 4 x difficulty (10 / 6 / 2): each axis of the unit + direction gets a triangular deviation of 0.0172275 x inaccuracy (Projectile.getMovementToShoot).""" + k, e, p = self.k, self.e, case.body.e + start = e.pos + [0, 1.6, 0] + e.fwd * 0.4 + target = p.pos + [0, PLAYER_H / 3, 0] + d = target - start + horiz = float(math.hypot(d[0], d[2])) + d[1] += horiz * 0.2 + n = float(np.linalg.norm(d)) + 1e-9 + spread = 0.0172275 * k.error + direction = d / n + (case.rng.random(3) - case.rng.random(3)) * spread + direction /= float(np.linalg.norm(direction)) + 1e-9 + self.shots += 1 + self.arrows.append({"id": self.shots, "pos": start, "vel": direction * per_vt(1.6), "age": 0, + "damage": float(case.rng.uniform(k.arrow_min, k.arrow_max))}) + case.events.append(("skeleton_shot", self.shots)) + + def _arrows(self, case): + p, keep = case.body.e, [] + lo, hi = p.pos - [PLAYER_W / 2, 0.0, PLAYER_W / 2], p.pos + [PLAYER_W / 2, PLAYER_H, PLAYER_W / 2] + for a in self.arrows: + start, end = a["pos"], a["pos"] + a["vel"] + hit_p = _segment_box(start, end, lo, hi) + hit_w, _ = case._arrow_world_hit(start, end) + if hit_p is not None and (hit_w is None or hit_p <= hit_w): + if self.hurt_player(case, a["damage"], fling=0.3, origin=start): + case.events.append("skeleton_arrow_hit") + continue + if hit_w is not None or a["age"] > FPS * 6: + case.events.append("skeleton_arrow_blocked") + continue + a["pos"] = end + a["vel"] = a["vel"] * decay(0.99) + a["vel"][1] -= 0.05 * VT * VT + a["age"] += 1 + keep.append(a) + self.arrows = keep + + def pose(self, case): + mcskin.pose_skeleton(self, case) + + def extra(self, case): + return [] # arrows are drawn by mcskin.arrow_rows (same look as the player's) + + +# ---------------------------------------------------------------- rigs +golem_rig, zombie_rig = mcskin.golem_rig, mcskin.zombie_rig +dragon_rig, wither_rig = mcskin.dragon_rig, mcskin.wither_rig +warden_rig, skeleton_rig = mcskin.warden_rig, mcskin.skeleton_rig + + +# ---------------------------------------------------------------- case +MOBS = {"iron_golem": IronGolem, "zombie": Zombie, "ender_dragon": EnderDragon, "wither": Wither, + "warden": Warden, "skeleton": Skeleton, "zombie_leader": ZombieLeader} + + +class MobFight(Case): + """Arena + player + one mob. One class serves every boss; `mob` picks the boss.""" + R = 3 + obs_dim = 12 + 14 + (2 * R + 1) ** 2 + # per-boss observation extras: wither 3 nearest skulls x 7, skeleton 3 nearest arrows x 7, leader zombie 3 nearest + # reinforcements x 4, warden boom charge / time out of reach / darkness (the last three since minecraft-arena@5; + # the formal zombie case has none, as in @4) + EXTRA_OBS = {"wither": 21, "skeleton": 21, "zombie_leader": 12, "warden": 3} + + # The camera changes only the image. Third-person is available through the reset options. + def __init__(self, mob="iron_golem", style="field", width=RES[0], height=RES[1], camera="first", + max_seconds=120.0, weapon='sword'): + self.default_weapon, self.default_camera = _weapon(weapon), _camera(camera) + self.mob_name = mob + self.max_seconds = max_seconds + self.obs_dim = MobFight.obs_dim + self.EXTRA_OBS.get(mob, 0) + super().__init__(VoxelArena(style), Steve(weapon), MOBS[mob]()) + self.name = f"minecraft_{mob}_1v1" + self.size, self.camera, self._gl = (width, height), camera, None + self.render_error = None + + def reset(self, seed, d, options=None): + options = dict(options or {}) + weapon = _weapon(options.get('weapon', self.default_weapon)) + camera = _camera(options.get('camera', self.default_camera)) + self.body.weapon, self.camera = weapon, camera + self.render_error = None + self.arrows = [] + super().reset(seed, d) + self.fxrng = np.random.default_rng((int(seed) * 2654435761 + 0x9E3779B9) % (2 ** 32)) + self.fx = [] + if self.body.weapon == 'bow': + self.body.pose(self) # establish visible bow pose before frame zero + + def hurt_player(self, dmg, armor=True, iframes=True, share=1.0): + """Java LivingEntity.hurt for the player. A hit starts 10 vanilla ticks of immunity; inside the window + only a stronger raw hit lands, dealing the difference (no knockback, no new window). Returns "fresh", + "partial" or False. share < 1: this tick's part of a per-vanilla-tick damage (armor sees the whole hit); + iframes=False: damage that neither starts nor respects the window (fall, Wither effect, breath).""" + b = self.body + landed = "fresh" + if iframes: + if b.iframes > 0: + if dmg <= b.last_hurt: + return False + dmg, b.last_hurt, landed = dmg - b.last_hurt, dmg, "partial" + else: + b.last_hurt, b.iframes = dmg, ticks(10) + if armor: + dmg = armor_reduce(dmg, b.k.armor, b.k.toughness) + dmg *= share + b.hp -= dmg + self.events.append(("player_hit", round(float(dmg), 2))) + return landed + + + def interact(self): + p = self.body.e + if self.boss.hover: + return + # bodies push the player out (the boss, and since minecraft-arena@5 any living reinforcement); a zombie horde + # can pin a player against cover this way + for mob in [self.boss] + [z for z in getattr(self.boss, "minions", ()) if z.hp > 0]: + g = mob.e + d = p.pos[[0, 2]] - g.pos[[0, 2]] + dist, need = float(np.linalg.norm(d)), (PLAYER_W + 2 * mob.half[0]) / 2 + if dist < need and abs(p.pos[1] - g.pos[1]) < mob.height: + push = d / (dist + 1e-6) * (need - dist) + new = p.pos.copy() + new[[0, 2]] += push + if self.arena.ground(new, PLAYER_W) <= p.pos[1] + 0.6: + p.pos = new + + def track(self): + """Advance visual-only state after the rules ran: pose the player, step particles. Draws + from case.fxrng only, never touches gameplay state.""" + self.body.pose(self) + mcskin.step_fx(self) + + def tick(self, action): + self._ev0 = len(self.events) # first event of this tick (fx juice reads only new ones) + self.body.apply(self, action) + self.boss.update(self) + if self.arrows: + self._update_arrows() + self.arena.update(self) + self.interact() + self.track() + self.t += 1 + + def _arrow_world_hit(self, start, end): + """Swept collision against actual voxel columns and the arena floor.""" + radius = BOW_RULES['arrow_radius_blocks'] + first, reason = None, None + for axis in (0, 2): + if start[axis] < 0 or start[axis] > S: + return 0.0, 'bounds' + if end[axis] < 0 or end[axis] > S: + boundary = 0.0 if end[axis] < 0 else float(S) + value = (boundary - start[axis]) / (end[axis] - start[axis]) + if first is None or value < first: + first, reason = value, 'bounds' + low = np.floor(np.minimum(start, end)[[0, 2]] - radius).astype(int) + high = np.floor(np.maximum(start, end)[[0, 2]] + radius).astype(int) + for x in range(max(0, low[0]), min(S - 1, high[0]) + 1): + for z in range(max(0, low[1]), min(S - 1, high[1]) + 1): + height = float(self.arena.H[x, z]) + hit = _segment_box(start, end, + np.array([x - radius, -radius, z - radius]), + np.array([x + 1 + radius, height + radius, z + 1 + radius])) + if hit is not None and (first is None or hit < first): + first, reason = hit, 'ground' if height == 0 else 'voxel' + return first, reason + + def _targets(self): + """Damageable boxes for arrows and the sword ray: (kind, lo, hi, payload).""" + g, out = self.boss, [] + if hasattr(g, "hitboxes"): + out += [("boss", lo, hi, part) for part, lo, hi in g.hitboxes()] + else: + out.append(("boss", g.hit_lo(), g.hit_hi(), "body")) + for c in getattr(g, "crystals", ()): + if c["alive"]: + out.append(("crystal", c["pos"] - [0.5, 0.0, 0.5], c["pos"] + [0.5, 1.6, 0.5], c)) + for z in getattr(g, "minions", ()): # zombie reinforcements (minecraft-arena@5) + if z.hp > 0: + out.append(("minion", z.hit_lo(), z.hit_hi(), z)) + return out + + def _damage(self, kind, payload, dmg, how, bonus_knockback=0.0): + g = self.boss + if kind == "crystal": + g.crystal_destroyed(self, payload) + return 0.0 + if kind == "minion": # a reinforcement's health is not the boss's health + payload.take_hit(self, dmg, how, bonus_knockback=bonus_knockback) + return 0.0 + before = max(0.0, float(g.hp)) + if hasattr(g, "hitboxes"): + g.take_hit(self, dmg, how, bonus_knockback=bonus_knockback, part=payload) + else: + g.take_hit(self, dmg, how, bonus_knockback=bonus_knockback) + return max(0.0, before - max(0.0, float(g.hp))) + + def _update_arrows(self): + kept = [] + radius = BOW_RULES['arrow_radius_blocks'] + for arrow in self.arrows: + if arrow['age'] >= FPS * BOW_RULES['maximum_life_seconds']: + self.events.append(('arrow_expired', arrow['id'])) + continue + start, end = arrow['pos'], arrow['pos'] + arrow['vel'] + world_hit, reason = self._arrow_world_hit(start, end) + best = None + for kind, lo, hi, payload in self._targets(): + u = _segment_box(start, end, lo - radius, hi + radius) + if u is not None and (best is None or u < best[0]): + best = (u, kind, payload) + if world_hit is not None and (best is None or world_hit <= best[0]): + self.events.append(('arrow_blocked', arrow['id'], reason)) + continue + if best is not None: + _, kind, payload = best + damage = math.ceil(float(np.linalg.norm(arrow['vel'])) / VT + * BOW_RULES['base_damage_per_speed']) + if arrow['critical']: + damage += int(self.rng.integers(0, damage // 2 + 2)) + actual = self._damage(kind, payload, damage, 'arrow_critical' if arrow['critical'] else 'arrow') + if actual > 0: + self.body.arrows_hit += 1 + self.body.arrow_damage += actual + self.events.append(('arrow_hit', arrow['id'], round(actual, 4), kind)) + continue + arrow['pos'] = end + arrow['vel'] *= decay(BOW_RULES['drag_per_vanilla_tick']) + arrow['vel'][1] -= BOW_RULES['gravity_blocks_per_vanilla_tick_squared'] * VT * VT + arrow['age'] += 1 + kept.append(arrow) + self.arrows = kept + + + # -- observation ------------------------------------------------------- + def _rel(self): + p, g = self.body.e, self.boss.e + d = g.pos - p.pos + bearing = math.atan2(d[2], d[0]) - p.yaw + return d, math.hypot(d[0], d[2]), math.atan2(math.sin(bearing), math.cos(bearing)) + + def observe(self): + b, g, p = self.body, self.boss, self.body.e + d, dist, bearing = self._rel() + H = np.pad(self.arena.H, self.R, constant_values=WALL_CAP).astype(np.float32) + ix, iz = int(p.pos[0]) + self.R, int(p.pos[2]) + self.R + local = (H[max(ix - self.R, 0):ix + self.R + 1, max(iz - self.R, 0):iz + self.R + 1] - p.pos[1]) / 4 + mine = [p.pos[0] / S, p.pos[1] / 4, p.pos[2] / S, *p.vel / VT * 4, math.sin(p.yaw), math.cos(p.yaw), + b.hp / b.max_hp, b.charge, float(p.on_ground)] + states = type(g).STATES + hot = g.state in ("windup", "lineup", "charge") + boss = [*d / 8, dist / 8, math.sin(bearing), math.cos(bearing), g.hp / g.max_hp, + *np.eye(4)[states.index(g.state)], max(g.timer, 0) if hot else 0, + min(g.cd / FPS, 2.0), float(g.enraged), float(g.in_reach(self))] + extra = [] + skulls = getattr(g, "skulls", None) + if skulls is not None: # three nearest skulls, in player-relative terms + order = sorted(skulls, key=lambda s: float(np.linalg.norm(s["pos"] - p.pos)))[:3] + for s in order: + rel = s["pos"] - p.pos + extra += [*rel / 8, *s["vel"] / VT / 2, float(s["life"])] + extra += [0.0] * (3 - len(order)) * 7 + if isinstance(g, Skeleton): # three nearest skeleton arrows + order = sorted(g.arrows, key=lambda a: float(np.linalg.norm(a["pos"] - p.pos)))[:3] + for a in order: + rel = a["pos"] - p.pos + extra += [*rel / 8, *a["vel"] / VT / 2, a["age"] / FPS] + extra += [0.0] * (3 - len(order)) * 7 + if isinstance(g, ZombieLeader): # three nearest live reinforcements + live = sorted((z for z in g.minions if z.hp > 0), key=lambda z: float(np.linalg.norm(z.e.pos - p.pos)))[:3] + for z in live: + extra += [*(z.e.pos - p.pos) / 8, z.hp / z.max_hp] + extra += [0.0] * (3 - len(live)) * 4 + if isinstance(g, Warden): + extra += [max(g.timer, 0.0) if g.phase == "boom" else 0.0, min(g.out_of_reach / FPS, 10.0) / 10.0, + g.dark_t / ticks(260)] + return np.concatenate([mine, boss, extra, local.ravel()]).astype(np.float32) + + def state(self): + b, g = self.body, self.boss + d, dist, bearing = self._rel() + mob = {"pos": g.e.pos.round(2).tolist(), "hp": round(g.hp, 2), "max_hp": round(g.max_hp, 1), + "state": g.state, "timer": round(max(g.timer, 0), 2), "cooldown_s": round(g.cd / FPS, 2), + "enraged": bool(g.enraged), "distance": round(dist, 2), + "distance3d": round(float(np.linalg.norm(d)), 2), + "bearing_deg": round(math.degrees(bearing), 1), "in_reach": g.in_reach(self), + "iframes": int(g.iframes), "yaw_deg": round(math.degrees(g.e.yaw), 1)} + if g.state == "windup": + mob["windup_left"] = round(max(g.timer, 0), 2) + if getattr(g, "skulls", None): + mob["skulls"] = [{"pos": s["pos"].round(2).tolist(), "vel": (s["vel"] * FPS).round(2).tolist(), # b/s + "blue": bool(s.get("blue", False))} for s in g.skulls] + if hasattr(g, "phase"): + mob["phase"] = g.phase + if hasattr(g, "armored"): + mob["armored"] = bool(g.armored) + if hasattr(g, "crystals"): + mob["crystals"] = [{"id": c["id"], "pos": c["pos"].round(2).tolist(), "alive": bool(c["alive"])} + for c in g.crystals] + mob["healing_from"] = None if g.heal_from is None else g.heal_from["id"] + mob["fireballs"] = [{"pos": f["pos"].round(2).tolist()} for f in g.fireballs] + mob["clouds"] = [{"pos": c["pos"].round(2).tolist(), "r": round(c["r"], 2), "kind": c["kind"], + "life": round(c["life"], 2)} for c in g.clouds] + if isinstance(g, ZombieLeader): + mob["minions"] = [{"n": z.n, "pos": z.e.pos.round(2).tolist(), "hp": round(z.hp, 2), "state": z.state} + for z in g.minions if z.hp > 0] + mob["reinforce_chance"] = round(g.chance, 4) + mob["summoned"] = g.summoned + if isinstance(g, Warden): + mob["darkness_s"] = round(g.dark_t / FPS, 2) + mob["out_of_reach_s"] = round(g.out_of_reach / FPS, 2) + mob["booms"] = g.booms + if isinstance(g, Skeleton): + mob["arrows"] = [{"id": a["id"], "pos": a["pos"].round(3).tolist(), "vel": (a["vel"] * FPS).round(3).tolist()} + for a in g.arrows] + mob["shots"] = g.shots + result = {"rules": RULES, + "player": {"pos": b.e.pos.round(2).tolist(), "yaw_deg": round(math.degrees(b.e.yaw), 1), + "pitch_deg": round(math.degrees(b.e.pitch), 4), "weapon": b.weapon, + "hp": round(b.hp, 2), "max_hp": b.max_hp, "attack_charge": round(b.attack_charge, 2), + "on_ground": b.e.on_ground, "sprinting": bool(b.sprinting), + "iframes": int(b.iframes), "wither_effect_s": round(b.wither_t / FPS, 2)}, + "boss": mob, + "boss_kind": self.mob_name, "boss_skills": list(self.boss.SKILLS)} + result['player'].update(bow_charge=round(b.bow_charge, 6), bow_drawing=b.bow_drawing, + arrows_fired=b.arrows_fired, arrows_hit=b.arrows_hit, + arrow_damage=round(b.arrow_damage, 6), melee_damage=round(b.melee_damage, 6)) + result['arrows'] = [{'id': arrow['id'], 'pos': arrow['pos'].round(4).tolist(), + 'vel': (arrow['vel'] * FPS).round(4).tolist(), 'age': arrow['age'], + 'damage': arrow['damage'], 'critical': arrow['critical']} for arrow in self.arrows] + result['weapon_rules'] = dict(BOW_RULES) + return result + + + # -- rendering --------------------------------------------------------- + def render(self, t=None): + try: + if self._gl is None: + self._gl = mcskin.VoxelRenderer(*self.size) + img = self._gl.draw(self, t) + self.render_error = None + except Exception as ex: # no GL context: top-down map, reason kept for debugging + self.render_error = repr(ex) + renderer, self._gl = self._gl, None + if renderer is not None: + try: + renderer.close() + except Exception as close_ex: + self.render_error += f"; cleanup: {close_ex!r}" + img = self._topdown() + return mcskin.hud(img, self) + + def close(self): + """Release the lazy renderer; a later render can create a fresh context.""" + renderer, self._gl = self._gl, None + if renderer is not None: + renderer.close() + + def _topdown(self): + W, H = self.size + T = H // S + img = np.zeros((H, W, 3), np.uint8) + pal = np.array([[90, 150, 60], [150, 110, 60], [120, 120, 120], [100, 100, 110], [60, 60, 60], + [70, 70, 75], [80, 80, 85], [95, 95, 100], [110, 110, 115]], np.uint8) + ox = (W - S * T) // 2 + world = img[:S * T, ox:ox + S * T] + world[:] = pal[np.clip(self.arena.H.T, 0, 8)].repeat(T, 0).repeat(T, 1) + for e, c in ((self.boss.e, (220, 215, 205)), (self.body.e, (40, 120, 230))): + x, z, r = int(e.pos[0] * T), int(e.pos[2] * T), int(e.w * T / 2) + world[max(z - r, 0):z + r, max(x - r, 0):x + r] = c + return img + + +# ---------------------------------------------------------------- factories +STYLES = {"iron_golem": "field", "zombie": "field", "ender_dragon": "towers", "wither": "towers", + "warden": "deep_dark", "skeleton": "ruins", "zombie_leader": "night"} +SECONDS = {"iron_golem": 300.0, "zombie": 90.0, "ender_dragon": 300.0, "wither": 300.0, # hard tier ~3 min (@4) + "warden": 300.0, "skeleton": 300.0, "zombie_leader": 300.0} + + +def make(mob="iron_golem", **kw) -> BossBenchEnv: + case_kw = {k: kw.pop(k) for k in ("style", "width", "height", "camera", "weapon") if k in kw} + case_kw.setdefault("style", STYLES.get(mob, "field")) + seconds = kw.pop("max_seconds", SECONDS.get(mob, 120.0)) + return BossBenchEnv(MobFight(mob, max_seconds=seconds, **case_kw), max_seconds=seconds, **kw)