#!/usr/bin/env python3
"""Rhem open challenges: Copycat, Pillow Fight and One Cookie.

Three games for one simulated humanoid. Each has a score that nobody can max.

    pip install mujoco numpy
    python rhem_challenges.py pillow-fight                      # run the starter policy
    python rhem_challenges.py pillow-fight --policy mine.py     # run yours
    python rhem_challenges.py copycat --policy mine.py --episodes 50
    python rhem_challenges.py copycat --video copycat.mp4       # watch an episode
                                                                # (pip install imageio imageio-ffmpeg)

THE GAMES
    copycat       A ghost strikes poses, live, with no preview. Copy it without
                  falling. Score is a cost, lower is better. The starter scores 100.
    pillow-fight  Pillows fly in from every side and each one that lands makes the
                  next 2% heavier. Score is the pillows you take before you fall.
    one-cookie    You get the energy in one cookie (50 kcal). Score is how many
                  meters you walk before it runs out. The starter shuffles.

YOUR POLICY
    A Python file with one class. `act` is called 50 times a second.

        import numpy as np

        class Policy:
            def __init__(self, spec):   # spec: joint names, limits, standing pose, ...
                self.stand = spec["stand_pose"]

            def reset(self):            # optional, called before every episode
                pass

            def act(self, obs):         # returns 21 target joint angles, in radians
                return self.stand

    The robot holds each target with a fixed PD loop and limited torque, so the
    action is "where each joint should go", like on a real robot.

    obs is a dict of numpy arrays:
        time            seconds since the episode started
        joint_pos       (21,) joint angles, rad, in spec["joint_names"] order
        joint_vel       (21,) joint velocities, rad/s
        root_pos        (3,)  torso position, m, world frame
        root_quat       (4,)  torso orientation, w x y z
        root_lin_vel    (3,)  torso velocity, m/s, world frame
        root_ang_vel    (3,)  torso angular velocity, rad/s, body frame
        foot_pos        (2, 3) right and left ankle position, m, world frame
        foot_force      (2,)  how hard each foot presses on the floor, N
        cop             (2,)  center of pressure under the feet, m, world x y
      copycat adds
        ghost_joint_pos (21,)   the ghost's pose right now, as joint angles
        ghost_segments  (10, 3) the same pose as limb directions (what is scored)
      pillow-fight adds
        pillows         (6, 7)  position, velocity and mass of each pillow in the air
        pillow_flying   (6,)    which rows of `pillows` are real
      one-cookie adds
        energy_left     joules left in the cookie
        distance        meters walked so far

RULES
    Any method, any training data, any amount of training compute. The submitted
    policy has to average under 20 ms per step on a laptop CPU with no network.
    Scores on the public board come from seeds that are not in this file.
    A fall is anything but your feet touching the floor, or your head dropping
    below one meter. The same seed gives the same episode on the same machine.

ENTERING
    Every run ends with a line that starts with RESULT. Email that line, your
    policy file and a few sentences on how it works to support@rhem.ai. We run
    it again on our own seeds and add the score to the board at
    https://www.rhem.ai/careers.

TRAINING
    The same environment is importable:

        import rhem_challenges as rc
        env = rc.Env("pillow-fight")
        obs = env.reset(seed=0)
        while not env.done:
            obs, done, info = env.step(action)
        print(env.score())

    env.model and env.data are the raw MuJoCo objects if you want more than obs.

Kit code: Copyright 2026 Rhem Labs, MIT License.
The humanoid is adapted from MuJoCo's model/humanoid/humanoid.xml, Copyright 2021
DeepMind Technologies Limited, Apache License 2.0
(https://www.apache.org/licenses/LICENSE-2.0). Changes: position actuators,
stronger ankle pitch, lighter arms, wider feet, an arms-down standing pose,
recolored materials and lights, pillows added, cameras and keyframes removed.
"""
from __future__ import annotations

import argparse
import hashlib
import importlib.util
import json
import sys
import time
from pathlib import Path

import mujoco
import numpy as np

KIT_VERSION = "1.0.0"
OFFICIAL_MUJOCO = "4.0.1"  # the version official scores are computed with

GAMES = ("copycat", "pillow-fight", "one-cookie")

PHYSICS_DT = 0.005  # s
SUBSTEPS = 4  # physics steps per policy step
CONTROL_DT = PHYSICS_DT * SUBSTEPS  # 0.02 s, so the policy runs at 50 Hz
STEP_BUDGET_MS = 20.0

HEAD_MIN_Z = 1.0  # m. Below this the robot has fallen.
STAND_Z = 1.285  # m. Torso height when standing.
SETTLE_S = 1.0  # the robot stands for this long before an episode starts

# Energy model, shared by Copycat's power term and One Cookie's budget.
#   joint power = positive mechanical power + resistive heat
#   heat        = HEAT_W_PER_NM * torque^2 / torque_limit   (a stalled motor burns
#                 HEAT_W_PER_NM watts for every N·m of its limit)
# Braking returns nothing: there is no regeneration.
HEAT_W_PER_NM = 1.5
IDLE_W = 40.0  # the computer. Counted in One Cookie, where standing still is not free.

# Joint, PD stiffness (N·m/rad), PD damping (N·m·s/rad), torque limit (N·m).
ACTUATORS = (
    ("abdomen_z", 600, 30, 40),
    ("abdomen_y", 600, 30, 40),
    ("abdomen_x", 600, 30, 40),
    ("hip_x_right", 600, 30, 40),
    ("hip_z_right", 400, 20, 40),
    ("hip_y_right", 800, 40, 120),
    ("knee_right", 800, 40, 80),
    ("ankle_y_right", 1000, 50, 40),
    ("ankle_x_right", 600, 30, 20),
    ("hip_x_left", 600, 30, 40),
    ("hip_z_left", 400, 20, 40),
    ("hip_y_left", 800, 40, 120),
    ("knee_left", 800, 40, 80),
    ("ankle_y_left", 1000, 50, 40),
    ("ankle_x_left", 600, 30, 20),
    ("shoulder1_right", 150, 8, 20),
    ("shoulder2_right", 150, 8, 20),
    ("elbow_right", 150, 6, 40),
    ("shoulder1_left", 150, 8, 20),
    ("shoulder2_left", 150, 8, 20),
    ("elbow_left", 150, 6, 40),
)
JOINT_NAMES = tuple(a[0] for a in ACTUATORS)
NU = len(ACTUATORS)
TORQUE_LIMIT = np.array([a[3] for a in ACTUATORS], dtype=float)


