Recipes

Common tasks from start to finish, one short example per mechanic. Each links to the full explanation.

A new NPC who talks

  1. The character: src/content/characters/mira/index.ts
    import { defineCharacter } from '@/core/define'
    import sprite from './sprites/mira.gen'          // characters/mira/sprites/mira.aseprite (idle/walk tags)
    
    export default defineCharacter({ name: 'Mira', color: '#ce93d8', blip: 'sfx/blip', sprite })
    No portraits yet? Leave them out: scenes show a coloured placeholder. (Characters, sprites)
  2. The scene: src/content/events/mira/hello/index.vn
    show mira
    mira: Oh, a visitor!
    choice:
      * Who are you?
        mira: Just a traveller.
      * Bye.
    set met_mira = true
    Add met_mira: false to flags.ts. (.vn scripts)
  3. On the map: in Tiled, add a 16×16 object named mira on the object layer. In the map's index.ts:
    objects: {
      mira: { character: 'mira', facing: 'down', onInteract: ({ game }) => game.events.start('mira/hello') },
    }
  4. Translate: pnpm lang --write, fill in the Polish lines. (Translations)

A new map with a door

  1. Make src/content/maps/countryside/cave/ with cave.tmx (tileset: ../../../tilesets/countryside.tsj).
  2. In Tiled add a spawn object named entrance, and a door object with map = countryside/town, spawn = from_cave.
  3. index.ts:
    import { defineMap } from '@/core/define'
    import cave from './cave.gen'
    
    export default defineMap({ title: 'Cave', tiled: cave, music: null, lighting: { tint: '#000000', strength: 0.7 } })
  4. In town.tmx add a spawn from_cave and a door to countryside/cave / entrance.
  5. pnpm test: the maps test checks both doors lead somewhere real. (Doors)
Dark map? Give the player a light: the lantern already does that (items/lantern). Add light to torches. (Lights)

A shop

  1. src/content/shops/blacksmith/index.ts:
    export default defineShop({
      name: 'Blacksmith',
      items: { wooden_sword: {}, leather_vest: { stock: 2 } },
      buys: true,
    })
  2. Open it from an NPC or scene: game.shops.open('blacksmith') (in .vn: shop blacksmith).
  3. Item prices come from each item's price. (Money & shops)

A quest

  1. src/content/quests/lost_cat/index.ts:
    export default defineQuest({
      title: 'The lost cat',
      description: 'Mira lost her cat somewhere in the forest.',
      steps: { search: 'Look for the cat in the forest', return: 'Bring the cat back to Mira' },
      onComplete: ({ game }) => game.money.add(20, { notify: true }),
    })
  2. Start it in Mira's scene: quest start lost_cat.
  3. A trigger in the forest (Tiled object named cat, behaviour in the forest map):
    cat: {
      onInteract: async ({ game }) => {
        if (game.quests.step('lost_cat') !== 'search') return
        await game.events.start('forest/found_cat')
        game.quests.setStep('lost_cat', 'return')
      },
    },
  4. Back in Mira's scene:
    if game.quests.step('lost_cat') === 'return':
      mira:happy: You found her!
      quest done lost_cat
    (Quests)

A quest step that stays "???"

steps: {
  search: 'Look for the cat in the forest',          // plain: shown once the quest gets there
  secret: {                                          // listed from the start, masked until `when` is true
    text: 'Ask the hermit about the collar',
    when: ({ game }) => game.flags.get('found_collar'),
    // hiddenText: 'Something is missing…',          // instead of "???"
  },
},

Keep steps written out in the quest file: the step ids are read from it. (Quests)

A choice the game remembers, and a friendship

mira: Will you help me look?
choice:
  * Of course.
    set helping_mira = true
    love mira +5
    mira:happy: Thank you!
  * Not now.
    mira: Oh. All right.
  * You can count on me, as always. if love('mira') >= 20
    mira:happy: I knew it.

A cutscene that plays once when you walk in

// in a map's objects (Tiled: a rectangle named "bridge_scene")
bridge_scene: {
  onEnter: async ({ game, world }) => {
    if (game.flags.get('saw_bridge')) return
    game.flags.set('saw_bridge', true)
    await world.camera.panTo({ x: 20, y: 6 })
    await game.events.start('forest/bridge')
    await world.camera.reset()
  },
},

The world is frozen while the handler runs, so the player can't walk away mid-scene. (Cutscenes)

