# Build your first game

> Build the launcher game step by step - rules that run in Bun, a Story that tests them, a server half that calls Paper, live changes while you play, and a recorded session that becomes a test.

In this tutorial you build a small game: a sign next to spawn throws every player who right-clicks it into the air, and counts their launches. It is the [launcher example](https://minekube.com/games/examples/launcher) from the Minekube repository. On the way you write each part of a Minekube game yourself.

You will:

1. Write the rules as an Effect UI component that imports no Java.
2. Test the rules with a Story in Bun.
3. Write the server half, which turns Paper events into messages and carries out Commands with Paper calls.
4. Change the game while you play.
5. Turn a session you played into a test.

**Before you start:** do the [quick start](https://minekube.com/games/quick-start). You need the Minekube CLI, Bun 1.4.4 or newer and Minecraft: Java Edition 26.3, and the dev server must run (`mk server --accept-eula`).

## 1. Create the project

Create a project named `launcher`. `mk init` names the game's bundle after the folder, in `vite.config.ts`: `launcher` is the game's id on the server.

```sh
mk init launcher
cd launcher
```

Start `mk dev .` in a second terminal and keep it running:

```sh
mk dev .
```

It brings the Paper types in `types/paper`, which the rules and the tests import, up to the version `vite.config.ts` names. Then it installs the game on every save.

The project starts with a small game in `src/Round.ts` and `src/game.ts`. You replace it, so delete the rules and their test:

```sh
rm src/Round.ts src/Round.test.ts
```

Until you finish step 4, `mk dev` prints `launcher: build failed`, because `src/game.ts` still imports the rules you deleted. That is expected.

## 2. Write the rules

The rules decide what happens. They do not know about Paper: they receive messages and return a new Model and the Commands to run. Because they import no Java, they run on the server, in Bun and in the devtools alike.

Create `src/Launcher.ts`:

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

// 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 }));
    },
  },
});
```

- **Messages** say what happened: a player joined, a player clicked the sign. They carry data with Schemas, so they can be recorded and replayed.
- **Commands** say what should happen. Each one is declared here and implemented on the server in step 4.
- **The Model** is the game's state: launches per player. `init` creates it and places the sign. Each `update` handler returns the next Model and the Commands to run.

## 3. Test the rules

Create `src/Launcher.test.ts` with a Story. It sends messages to the component and checks every Command it issues:

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

const PlayerId = Schemas["java.util.UUID"];
const alex = { player: PlayerId.make("36532b5e-c442-3dbb-a24c-c7e55d0f979a"), name: "Alex" };
const sam = { player: PlayerId.make("77bfcc1c-1831-3a3c-84d6-63015aaf34af"), name: "Sam" };

/** A Story past `init`, whose sign placement is done. */
const started = () => Story.start(Launcher, {}).expectExact(PlaceSign.make()).resolve(PlaceSign, Component.noop);

describe("Launcher rules", () => {
  test("counts launches per player", () => {
    const story = started()
      .send(LauncherMessage.ClickedSign(alex))
      .expectExact(Launch.make({ player: alex.player, count: 1 }))
      .resolve(Launch, Component.noop)
      .send(LauncherMessage.ClickedSign(sam))
      .expectExact(Launch.make({ player: sam.player, count: 1 }))
      .resolve(Launch, Component.noop)
      .send(LauncherMessage.ClickedSign(alex))
      .expectExact(Launch.make({ player: alex.player, count: 2 }))
      .resolve(Launch, Component.noop);
    expect(story.model.launches).toEqual({ [alex.player]: 2, [sam.player]: 1 });
  });
});
```

Run it:

```sh
bun test
```

The test needs no server. It proves the rules before any player ever clicks the sign. [Test rules with Stories](https://minekube.com/games/testing/rules) shows `Story.explore`, which tries every order of a set of messages.

## 4. Write the server half

The server half connects the rules to Paper. It turns Paper events into messages and implements each Command with Paper calls. Replace `src/game.ts`:

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

const Action = Java.type("org.bukkit.event.block.Action");
const Component = Java.type("net.kyori.adventure.text.Component");
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 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 this and save: the running server picks up the new revision within a tick or two.
const LAUNCH_SPEED = 1.6;

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

const LauncherGame = Paper.component(Launcher).make({
  subscriptions: () => [
    Paper.event("org.bukkit.event.player.PlayerJoinEvent", (event) => LauncherMessage.Joined(who(event.getPlayer()))),
    Paper.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* PaperServer;
    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* PaperServer;
    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* PaperServer;
    return ({ player: id, count }) =>
      Effect.sync(() => {
        const player = server.getPlayer(toJava("java.util.UUID", id));
        if (player === null) return;
        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));
      });
  })),
);

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

- `Java.type` gives you Paper's own classes, typed from the dev server's jars. There is no wrapper.
- `Paper.event` turns a Paper event into a message, in the same tick. `{ cancel: true }` cancels the event when it becomes a message, so the click does not open the sign editor.
- `fromJava` and `toJava` convert a Java `UUID` to the data form that the rules use, and back.
- `Paper.make` turns the mounted component into the bundle that the server runs.

Save. The `mk dev` terminal builds the bundle, and the server log says `Installed launcher` with the revision.

Run the strict check:

```sh
bun run check
```

## 5. Play and change it while you play

Join `localhost:25569` in Minecraft. You see the greeting in chat and a sign next to spawn. Right-click the sign: you fly up, and the action bar says `Launch #1`.

Stay on the server. In `src/game.ts`, change `LAUNCH_SPEED` to `3` and save. The server swaps the game within a tick or two, and your next launch goes much higher. You did not reconnect.

The launch counts start again after the swap, because a new revision starts with a fresh Model from `init`. The world keeps its blocks. [Live swap](https://minekube.com/games/local-development/live-swap) explains what survives a swap and why.

## 6. Turn your session into a test

The server recorded everything you just did. Open the devtools at [http://127.0.0.1:4774](http://127.0.0.1:4774) to see each click as a message, the `Launch` Command it issued and the Model after it.

Copy the recording into the project:

```sh
mkdir -p recordings
cp ~/.minekube/server/plugins/Minekube/recordings/launcher/*.ndjson recordings/
```

Add the replay test to `src/Launcher.test.ts`: the three imports at the top, and the test at the end.

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

const root = `${import.meta.dir}/..`;
describe("recorded sessions", () => {
  for (const recording of new Glob("recordings/*.ndjson").scanSync(root)) {
    test(recording, () =>
      Effect.runPromise(Effect.gen(function* () {
        const log = yield* Effect.promise(() => Bun.file(`${root}/${recording}`).text());
        const frames = yield* decodeRecording(log);
        const replay = Story.fromLog(Launcher, frames);
        expect(replay.divergence).toBeUndefined();
      })));
  }
});
```

Run `bun test`. Your session now replays through the rules on every test run. If you change a rule, the replay names the first message that behaves differently.

## Summary

You wrote a Minekube game from its two halves. The rules are a component that runs anywhere, the server half connects it to Paper, and every session you play can become a test.

## Next steps

- [Game structure](https://minekube.com/games/write/game-structure): events, Commands that run over time, lifetime and failures.
- [Test with bot clients](https://minekube.com/games/testing/bots): a real client that finds the sign and launches itself.
- [Build with a coding agent](https://minekube.com/games/get-started/coding-agent): let an agent extend the game.