def _joint(name: str) -> int:
    return JOINT_NAMES.index(name)


# Standing pose: legs straight, arms hanging by the sides, weight over mid-foot.
STAND_POSE = np.zeros(NU)
for _side in ("right", "left"):
    STAND_POSE[_joint(f"ankle_y_{_side}")] = -0.03
    STAND_POSE[_joint(f"shoulder1_{_side}")] = 0.7422
    STAND_POSE[_joint(f"shoulder2_{_side}")] = -0.4240
    STAND_POSE[_joint(f"elbow_{_side}")] = -1.6507

# The ten limbs Copycat compares, each as (name, from body, to body).
SEGMENTS = (
    ("spine", "pelvis", "torso"),
    ("head", "torso", "head"),
    ("upper_arm_right", "upper_arm_right", "lower_arm_right"),
    ("forearm_right", "lower_arm_right", "hand_right"),
    ("upper_arm_left", "upper_arm_left", "lower_arm_left"),
    ("forearm_left", "lower_arm_left", "hand_left"),
    ("thigh_right", "thigh_right", "shin_right"),
    ("shin_right", "shin_right", "foot_right"),
    ("thigh_left", "thigh_left", "shin_left"),
    ("shin_left", "shin_left", "foot_left"),
)

_HUMANOID_XML = r"""
<mujoco model="rhem-practice-humanoid">
  <option timestep="0.005" integrator="implicitfast"/>

  <visual>
    <map force="0.1" zfar="30"/>
    <rgba haze="0.984 0.980 0.973 1"/>
    <global offwidth="1280" offheight="720" elevation="-12" azimuth="140"/>
    <headlight ambient="0.72 0.72 0.72" diffuse="0.08 0.08 0.08" specular="0 0 0"/>
    <quality shadowsize="4096"/>
  </visual>

  <statistic center="0 0 0.8" extent="2.2"/>

  <asset>
    <texture type="skybox" builtin="flat" rgb1="0.984 0.980 0.973" rgb2="0.984 0.980 0.973" width="32" height="32"/>
    <material name="body" rgba="0.133 0.137 0.129 1" specular="0.15" shininess="0.2"/>
    <texture name="floor" type="2d" builtin="flat" mark="edge" rgb1="0.984 0.980 0.973" markrgb="0.9 0.89 0.865" width="400" height="400"/>
    <material name="floor" texture="floor" texrepeat="1 1" texuniform="true" reflectance="0"/>
    <material name="pillow" rgba="1 0.733 0 1" specular="0.05" shininess="0.05"/>
  </asset>

  <default>
    <default class="body">
      <geom type="capsule" condim="1" friction=".7" solimp=".9 .99 .003" solref=".015 1" material="body" group="1"/>
      <default class="thigh"><geom size=".06"/></default>
      <default class="shin"><geom fromto="0 0 0 0 0 -.3" size=".049"/></default>
      <default class="foot">
        <geom size=".03"/>
        <default class="foot1"><geom fromto="-.08 -.02 0 .15 -.05 0"/></default>
        <default class="foot2"><geom fromto="-.08 .02 0 .15 .05 0"/></default>
      </default>
      <default class="arm_upper"><geom size=".04" density="400"/></default>
      <default class="arm_lower"><geom size=".031" density="400"/></default>
      <default class="hand"><geom type="sphere" size=".04" density="400"/></default>

      <joint type="hinge" damping=".2" stiffness="1" armature=".01" limited="true" solimplimit="0 .99 .01"/>
      <default class="joint_big">
        <joint damping="5" stiffness="10"/>
        <default class="hip_x"><joint range="-30 10"/></default>
        <default class="hip_z"><joint range="-60 35"/></default>
        <default class="hip_y"><joint axis="0 1 0" range="-150 20"/></default>
        <default class="joint_big_stiff"><joint stiffness="20"/></default>
      </default>
      <default class="knee"><joint pos="0 0 .02" axis="0 -1 0" range="-160 2"/></default>
      <default class="ankle">
        <joint range="-50 50"/>
        <default class="ankle_y"><joint pos="0 0 .08" axis="0 1 0" stiffness="6"/></default>
        <default class="ankle_x"><joint pos="0 0 .04" stiffness="3"/></default>
      </default>
      <default class="shoulder"><joint range="-85 60"/></default>
      <default class="elbow"><joint range="-100 50" stiffness="0"/></default>
    </default>
    <default class="pillow">
      <geom type="ellipsoid" size=".2 .15 .07" mass="0.5" material="pillow" condim="3" friction=".6" solref=".03 1" group="2"/>
    </default>
  </default>

  <worldbody>
    <geom name="floor" size="0 0 .05" type="plane" material="floor" condim="3"/>
    <light name="key" directional="true" pos="0 0 5" dir="-0.35 0.45 -1" diffuse=".3 .3 .3" specular="0.1 0.1 0.1"/>
    <body name="torso" pos="0 0 1.285" childclass="body">
      <freejoint name="root"/>
      <geom name="torso" fromto="0 -.07 0 0 .07 0" size=".07"/>
      <geom name="waist_upper" fromto="-.01 -.06 -.12 -.01 .06 -.12" size=".06"/>
      <body name="head" pos="0 0 .19">
        <geom name="head" type="sphere" size=".09"/>
      </body>
      <body name="waist_lower" pos="-.01 0 -.26">
        <geom name="waist_lower" fromto="0 -.06 0 0 .06 0" size=".06"/>
        <joint name="abdomen_z" pos="0 0 .065" axis="0 0 1" range="-45 45" class="joint_big_stiff"/>
        <joint name="abdomen_y" pos="0 0 .065" axis="0 1 0" range="-75 30" class="joint_big"/>
        <body name="pelvis" pos="0 0 -.165">
          <joint name="abdomen_x" pos="0 0 .1" axis="1 0 0" range="-35 35" class="joint_big"/>
          <geom name="butt" fromto="-.02 -.07 0 -.02 .07 0" size=".09"/>
          <body name="thigh_right" pos="0 -.1 -.04">
            <joint name="hip_x_right" axis="1 0 0" class="hip_x"/>
            <joint name="hip_z_right" axis="0 0 1" class="hip_z"/>
            <joint name="hip_y_right" class="hip_y"/>
            <geom name="thigh_right" fromto="0 0 0 0 .01 -.34" class="thigh"/>
            <body name="shin_right" pos="0 .01 -.4">
              <joint name="knee_right" class="knee"/>
              <geom name="shin_right" class="shin"/>
              <body name="foot_right" pos="0 0 -.39">
                <joint name="ankle_y_right" class="ankle_y"/>
                <joint name="ankle_x_right" class="ankle_x" axis="1 0 .5"/>
                <geom name="foot1_right" class="foot1"/>
                <geom name="foot2_right" class="foot2"/>
              </body>
            </body>
          </body>
          <body name="thigh_left" pos="0 .1 -.04">
            <joint name="hip_x_left" axis="-1 0 0" class="hip_x"/>
            <joint name="hip_z_left" axis="0 0 -1" class="hip_z"/>
            <joint name="hip_y_left" class="hip_y"/>
            <geom name="thigh_left" fromto="0 0 0 0 -.01 -.34" class="thigh"/>
            <body name="shin_left" pos="0 -.01 -.4">
              <joint name="knee_left" class="knee"/>
              <geom name="shin_left" fromto="0 0 0 0 0 -.3" class="shin"/>
              <body name="foot_left" pos="0 0 -.39">
                <joint name="ankle_y_left" class="ankle_y"/>
                <joint name="ankle_x_left" class="ankle_x" axis="-1 0 -.5"/>
                <geom name="foot1_left" class="foot1"/>
                <geom name="foot2_left" class="foot2"/>
              </body>
            </body>
          </body>
        </body>
      </body>
      <body name="upper_arm_right" pos="0 -.17 .06">
        <joint name="shoulder1_right" axis="2 1 1" class="shoulder"/>
        <joint name="shoulder2_right" axis="0 -1 1" class="shoulder"/>
        <geom name="upper_arm_right" fromto="0 0 0 .16 -.16 -.16" class="arm_upper"/>
        <body name="lower_arm_right" pos=".18 -.18 -.18">
          <joint name="elbow_right" axis="0 -1 1" class="elbow"/>
          <geom name="lower_arm_right" fromto=".01 .01 .01 .17 .17 .17" class="arm_lower"/>
          <body name="hand_right" pos=".18 .18 .18">
            <geom name="hand_right" zaxis="1 1 1" class="hand"/>
          </body>
        </body>
      </body>
      <body name="upper_arm_left" pos="0 .17 .06">
        <joint name="shoulder1_left" axis="-2 1 -1" class="shoulder"/>
        <joint name="shoulder2_left" axis="0 -1 -1" class="shoulder"/>
        <geom name="upper_arm_left" fromto="0 0 0 .16 .16 -.16" class="arm_upper"/>
        <body name="lower_arm_left" pos=".18 .18 -.18">
          <joint name="elbow_left" axis="0 -1 -1" class="elbow"/>
          <geom name="lower_arm_left" fromto=".01 -.01 .01 .17 -.17 .17" class="arm_lower"/>
          <body name="hand_left" pos=".18 -.18 .18">
            <geom name="hand_left" zaxis="1 -1 1" class="hand"/>
          </body>
        </body>
      </body>
    </body>
__PILLOWS__
  </worldbody>

  <contact>
    <exclude body1="waist_lower" body2="thigh_right"/>
    <exclude body1="waist_lower" body2="thigh_left"/>
  </contact>

  <tendon>
    <fixed name="hamstring_right" limited="true" range="-0.3 2">
      <joint joint="hip_y_right" coef=".5"/>
      <joint joint="knee_right" coef="-.5"/>
    </fixed>
    <fixed name="hamstring_left" limited="true" range="-0.3 2">
      <joint joint="hip_y_left" coef=".5"/>
      <joint joint="knee_left" coef="-.5"/>
    </fixed>
  </tendon>

  <actuator>
__ACTUATORS__
  </actuator>
</mujoco>
"""