An enemy and a battle area

  1. src/content/enemies/mushroom/index.ts:
    export default defineEnemy({
      name: 'Angry mushroom', color: '#e57373',
      stats: { hp: 22, attack: 6, defense: 3, speed: 2 },   // speed = how often it acts
      xp: 9, money: 5, drops: [{ item: 'bread', chance: 0.2 }],
    })
  2. In Tiled: a rectangle with class encounter, property enemies = mushroom;mushroom,slime, rate = 0.1.
  3. Or one standing on the map: an object with class enemy, property enemy = mushroom. Gone after a win.
  4. Or a fixed fight from a scene: battle mushroom, mushroom, and check the result in TS: if ((await game.battles.start({ enemies: ['mushroom'] })) === 'win') …. (Battles)

A skill

// src/content/skills/frost_bite/index.ts
export default defineSkill({
  name: 'Frost bite', description: 'A cold hit that may slow.',
  mp: 4,
  target: 'enemy',                 // enemy | all_enemies | ally | all_allies | self | fallen_ally
  element: 'ice',
  delay: 1.2,                      // the user's next turn comes a little later (1 = normal)
  effects: [
    { type: 'damage', power: 1.3, uses: 'magic', against: 'resistance' },
    { type: 'status', status: 'slow', chance: 0.5 },          // chained: only if the hit landed
    { type: 'delay', amount: 0.3, evenOnMiss: true },         // separate: happens either way
  ],
})

A status, and a weak spot

// src/content/statuses.ts — add an entry
bleed: { name: 'Bleed', description: 'Loses HP every turn.', icon: '✚', color: '#e53935',
         bad: true, turns: 3, tick: { hp: -0.06 } },
rage:  { name: 'Rage', icon: '▲', turns: 2, stats: { attack: 1.5, defense: 0.7 } },   // a buff with a price

// an enemy (or a character's `battle`, or an item's `equip`)
elements: { fire: 2, ice: 0.5, poison: 0 },   // weak to fire ("Weak!"), resists ice, immune to poison
immune: ['sleep'],                            // statuses that never stick

Elements are listed in stats.ts. restrict: 'skip' makes a status cost the turn (sleep, stun). All statuses end with the fight. (Statuses and elements)

A boss fight (a troop) and a smarter enemy

// src/content/troops/mushroom_king/index.ts
export default defineTroop({
  enemies: ['mushroom_king', 'mushroom', 'mushroom'],
  background: 'forest', music: 'music/forest', canFlee: false,
  rewards: { xp: 80, money: 50, drops: [{ item: 'lantern', chance: 1 }] },
})

// src/content/enemies/mushroom_king/index.ts
actions: [
  { skill: 'attack', weight: 3 },
  { skill: 'venom' },
  { skill: 'heal', weight: 5, when: ({ self }) => self.hp < 20 },   // only when hurt
],

Start it with battle mushroom_king in a .vn file, game.battles.start('mushroom_king'), or a map enemy's fight: { troop: 'mushroom_king' }. (Enemies and troops)

A party member who learns skills

  1. Give the character numbers:
    // characters/mira/index.ts
    battle: {
      base: { hp: 22, mp: 12, attack: 4, defense: 3, magic: 6, resistance: 4, speed: 7, luck: 5 },
      growth: { hp: 4, mp: 2, attack: 1, magic: 1.2, speed: 1 },                  // per level
      skills: ['heal', { skill: 'frost_bite', level: 3 }, { skill: 'fire', quest: 'lost_cat' }],
    },
  2. She joins in a scene: join mira (TS: game.party.add('mira', { notify: true })). XP: xp 20.
  3. Teach a skill from the story: game.party.learn('mira', 'quicken', { notify: true }).
  4. A weapon with its own move: equip: { slot: 'weapon', stats: { attack: 3 }, skills: ['slash'] }. Off again when unequipped.

(Party, Who has which skill)

Equipment that does something in battle

// items/cursed_ring/index.ts
equip: {
  slot: 'accessory', stats: { magic: 2 }, elements: { fire: 0.5 }, immune: ['sleep'],
  battle: {
    onStart: [{ type: 'status', status: 'strong' }],                                   // when the fight begins
    onTurn: [{ type: 'heal', amount: 6 }, { type: 'status', status: 'poison', turns: 1 }],   // every turn of the wearer
  },
}

The effects are the same as a skill's and always land on the wearer. (Skills and effects)

An item that does something while you carry it

