# Game structure

> How a Minekube game is built - rules that run without a server, a server half that talks to Paper, Commands, events in the same tick, and what happens on a reload or a failure.

A game is a project folder; its name is the game's id on the server. Inside, the game has two halves, the same split Effect UI uses for `Html.component(logic)`:

| File | Holds | Imports Java | Runs in |
| --- | --- | --- | --- |
| `src/<Name>.ts` | The rules: `Component.define(...).logic(...)` and the Command declarations | No | Bun (Stories, replays) and the server |
| `src/game.ts` | The server half: Paper events to messages, Command implementations, `export default Game.make(...)` | Yes | The server |
| `src/<Name>.test.ts` | Stories and replays | No | Bun |
| `recordings/*.ndjson` | Real sessions from the server | | Replayed by the tests |

A project made with `mk init` also has `AGENTS.md`, the `minekube-games` skill in `.agents/skills/` and `.mcp.json` for your coding agent, and `types/paper`, the Paper types your dev server wrote from its own jars, which `mk dev .` copies in. Don't edit them.

The example on this page is a launcher: right-click a sign next to spawn and you fly up, with a particle trail. Each player's launches are counted.

## The rules

The rules are an Effect UI component: a Model, the messages that change it, and `update`, which says what each message does. Anything that touches the world is a Command, declared here and implemented in the server half.

```ts title="src/Launcher.ts"

// The rules, with no server in sight: this module imports no Java, so Stories and replays run in Bun.
// Players are what Paper identifies them by, `Player.getUniqueId()`, in its generated data form.
const PlayerId = Schemas["java.util.UUID"];

export const LauncherMessage = UiSchema.TaggedEnum({
  Joined: { player: PlayerId, name: Schema.String },
  ClickedSign: { player: PlayerId, name: Schema.String },
});

/** Places the launch sign next to spawn. */
export class PlaceSign extends Command.Service<PlaceSign>()("launcher/PlaceSign", {}) {}

/** Tells a player how to launch. */
export class Greet extends Command.Service<Greet>()("launcher/Greet", { args: { player: PlayerId } }) {}

/** Throws a player into the air, for their `count`th launch. */
export class Launch extends Command.Service<Launch>()("launcher/Launch", {
  args: { player: PlayerId, count: Schema.Int },
}) {}

export const Launcher = Component.define({
  name: "Launcher",
  model: Schema.Struct({ launches: Schema.Record(PlayerId, Schema.Int) }),
  message: LauncherMessage,
}).logic({
  init: ($) => $.set({ launches: {} }).run(PlaceSign.make()),
  update: {
    Joined: ($, { player }) => $.run(Greet.make({ player })),
    ClickedSign: ($, { player }) => {
      const count = ($.model.launches[player] ?? 0) + 1;
      return $.evolve({ launches: { ...$.model.launches, [player]: count } }).run(Launch.make({ player, count }));
    },
  },
});
```