N_PILLOWS = 6


def build_xml(pillows: bool = False) -> str:
    """The humanoid as MJCF. Pillow Fight adds six pillows, parked far away."""
    actuators = "\n".join(
        f'    <position name="{name}" joint="{name}" kp="{kp}" kv="{kd}" '
        f'forcerange="-{limit} {limit}" forcelimited="true" ctrllimited="false"/>'
        for name, kp, kd, limit in ACTUATORS
    )
    parked = "\n".join(
        f'    <body name="pillow{i}" pos="{30 + 2 * i} 30 .08" childclass="pillow">'
        f'<freejoint name="pillow{i}"/><geom name="pillow{i}"/></body>'
        for i in range(N_PILLOWS)
    )
    return _HUMANOID_XML.replace("__ACTUATORS__", actuators).replace("__PILLOWS__", parked if pillows else "")


def _unit(v: np.ndarray) -> np.ndarray:
    return v / (np.linalg.norm(v, axis=-1, keepdims=True) + 1e-12)


def _smooth(u: np.ndarray) -> np.ndarray:
    """Minimum-jerk blend from 0 to 1."""
    return u * u * u * (10 + u * (-15 + 6 * u))


class Game:
    """Hooks a game implements. One instance lives for the life of an Env."""

    def __init__(self, env: "Env"):
        self.env = env

    def reset(self, rng: np.random.Generator) -> None: ...

    def before_physics(self) -> None: ...

    def after_physics(self) -> None: ...

    def after_control(self) -> None: ...

    def observe(self, obs: dict) -> None: ...

    def score(self) -> float:
        raise NotImplementedError

    def details(self) -> dict:
        return {}