// items/lantern/index.ts
export default defineItem({
  name: 'Lantern', icon, price: 20, max: 1,
  light: { radius: 3.5, color: '#ffe0a0' },                 // glows around the player while switched on
  onObtain: ({ game, id }) => game.items.setOn(id, true),   // found, bought, given
  onLose: ({ game, id }) => game.items.setOn(id, false),    // sold, used up, taken
  keepOnUse: true,
  useLabel: ({ game, id }) => (game.items.isOn(id) ? game.t('Put out') : game.t('Light')),
  use: ({ game, id }) => { game.items.toggle(id) },         // the inventory button
})

onObtain / onLose can do anything: set a flag, move a quest on, change a stat. Use the game they are given; item files must not import it. (Items that do something while carried)

An NPC with a daily routine

// in a map's objects
mira: {
  character: 'mira',
  schedule: [
    { from: '8', at: { x: 14, y: 9 }, facing: 'down' },        // walks there when the time comes
    { from: '18', at: { x: 20, y: 5 } },
    { from: '22', at: { x: 31, y: 10 }, hidden: true },        // goes home
  ],
},

// anywhere with the world: a line over her head, no scene needed
void world.npc('mira').bark('Lovely evening.')

Time only runs while the player is free on a map. (Schedules, Speech bubbles, Time of day)

A dark, rainy place with its own sound

// the map
defineMap({ title: 'Cave', tiled: cave, music: null, ambient: 'ambient/wind',
            lighting: { tint: '#000000', strength: 0.7 } })

// a torch (any object or prop)
torch: { light: { radius: 4, color: '#ffa04a', flicker: 0.35 } },

// from a script
game.maps.weather('rain', { intensity: 0.5 })     // 'snow' | null

A corner with different sound: in Tiled draw a rectangle with class zone and the properties music and / or ambient (empty = silence). Lights only show when it is dark. (Lights, Weather, Sound zones)

A chest that stays open

  1. The chest is already a prop (props/chest). In Tiled: an object with class chest and the property item = lantern.
  2. Your own prop remembers things per place with memory:
    onInteract: async ({ game, prop, memory }) => {
      if (memory.get('open')) return game.toast(game.t('The chest is empty.'))
      memory.set('open', true)                 // saved
      await prop.play('opening', { hold: true })
      game.items.add('apple', 1, { notify: true })
    },

(Props)

An achievement, a journal entry and a gallery picture

// achievements/cat_finder/index.ts
export default defineAchievement({ title: 'Cat finder', description: 'Bring the cat home.' })

// codex/mira/index.ts — the text can change with the story
export default defineCodex({
  title: 'Mira', category: 'People', text: 'A traveller looking for her cat.',
  versions: [{ when: (game) => game.quests.isDone('lost_cat'), text: 'A friend. Her cat likes you too.' }],
})

// gallery/reunion/index.ts
export default defineGallery({ title: 'Reunion', image })
cg reunion
mira:happy: There you are!
cg none
achievement cat_finder
codex mira

Showing a cg unlocks it in Extras. To make the whole scene replayable there, give the event replay: 'The reunion'. (Achievements & journal, Extras)

A window with its own key

  1. src/content/windows/map_view/index.tsx with defineWindow({ title: 'Map', component: MapView }). (Windows)
  2. In input.ts: map_view: { keys: ['KeyL'], buttons: [GP.RT] } (pick a key and a button no other action uses), and its name in windows/settings/Controls.tsx.
  3. In Hud.tsx: useAction('map_view', () => game.windows.toggle('map_view'), { layers: ['map', 'windows'] }). (Input)
  4. Touch and pad players without a spare button: add a button for it to the pause menu (windows/menu), or a touchButtons entry in input.ts.

A minigame that changes the story

// in an event
const result = await game.minigames.start('rock_paper_scissors')
if (result === 'win') {
  game.achievements.unlock('first_win')
  await say('anna:surprised', 'You won?!')
} else {
  await say('anna:happy', 'Ha! Just like old times.')
}

Minigame results are recorded in mid-scene saves, so loading replays the same outcome. (Minigames)

Saving something new

  1. Add the field in save/data.ts: visitedCaves: [] as string[].
  2. Once the game is out (players have saves), add save/migrations/vN.ts, one higher than the last (the first is v2.ts), and an example old save in save.test.ts:
    export default defineMigration(({ engine, data }) => ({ engine, data: { ...data, visitedCaves: [] } }))
  3. Use it: game.state.update((d) => { d.visitedCaves.push('cave') }). (Migrations)

Just a yes/no or a counter? A flag needs no migration.

A new language

See Adding a language: one folder, pnpm lang --write, fill in.