Skip to content
Get started

Game structure

View as Markdown

A game is a project folder with a vite.config.ts that names its bundle; the bundle’s 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 Paper.make(...) Yes The server
src/<Name>.test.ts Stories and replays No Bun
recordings/*.ndjson Real sessions from the server Replayed by the tests
vite.config.ts The bundles the project builds, and where mk deploy sends them Vite (Vite plugin and configuration)

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 of the version vite.config.ts names, which mk types generates. 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 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.

src/Launcher.ts
import { Schemas } from "@minekube/paper-types/schemas";
import { Schema } from "effect";
import { Command, Component, UiSchema } from "effect/ui";
// 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.
  • 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.

Paper.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 PaperServer service.

src/game.ts
import { fromJava, Paper, PaperServer, toJava } from "@minekube/paper";
import { Effect, Layer, Schedule } from "effect";
import { View } from "effect/ui";
import { Greet, Launch, Launcher, LauncherMessage, PlaceSign } from "./Launcher.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 = 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 }) => {
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 Paper.make(Paper.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 explains Java.type, null and the other rules at the Java boundary.

Paper.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.

Paper.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.

  • Paper.make(program) runs the program once per revision, until the revision stops. Paper.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.
  • A bug fails the component. A defect in update, a Command or a Subscription, such as a Java exception, fails it. Paper.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 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.

Was this helpful?