class Copycat(Game):
    """Copy a ghost's pose, live.

    cost = 70 * pose / POSE_REF + 15 * jerk / JERK_REF + 15 * power / POWER_REF

      pose   mean angle, in degrees, between each of the robot's ten limbs and the
             ghost's, measured in the world frame. After a fall every remaining
             frame scores 90.
      jerk   RMS joint jerk, rad/s^3, sampled at 50 Hz.
      power  mean joint power, W (see the energy model at the top of the file).

    The three references are what the starter policy scores on the public seeds,
    so the starter costs 100.
    """

    EPISODE_S = 20.0
    POSE_REF = 6.77  # degrees
    JERK_REF = 78.9  # rad/s^3
    POWER_REF = 30.4  # W
    FALL_POSE_DEG = 90.0
    SHOVE_NS = (2.0, 5.0)  # one shove per episode, impulse in N·s
    SHOVE_S = 0.1
    SPINE_LOW = (-0.6, -0.30, -0.25)  # twist, bow, lean: the ghost's torso range, rad
    SPINE_HIGH = (0.6, 0.15, 0.25)
    SQUAT = (0.15, 0.45)  # how far the ghost bends its ankles in a squat, rad
    PEAK_SPEED = (2.0, 5.0)  # the fastest joint in a move, rad/s

    def __init__(self, env):
        super().__init__(env)
        self.steps = int(round(self.EPISODE_S / CONTROL_DT))
        self.ghost = mujoco.MjData(env.model)

    def reset(self, rng):
        env = self.env
        self.clip = self._make_clip(rng)
        self.k = 0
        self.pose_sum = 0.0
        self.jerk_sum = 0.0
        self.energy0 = env.joint_energy
        self.vel_history = [env.data.qvel[6 : 6 + NU].copy()] * 2
        when = rng.uniform(5.0, 15.0)
        angle = rng.uniform(0, 2 * np.pi)
        impulse = rng.uniform(*self.SHOVE_NS)
        self.shove_window = (when, when + self.SHOVE_S)
        self.shove_force = impulse / self.SHOVE_S * np.array([np.cos(angle), np.sin(angle), 0.0])
        self.ghost_segments = self._ghost_segments(self.clip[0])

    def _ghost_segments(self, joints: np.ndarray) -> np.ndarray:
        """Limb directions of the ghost: same body, pelvis upright, facing +x."""
        env, g = self.env, self.ghost
        g.qpos[:] = env.model.qpos0
        g.qpos[7 : 7 + NU] = joints
        mujoco.mj_kinematics(env.model, g)
        w, x, y, z = g.xquat[env.pelvis]
        g.qpos[3:7] = (w, -x, -y, -z)  # rotate the whole ghost so its pelvis is level
        mujoco.mj_kinematics(env.model, g)
        return env.segments(g)

    def _self_collides(self, joints: np.ndarray) -> bool:
        env, g = self.env, self.ghost
        self._ghost_segments(joints)
        mujoco.mj_fwdPosition(env.model, g)  # kinematics, then collision detection
        pairs = g.contact.geom[: g.ncon]
        return bool(len(pairs)) and bool(np.any(np.all(pairs != env.floor, axis=1)))

    def _make_clip(self, rng) -> np.ndarray:
        """A random gesture sequence: poses joined by smooth moves and short holds.

        Arms go anywhere in their range, the torso bows, twists and leans, and the
        legs squat. The ghost has no weight, so some of what it does is hard or
        impossible to copy exactly while staying upright. Deciding how much to
        follow is the game.
        """
        lo, hi = self.env.joint_low, self.env.joint_high
        amplitude = rng.uniform(0.55, 1.0)
        tempo = rng.uniform(0.8, 1.3)
        arm = {s: [_joint(f"{j}_{s}") for j in ("shoulder1", "shoulder2", "elbow")] for s in ("right", "left")}
        legs = [(_joint(f"hip_y_{s}"), _joint(f"knee_{s}"), _joint(f"ankle_y_{s}")) for s in ("right", "left")]
        spine = [_joint("abdomen_z"), _joint("abdomen_y"), _joint("abdomen_x")]

        def next_pose(prev):
            for _ in range(20):
                pose = prev.copy()
                mirrored = rng.random() < 0.3
                for side in ("right", "left"):
                    if rng.random() < 0.75:
                        target = rng.uniform(lo[arm[side]] + 0.05, hi[arm[side]] - 0.05)
                        pose[arm[side]] = STAND_POSE[arm[side]] + amplitude * (target - STAND_POSE[arm[side]])
                if mirrored:
                    pose[arm["left"]] = pose[arm["right"]]
                if rng.random() < 0.5:
                    pose[spine] = amplitude * rng.uniform(self.SPINE_LOW, self.SPINE_HIGH)
                elif rng.random() < 0.5:
                    pose[spine] = 0.0
                depth = amplitude * rng.uniform(*self.SQUAT) if rng.random() < 0.3 else 0.0
                for hip, knee, ankle in legs:  # a squat that keeps the feet flat
                    pose[hip], pose[knee], pose[ankle] = -depth, -2 * depth, STAND_POSE[ankle] - depth
                if not self._self_collides(pose):
                    return pose
            return prev

        times, poses = [0.0, 1.0], [STAND_POSE.copy(), STAND_POSE.copy()]
        while times[-1] < self.EPISODE_S + 1.0:
            pose = next_pose(poses[-1])
            reach = float(np.abs(pose - poses[-1]).max())
            speed = tempo * rng.uniform(*self.PEAK_SPEED)
            times.append(times[-1] + max(0.35, 1.875 * reach / speed))  # 1.875: peak speed of the blend
            poses.append(pose)
            if rng.random() < 0.4:  # hold the pose for a beat
                poses.append(poses[-1])
                times.append(times[-1] + rng.uniform(0.2, 0.7))
        times, poses = np.array(times), np.array(poses)
        t = np.arange(self.steps + 1) * CONTROL_DT
        i = np.clip(np.searchsorted(times, t, side="right") - 1, 0, len(times) - 2)
        u = _smooth(np.clip((t - times[i]) / (times[i + 1] - times[i]), 0.0, 1.0))[:, None]
        return poses[i] * (1 - u) + poses[i + 1] * u

    def before_physics(self):
        env = self.env
        start, end = self.shove_window
        env.data.xfrc_applied[env.torso, :3] = self.shove_force if start <= env.time < end else 0.0

    def after_control(self):
        env = self.env
        self.k += 1
        self.ghost_segments = self._ghost_segments(self.clip[self.k])
        if env.fell:
            self.pose_sum += self.FALL_POSE_DEG * (self.steps - self.k + 1)
            env.done = True
            return
        cosine = np.sum(env.segments(env.data) * self.ghost_segments, axis=1)
        self.pose_sum += float(np.degrees(np.arccos(np.clip(cosine, -1.0, 1.0))).mean())
        vel = env.data.qvel[6 : 6 + NU].copy()
        jerk = (vel - 2 * self.vel_history[-1] + self.vel_history[-2]) / CONTROL_DT**2
        self.jerk_sum += float(np.sqrt(np.mean(jerk * jerk)))
        self.vel_history = [self.vel_history[-1], vel]
        if self.k >= self.steps:
            env.done = True

    def observe(self, obs):
        obs["ghost_joint_pos"] = self.clip[self.k].copy()
        obs["ghost_segments"] = self.ghost_segments.copy()

    def details(self):
        seconds = self.steps * CONTROL_DT
        return {
            "pose_deg": self.pose_sum / self.steps,
            "jerk": self.jerk_sum / self.steps,
            "power_w": (self.env.joint_energy - self.energy0) / seconds,
            "fell": self.env.fell,
        }

    def score(self):
        d = self.details()
        return 70 * d["pose_deg"] / self.POSE_REF + 15 * d["jerk"] / self.JERK_REF + 15 * d["power_w"] / self.POWER_REF