- **Name messages after what happened in the game** (`ClickedSign`), not after the Paper event.
- **Messages, the Model and Command args are data with Schemas.** They are recorded, replayed and shown in the devtools. Never put a Java object in them; convert at the edge with `fromJava` and `toJava`. For Java values such as UUIDs and enums, use the [generated Schemas](https://minekube.com/games/write/paper-api#data-for-messages-generated-schemas).
- **A Command without `success` is silent**: its body returns nothing to `update`. To get a result back in `update`, declare `success: SomeMessage` and return that message from the body.
- **`update` reads only its arguments.** The clock, random numbers and globals belong in a Command or in the message, or a replay can no longer reproduce the session.

## The server half

`Minecraft.component(logic)` puts the rules on the server. Its subscriptions turn Paper events into messages, and each Command becomes a layer that calls Paper through the `Paper` service.

```ts title="src/game.ts"

// The server half: Paper events become Launcher messages, and the Launcher's Commands call Paper.
// Classes are typed from the server jar. No wrapper and no adapter code in between.
const Action = Java.type("org.bukkit.event.block.Action");
const Color = Java.type("org.bukkit.Color");
const Component = Java.type("net.kyori.adventure.text.Component");
const DustOptions = Java.type("org.bukkit.Particle$DustOptions");
const EquipmentSlot = Java.type("org.bukkit.inventory.EquipmentSlot");
const Material = Java.type("org.bukkit.Material");
const NamedTextColor = Java.type("net.kyori.adventure.text.format.NamedTextColor");
const Particle = Java.type("org.bukkit.Particle");
const Side = Java.type("org.bukkit.block.sign.Side");
const Sign = Java.type("org.bukkit.block.Sign");
const Sound = Java.type("org.bukkit.Sound");
const Tag = Java.type("org.bukkit.Tag");

// Change these and save: the running server picks up the new revision within a tick or two.
const LAUNCH_SPEED = 1.6;
const TRAIL = new DustOptions(Color.fromRGB(0x35efd0), 1.4);

const who = (player: org.bukkit.entity.Player) => ({ player: fromJava("java.util.UUID", player.getUniqueId()), name: player.getName() });

const LauncherGame = Minecraft.component(Launcher).make({
  subscriptions: () => [
    Game.event("org.bukkit.event.player.PlayerJoinEvent", (event) => LauncherMessage.Joined(who(event.getPlayer()))),
    Game.event("org.bukkit.event.player.PlayerInteractEvent", (event) => {
      const block = event.getClickedBlock();
      if (event.getAction() !== Action.RIGHT_CLICK_BLOCK || event.getHand() !== EquipmentSlot.HAND) return undefined;
      if (block === null || !Tag.ALL_SIGNS.isTagged(block.getType())) return undefined;
      return LauncherMessage.ClickedSign(who(event.getPlayer()));
    }, { cancel: true }),
  ],
  view: () => View.text(""),
});

const Commands = Layer.mergeAll(
  PlaceSign.toLayer(Effect.gen(function* () {
    const { server } = yield* Paper;
    return () =>
      Effect.sync(() => {
        const world = server.getWorlds().get(0);
        const spawn = world.getSpawnLocation();
        const block = world.getBlockAt(spawn.getBlockX() + 2, spawn.getBlockY(), spawn.getBlockZ());
        if (!Tag.ALL_SIGNS.isTagged(block.getType())) block.setType(Material.OAK_SIGN);
        const state = block.getState();
        if (!(state instanceof Sign)) return;
        const front = state.getSide(Side.FRONT);
        front.line(1, Component.text("LAUNCH", NamedTextColor.AQUA));
        front.line(2, Component.text("right-click", NamedTextColor.GRAY));
        state.update();
      });
  })),
  Greet.toLayer(Effect.gen(function* () {
    const { server } = yield* Paper;
    return ({ player }) =>
      Effect.sync(() => {
        server.getPlayer(toJava("java.util.UUID", player))?.sendMessage(Component.text("Right-click the sign to launch.", NamedTextColor.AQUA));
      });
  })),
  Launch.toLayer(Effect.gen(function* () {
    const { server } = yield* Paper;
    return ({ player: id, count }) => {
      const player = server.getPlayer(toJava("java.util.UUID", id));
      if (player === null) return Effect.void;
      player.setVelocity(player.getVelocity().setY(LAUNCH_SPEED));
      player.playSound(player.getLocation(), Sound.ENTITY_FIREWORK_ROCKET_LAUNCH, 1, 1.2);
      player.sendActionBar(Component.text(`Launch #${count}`, NamedTextColor.AQUA));
      return Effect.sync(() => {
        if (player.isOnline()) player.getWorld().spawnParticle(Particle.DUST, player.getLocation(), 12, 0.25, 0.1, 0.25, 0, TRAIL);
      }).pipe(Effect.repeat({ schedule: Schedule.spaced("50 millis"), times: 20 }));
    };
  })),
);

export default Game.make(Game.mount(LauncherGame, {}).pipe(Effect.provide(Commands)));
```

`Launch` changes the player right away, in the same tick, and returns an Effect that keeps spawning particles for a second. [Paper from TypeScript](https://minekube.com/games/write/paper-api) explains `Java.type`, `null` and the other rules at the Java boundary.

## Events

`Game.event(eventClass, toMessage, options)` is a `Subscription.direct`:

- `toMessage` runs synchronously inside Paper's dispatch, on the server thread. Return a message, or `undefined` to ignore the event. Declared in `subscriptions`, it closes over the latest Model.
- The message's `update` runs right away, and its Commands run until their first wait, all before Paper continues. So a Command can still change the event's outcome in the same tick.
- `cancel: true` cancels the event whenever it becomes a message. The other options are `priority` (`"LOWEST"` to `"MONITOR"`), `ignoreCancelled`, and `key` to subscribe to one event class twice.
- The event class is its binary Java name, checked against `JavaEvents`, so a typo does not compile.

`Game.on(eventClass, handler)` is the low-level form for programs that are not components; its handler is an Effect, run synchronously. Prefer components: only they are recorded and replayable.

## Lifetime

- `Game.make(program)` runs the program once per revision, until the revision stops. `Game.mount` keeps a component mounted until then.
- On a reload, the old revision's component unmounts, its Subscriptions, Commands and Layers close, its recording ends, and only then does the new revision start, with a fresh Model from `init`.
- World changes (blocks, entities) persist across revisions, so make `init` idempotent. The launcher places its sign only if it is not there yet.
- A Command that runs over time, like the particle trail with `Effect.repeat`, is interrupted when the revision stops.
- Things you create in the world, such as entities, boss bars or teams, are not closed for you. Pair them with their removal in `Effect.acquireRelease`, so a reload does not leave them behind.

## Failures

- **A bug fails the component.** A defect in `update`, a Command or a Subscription, such as a Java exception, fails it. `Game.mount` then starts the game over from `init`, as on a reload, and reports it in chat. A game that fails more than 3 times in a minute stays off until its next revision. In recordings and the devtools, its instance path is `/Minekube/<Name>[<restart>]`.
- **Every child component is a failure boundary.** When a child fails, it shows its `fallback` and the parent hears of it through `onFailure`, while the rest of the game keeps running. Give per-player or per-arena state its own child, so one player's bug does not restart everyone's round. Restart a failed child by changing its key.
- **Expected failures are not bugs.** A checked Java exception through [`Jvm.attempt`](https://minekube.com/games/write/paper-api#exceptions-and-resources-jvm) is a typed failure. Handle it inside the Command with `Effect.catch`. When the rules must react, declare a Schema `error` on the Command, map the Java exception to it, and turn it into a message with `match`.