class PillowFight(Game):
    """Stay on your feet while the pillows get heavier.

    score = pillows that hit the robot before it falls

    A pillow that lands less than a second before the fall does not count, and
    neither does one that misses. Every pillow that lands makes the next one 2%
    heavier, and there is no last pillow.
    """

    START_MASS = 0.5  # kg
    GROWTH = 1.02  # per pillow that lands
    SPEED = 5.0  # m/s, horizontal
    THROW_FROM = 1.5  # m from the robot
    GAP_S = (1.2, 2.2)  # seconds between throws
    RING_M = 1.5  # leaving this circle ends the fight
    GRACE_S = 1.0  # a pillow counts once the robot has stood this long after it
    MAX_S = 600.0
    AIM = (("head", 0.15), ("torso", 0.35), ("pelvis", 0.30), ("thigh_right", 0.10), ("thigh_left", 0.10))
    PARKED, FLYING, LANDED = 0, 1, 2

    def __init__(self, env):
        super().__init__(env)
        m = env.model
        self.body = [m.body(f"pillow{i}").id for i in range(N_PILLOWS)]
        self.geom = np.array([m.geom(f"pillow{i}").id for i in range(N_PILLOWS)])
        self.qadr = [int(m.jnt_qposadr[m.body_jntadr[b]]) for b in self.body]
        self.vadr = [int(m.jnt_dofadr[m.body_jntadr[b]]) for b in self.body]
        self.unit_inertia = m.body_inertia[self.body[0]] / m.body_mass[self.body[0]]
        self.is_pillow_geom = np.zeros(m.ngeom, dtype=bool)
        self.is_pillow_geom[self.geom] = True
        self.pillow_of_geom = np.full(m.ngeom, -1)
        self.pillow_of_geom[self.geom] = np.arange(N_PILLOWS)
        self.aim_body = [m.body(name).id for name, _ in self.AIM]
        self.aim_weight = np.array([w for _, w in self.AIM])

    def reset(self, rng):
        self.rng = rng
        self.state = [self.PARKED] * N_PILLOWS
        self.since = [0.0] * N_PILLOWS  # time of launch, then time of landing
        self.mass = [self.START_MASS] * N_PILLOWS
        self.landed_at: list[float] = []
        self.next_throw = 1.0
        self.thrown = 0
        self.origin = self.env.data.qpos[:2].copy()
        for i in range(N_PILLOWS):
            self._park(i)

    def _park(self, i):
        d = self.env.data
        d.qpos[self.qadr[i] : self.qadr[i] + 7] = (30 + 2 * i, 30, 0.08, 1, 0, 0, 0)
        d.qvel[self.vadr[i] : self.vadr[i] + 6] = 0.0
        self.state[i] = self.PARKED

    def _throw(self):
        env, rng = self.env, self.rng
        free = [i for i in range(N_PILLOWS) if self.state[i] == self.PARKED]
        if not free:
            return
        i = free[0]
        m, d = env.model, env.data
        mass = self.START_MASS * self.GROWTH ** len(self.landed_at)
        m.body_mass[self.body[i]] = mass
        m.body_inertia[self.body[i]] = self.unit_inertia * mass
        mujoco.mj_setConst(m, env.scratch)  # refresh the constants that depend on mass

        target = d.xpos[rng.choice(self.aim_body, p=self.aim_weight)] + rng.normal(0, 0.04, 3)
        bearing = rng.uniform(0, 2 * np.pi)
        start = np.array([
            d.qpos[0] + self.THROW_FROM * np.cos(bearing),
            d.qpos[1] + self.THROW_FROM * np.sin(bearing),
            rng.uniform(0.6, 1.5),
        ])
        flat = target[:2] - start[:2]
        flight = np.linalg.norm(flat) / self.SPEED
        velocity = np.array([*(flat / flight), (target[2] - start[2]) / flight + 0.5 * 9.81 * flight])
        spin = rng.normal(0, 1.0, 4)
        d.qpos[self.qadr[i] : self.qadr[i] + 7] = (*start, *(spin / np.linalg.norm(spin)))
        d.qvel[self.vadr[i] : self.vadr[i] + 6] = (*velocity, *rng.normal(0, 2.0, 3))
        self.state[i], self.since[i], self.mass[i] = self.FLYING, env.time, mass
        self.thrown += 1

    def before_physics(self):
        if self.env.time >= self.next_throw:
            self._throw()
            self.next_throw = self.env.time + self.rng.uniform(*self.GAP_S)

    def after_physics(self):
        env = self.env
        pairs = env.data.contact.geom[: env.data.ncon]
        if len(pairs):
            a, b = pairs[:, 0], pairs[:, 1]
            touching = np.concatenate([
                self.pillow_of_geom[a[self.is_pillow_geom[a] & env.is_robot_geom[b]]],
                self.pillow_of_geom[b[self.is_pillow_geom[b] & env.is_robot_geom[a]]],
            ])
            for i in set(touching.tolist()):
                if self.state[i] == self.FLYING:
                    self.state[i], self.since[i] = self.LANDED, env.time
                    self.landed_at.append(env.time)
        for i in range(N_PILLOWS):
            if (self.state[i] == self.FLYING and env.time - self.since[i] > 2.0) or (
                self.state[i] == self.LANDED and env.time - self.since[i] > 0.8
            ):
                self._park(i)

    def after_control(self):
        env = self.env
        if np.linalg.norm(env.data.qpos[:2] - self.origin) > self.RING_M:
            env.fall("left the ring")
        if env.fell or env.time >= self.MAX_S:
            env.done = True

    def observe(self, obs):
        d = self.env.data
        pillows = np.zeros((N_PILLOWS, 7))
        flying = np.zeros(N_PILLOWS, dtype=bool)
        for i in range(N_PILLOWS):
            if self.state[i] == self.FLYING:
                pillows[i, :3] = d.qpos[self.qadr[i] : self.qadr[i] + 3]
                pillows[i, 3:6] = d.qvel[self.vadr[i] : self.vadr[i] + 3]
                pillows[i, 6] = self.mass[i]
                flying[i] = True
        obs["pillows"], obs["pillow_flying"] = pillows, flying

    def score(self):
        env = self.env
        if not env.fell:
            return float(len(self.landed_at))
        return float(sum(1 for t in self.landed_at if t <= env.time - self.GRACE_S))

    def details(self):
        landed = len(self.landed_at)
        heaviest = self.START_MASS * self.GROWTH ** max(landed - 1, 0)
        return {"thrown": self.thrown, "landed": landed, "heaviest_kg": heaviest, "seconds": self.env.time, "ended": self.env.fall_reason or "time"}


class OneCookie(Game):
    """Walk as far as you can on one cookie.

    score = meters traveled along +x when the energy runs out

    The cookie is 50 kcal = 209,200 J. It pays for the joints (see the energy
    model at the top of the file) and for 40 W of thinking, so standing still is
    not free. Distance is measured at the trailing foot, so a dive at the end
    earns nothing. A fall ends the walk where it happened.
    """

    COOKIE_J = 50 * 4184.0
    MAX_SPEED = 12.0  # m/s. Faster than this is a simulator glitch, not a gait.

    def __init__(self, env):
        super().__init__(env)
        self.feet = [env.model.body(f"foot_{s}").id for s in ("right", "left")]

    def _x(self):
        return float(min(self.env.data.xpos[b][0] for b in self.feet))

    def reset(self, rng):
        self.x0 = self._x()
        self.energy0 = self.env.joint_energy
        self.valid = True

    def _energy(self):
        return self.env.joint_energy - self.energy0 + IDLE_W * self.env.time

    def after_control(self):
        env = self.env
        if np.linalg.norm(env.data.qvel[:3]) > self.MAX_SPEED:
            self.valid = False
            env.fall("moved faster than 12 m/s")
        if env.fell or self._energy() >= self.COOKIE_J:
            env.done = True

    def observe(self, obs):
        obs["energy_left"] = max(self.COOKIE_J - self._energy(), 0.0)
        obs["distance"] = self._x() - self.x0

    def score(self):
        return max(self._x() - self.x0, 0.0) if self.valid else 0.0

    def details(self):
        return {
            "seconds": self.env.time,
            "mean_power_w": self._energy() / max(self.env.time, CONTROL_DT),
            "ended": self.env.fall_reason or "cookie finished",
        }


_GAME_CLASSES = {"copycat": Copycat, "pillow-fight": PillowFight, "one-cookie": OneCookie}


class Env:
    """One humanoid, one game. reset(), then step() until done, then score()."""

    def __init__(self, game: str):
        if game not in GAMES:
            raise ValueError(f"unknown game {game!r}; choose one of {', '.join(GAMES)}")
        self.name = game
        self.model = mujoco.MjModel.from_xml_string(build_xml(pillows=game == "pillow-fight"))
        self.data = mujoco.MjData(self.model)
        self.scratch = mujoco.MjData(self.model)
        m = self.model
        self.floor = m.geom("floor").id
        self.torso, self.pelvis, self.head = (m.body(n).id for n in ("torso", "pelvis", "head"))
        robot_bodies = np.zeros(m.nbody, dtype=bool)
        robot_bodies[self.torso : m.body("hand_left").id + 1] = True
        self.robot_bodies = np.flatnonzero(robot_bodies)
        self.is_robot_geom = robot_bodies[m.geom_bodyid]
        foot = np.zeros(m.ngeom, dtype=bool)
        self.foot_geoms = {s: [m.geom(f"foot{i}_{s}").id for i in (1, 2)] for s in ("right", "left")}
        for ids in self.foot_geoms.values():
            foot[ids] = True
        self.is_fall_geom = self.is_robot_geom & ~foot  # these must never touch the floor
        self.foot_bodies = np.array([m.body(f"foot_{s}").id for s in ("right", "left")])
        self.is_foot_geom = {s: np.isin(np.arange(m.ngeom), ids) for s, ids in self.foot_geoms.items()}
        self.joint_low = m.jnt_range[1 : 1 + NU, 0].copy()
        self.joint_high = m.jnt_range[1 : 1 + NU, 1].copy()
        self._segment_from = np.array([m.body(a).id for _, a, _ in SEGMENTS])
        self._segment_to = np.array([m.body(b).id for _, _, b in SEGMENTS])
        self._nominal = {
            "mass": m.body_mass.copy(),
            "inertia": m.body_inertia.copy(),
            "forcerange": m.actuator_forcerange.copy(),
            "friction": m.geom_friction.copy(),
        }
        self.spec = {
            "game": game,
            "control_hz": round(1 / CONTROL_DT),
            "joint_names": JOINT_NAMES,
            "joint_low": self.joint_low.copy(),
            "joint_high": self.joint_high.copy(),
            "stand_pose": STAND_POSE.copy(),
            "torque_limit": TORQUE_LIMIT.copy(),
            "segment_names": tuple(s[0] for s in SEGMENTS),
        }
        self.game: Game = _GAME_CLASSES[game](self)
        self.done = True
        self.fell = False
        self.fall_reason = ""
        self.time = 0.0
        self.joint_energy = 0.0

    def segments(self, data) -> np.ndarray:
        """(10, 3) unit vectors along each limb of SEGMENTS, world frame."""
        return _unit(data.xpos[self._segment_to] - data.xpos[self._segment_from])

    def fall(self, reason: str) -> None:
        if not self.fell:
            self.fell, self.fall_reason = True, reason

    def reset(self, seed: int = 0) -> dict:
        """Start an episode. The same seed always gives the same episode."""
        rng = np.random.default_rng(seed)
        m, d = self.model, self.data
        # No two robots are quite alike: mass, strength and floor grip vary a little.
        m.body_mass[:] = self._nominal["mass"]
        m.body_inertia[:] = self._nominal["inertia"]
        scale = rng.uniform(0.92, 1.08)
        m.body_mass[self.robot_bodies] *= scale
        m.body_inertia[self.robot_bodies] *= scale
        m.actuator_forcerange[:] = self._nominal["forcerange"] * rng.uniform(0.9, 1.1)
        m.geom_friction[:] = self._nominal["friction"]
        m.geom_friction[self.floor, 0] *= rng.uniform(0.7, 1.1)
        mujoco.mj_setConst(m, self.scratch)

        mujoco.mj_resetData(m, d)
        d.qpos[2] = STAND_Z
        d.qpos[7 : 7 + NU] = STAND_POSE
        for _ in range(int(round(SETTLE_S / PHYSICS_DT))):  # let it find its feet
            d.ctrl[:] = STAND_POSE
            mujoco.mj_step(m, d)
        mujoco.mj_forward(m, d)
        self.done, self.fell, self.fall_reason = False, False, ""
        self.time, self.joint_energy = 0.0, 0.0
        self.game.reset(rng)
        self._contacts()
        return self._observe()

    def step(self, action) -> tuple[dict, bool, dict]:
        """Advance 20 ms. action: 21 target joint angles in radians."""
        if self.done:
            raise RuntimeError("the episode is over; call reset()")
        target = np.asarray(action, dtype=float).reshape(-1)
        if target.shape != (NU,) or not np.all(np.isfinite(target)):
            raise ValueError(f"an action is {NU} finite joint angles; got {np.asarray(action).shape}")
        target = np.clip(target, self.joint_low, self.joint_high)
        m, d = self.model, self.data
        for _ in range(SUBSTEPS):
            d.ctrl[:] = target
            self.game.before_physics()
            mujoco.mj_step(m, d)
            self.time += PHYSICS_DT
            torque, speed = d.actuator_force[:NU], d.qvel[6 : 6 + NU]
            watts = np.maximum(torque * speed, 0.0).sum() + HEAT_W_PER_NM * (torque * torque / TORQUE_LIMIT).sum()
            self.joint_energy += float(watts) * PHYSICS_DT
            self.game.after_physics()
        self._contacts()
        self.game.after_control()
        return self._observe(), self.done, {"fell": self.fell, "reason": self.fall_reason}

    def _contacts(self) -> None:
        d = self.data
        pairs = d.contact.geom[: d.ncon]
        a, b = (pairs[:, 0], pairs[:, 1]) if len(pairs) else (np.zeros(0, int), np.zeros(0, int))
        on_floor = np.concatenate([b[a == self.floor], a[b == self.floor]])
        # Normal force under each foot, and the center of pressure of both.
        force, moment, wrench = np.zeros(2), np.zeros(2), np.zeros(6)
        for i in np.flatnonzero((a == self.floor) | (b == self.floor)):
            other = b[i] if a[i] == self.floor else a[i]
            for side, name in enumerate(("right", "left")):
                if self.is_foot_geom[name][other]:
                    mujoco.mj_contactForce(self.model, d, int(i), wrench)
                    force[side] += wrench[0]  # the first component is the normal force
                    moment += wrench[0] * d.contact.pos[i][:2]
        self._foot_force = force
        self._foot_pos = d.xpos[self.foot_bodies].copy()
        self._cop = moment / force.sum() if force.sum() > 1.0 else self._foot_pos[:, :2].mean(axis=0)
        if not np.all(np.isfinite(d.qpos)) or not np.all(np.isfinite(d.qvel)):
            self.fall("the simulation became unstable")
        elif np.any(self.is_fall_geom[on_floor]):
            self.fall("touched the floor")
        elif d.xpos[self.head][2] < HEAD_MIN_Z:
            self.fall("head below one meter")

    def _observe(self) -> dict:
        d = self.data
        obs = {
            "time": self.time,
            "joint_pos": d.qpos[7 : 7 + NU].copy(),
            "joint_vel": d.qvel[6 : 6 + NU].copy(),
            "root_pos": d.qpos[0:3].copy(),
            "root_quat": d.qpos[3:7].copy(),
            "root_lin_vel": d.qvel[0:3].copy(),
            "root_ang_vel": d.qvel[3:6].copy(),
            "foot_pos": self._foot_pos.copy(),
            "foot_force": self._foot_force.copy(),
            "cop": self._cop.copy(),
        }
        self.game.observe(obs)
        return obs

    def score(self) -> float:
        return float(self.game.score())

    def details(self) -> dict:
        return self.game.details()


# ----------------------------------------------------------------------------
# Starter policies
# ----------------------------------------------------------------------------


class StandStill:
    """Holds the standing pose. Pillow Fight's reference."""

    def __init__(self, spec):
        self.pose = spec["stand_pose"]

    def act(self, obs):
        return self.pose


class CopyTheGhost:
    """Sends the ghost's joint angles straight to the motors. Copycat's reference.

    It is always a little late, because the motors need time to get there and it
    has no idea what the ghost will do next. It also has no sense of balance, so
    a big enough gesture tips it over.
    """

    def __init__(self, spec):
        pass

    def act(self, obs):
        return obs["ghost_joint_pos"]


class Shuffle:
    """Repeats one small leg wiggle, blind. One Cookie's reference.

    The wiggle came out of a short random search. It never looks where it is
    going, so some walks curl back on themselves, and it wastes most of its
    energy. Both are yours to fix.
    """

    PERIOD = 0.4664  # s
    # Right leg: joint -> (amplitude, phase), rad. The left leg runs half a period behind.
    WIGGLE = {
        "hip_x": (-0.1197, -0.7568),
        "hip_z": (0.1872, -1.4514),
        "hip_y": (-0.0366, 1.2130),
        "knee": (-0.1472, -0.2557),
        "ankle_y": (-0.0348, -2.0213),
        "ankle_x": (0.0202, 0.8756),
    }
    BEND = {"hip_y": -0.0033, "knee": -0.0939, "ankle_y": -0.0648}  # a slight crouch, rad
    SWAY = (0.0474, -0.8928)  # the spine leans side to side: amplitude, phase

    def __init__(self, spec):
        self.stand = spec["stand_pose"]
        self.index = {name: i for i, name in enumerate(spec["joint_names"])}
        self.dt = 1.0 / spec["control_hz"]
        self.reset()

    def reset(self):
        self.t = 0.0

    def act(self, obs):
        target = self.stand.copy()
        angle = 2 * np.pi * self.t / self.PERIOD
        for side, behind in (("right", 0.0), ("left", np.pi)):
            for joint, (amplitude, phase) in self.WIGGLE.items():
                target[self.index[f"{joint}_{side}"]] += amplitude * np.sin(angle + behind + phase)
            for joint, bend in self.BEND.items():
                target[self.index[f"{joint}_{side}"]] += bend
        target[self.index["abdomen_x"]] += self.SWAY[0] * np.sin(angle + self.SWAY[1])
        ease = min(1.0, self.t)  # start gently over the first second
        self.t += self.dt
        return self.stand + ease * (target - self.stand)


STARTERS = {"copycat": CopyTheGhost, "pillow-fight": StandStill, "one-cookie": Shuffle}


# ----------------------------------------------------------------------------
# Running and scoring
# ----------------------------------------------------------------------------


DEFAULT_EPISODES = {"copycat": 200, "pillow-fight": 50, "one-cookie": 10}
UNITS = {"copycat": "cost, lower is better", "pillow-fight": "pillows, higher is better", "one-cookie": "meters, higher is better"}


def episode_seed(seed: int, game: str, episode: int) -> int:
    """Episodes of one run are independent, and each game gets its own stream."""
    return int(np.random.SeedSequence([seed, GAMES.index(game), episode]).generate_state(1)[0])


def load_policy(path: str | None, spec: dict):
    if path in (None, "starter"):
        return STARTERS[spec["game"]](spec), "starter"
    file = Path(path)
    module_spec = importlib.util.spec_from_file_location("entry_policy", file) if file.is_file() else None
    if module_spec is None or module_spec.loader is None:
        raise SystemExit(f"cannot load a policy from {path}")
    module = importlib.util.module_from_spec(module_spec)
    sys.path.insert(0, str(file.resolve().parent))
    module_spec.loader.exec_module(module)
    if not hasattr(module, "Policy"):
        raise SystemExit(f"{path} must define a class named Policy")
    return module.Policy(spec), hashlib.sha256(file.read_bytes()).hexdigest()[:12]


def evaluate(game: str, policy_path: str | None = None, episodes: int | None = None, seed: int = 0, verbose: bool = True, video: str | None = None) -> dict:
    """Run `episodes` episodes of `game` and return the scores."""
    episodes = episodes or DEFAULT_EPISODES[game]
    env = Env(game)
    policy, policy_id = load_policy(policy_path, env.spec)
    recorder = _Recorder(env, video) if video else None
    scores, act_ms = [], []
    for episode in range(episodes):
        obs = env.reset(episode_seed(seed, game, episode))
        if hasattr(policy, "reset"):
            policy.reset()
        while not env.done:
            started = time.perf_counter()
            action = policy.act(obs)
            act_ms.append((time.perf_counter() - started) * 1e3)
            obs, _, _ = env.step(action)
            if recorder and episode == 0:
                recorder.capture()
        scores.append(env.score())
        if verbose:
            extra = "  ".join(f"{k}={v:.3g}" if isinstance(v, float) else f"{k}={v}" for k, v in env.details().items())
            print(f"  episode {episode:3d}  score {scores[-1]:9.3f}  {extra}")
    if recorder:
        recorder.save()
    scores = np.array(scores)
    return {
        "game": game,
        "score": float(scores.mean()),
        "stderr": float(scores.std(ddof=1) / np.sqrt(len(scores))) if len(scores) > 1 else 0.0,
        "scores": scores.tolist(),
        "episodes": episodes,
        "seed": seed,
        "policy": policy_id,
        "act_ms_mean": float(np.mean(act_ms)),
        "act_ms_max": float(np.max(act_ms)),
        "kit": KIT_VERSION,
        "mujoco": mujoco.__version__,
    }


class _Recorder:
    """Writes the first episode to a video. Needs `pip install imageio imageio-ffmpeg`."""

    FPS = 25
    SIZE = (720, 1280)  # height, width
    GHOST_OFFSET = 0.9  # m. The ghost is drawn this far to the robot's left.

    def __init__(self, env: Env, path: str):
        try:
            import imageio.v2 as imageio
        except ImportError as error:
            raise SystemExit("--video needs: pip install imageio imageio-ffmpeg") from error
        self.env, self.path, self.imageio = env, path, imageio
        self.renderer = mujoco.Renderer(env.model, height=self.SIZE[0], width=self.SIZE[1])
        self.option = mujoco.MjvOption()
        self.camera = mujoco.MjvCamera()
        self.camera.azimuth, self.camera.elevation, self.camera.distance = 135.0, -10.0, 3.7
        self.frames: list[np.ndarray] = []
        self.every = round(1 / (self.FPS * CONTROL_DT))
        self.count = 0

    def capture(self):
        self.count += 1
        if self.count % self.every:
            return
        env = self.env
        copycat = isinstance(env.game, Copycat)
        self.camera.lookat[:] = (env.data.qpos[0], env.data.qpos[1] + (self.GHOST_OFFSET / 2 if copycat else 0.0), 0.85)
        self.renderer.update_scene(env.data, camera=self.camera, scene_option=self.option)
        if copycat:  # draw the ghost beside the robot, in yellow
            ghost, scene = env.game.ghost, self.renderer.scene
            ghost.qpos[:2] = env.data.qpos[:2] + (0.0, self.GHOST_OFFSET)
            mujoco.mj_kinematics(env.model, ghost)
            first = scene.ngeom
            mujoco.mjv_addGeoms(env.model, ghost, self.option, mujoco.MjvPerturb(), mujoco.mjtCatBit.mjCAT_DYNAMIC, scene)
            for geom in scene.geoms[first : scene.ngeom]:
                geom.rgba[:] = (1.0, 0.733, 0.0, 1.0)
        self.frames.append(self.renderer.render())

    def save(self):
        self.imageio.mimsave(self.path, self.frames, fps=self.FPS)
        print(f"wrote {self.path} ({len(self.frames)} frames)")


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description="Rhem open challenges: Copycat, Pillow Fight, One Cookie.")
    parser.add_argument("game", choices=GAMES)
    parser.add_argument("--policy", default="starter", help="path to your policy file (default: the starter policy)")
    parser.add_argument("--episodes", type=int, default=None, help="episodes to run (default: 200 copycat, 50 pillow-fight, 10 one-cookie)")
    parser.add_argument("--seed", type=int, default=0, help="seed of the run (default: 0, the public set)")
    parser.add_argument("--video", default=None, help="write the first episode to this .mp4")
    parser.add_argument("--json", action="store_true", help="print the result as JSON")
    parser.add_argument("--quiet", action="store_true", help="only print the result")
    args = parser.parse_args(argv)

    episodes = args.episodes or DEFAULT_EPISODES[args.game]
    if not args.quiet and not args.json:
        print(f"{args.game}: {episodes} episodes, seed {args.seed}")
    result = evaluate(args.game, args.policy, episodes, args.seed, verbose=not (args.quiet or args.json), video=args.video)
    if args.json:
        print(json.dumps(result))
        return 0
    print(f"\n{args.game}  {result['score']:.2f} ± {result['stderr']:.2f}  ({UNITS[args.game]})")
    print(f"policy step: {result['act_ms_mean']:.3f} ms mean, {result['act_ms_max']:.2f} ms max (budget {STEP_BUDGET_MS:.0f} ms mean)")
    if result["act_ms_mean"] > STEP_BUDGET_MS:
        print("warning: over the step budget; this entry would not be scored")
    if mujoco.__version__ != OFFICIAL_MUJOCO:
        print(f"note: official scores use mujoco {OFFICIAL_MUJOCO}; you have {mujoco.__version__}, so numbers can differ slightly")
    print(
        f"RESULT game={args.game} score={result['score']:.3f} episodes={episodes} seed={args.seed} "
        f"policy={result['policy']} kit={KIT_VERSION} mujoco={mujoco.__version__}"
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
