On this page
  1. Run it
  2. Keys
  3. The code

After school

An afternoon in town, told in Yarn. The lantern festival is at seven, and whom you talk to -- and what you say -- decides how the evening ends: with Mika at the festival, in the front row of Sora's concert, or at home. The town and everyone in it come from LDtk; each person is a Talker with a node of resources/dialogue/school.yarn; the conversations are a DialogueStage over the town, Persona style, each person with a face per mood and a voice of their own; the script's $variables are bound to the game's Story, so every conversation knows what the others decided; <<walk Mika pond>> makes the dialogue wait while she walks there with Pathfind, around the walls, and the view goes with her; trees and street lamps are entities too, drawn over whoever walks behind them; the light turns to dusk as the clock runs, and at seven the evening comes wherever you are; Kai's race is a timed choice; the flyer is a Collectible the script asks about with has_item(). English and Spanish, saved progress, lanterns over the town at dusk, and resources/ in folders by kind (maps/, sprites/, portraits/, ui/, audio/, fonts/, dialogue/). Kenney's art (CC0) from tools/make_story_assets.py.

After school, as it starts

Run it

From a clone of the framework:

rmp example 09_after_school

Keys

Read from the code below: the actions it defines with rmp::input::action, the ones that come defined that it reads by name, and the keys it asks raylib about directly.

ActionKeys
pauseEsc, P, gamepad middle right
interactE, Space, gamepad right face down

The code

Every file of examples/games/09_after_school, as it is at the commit this site documents (on GitHub).

src/main.cpp 41 lines
// ---------------------------------------------------------------------------
// examples/games/09_after_school -- an afternoon in town, told in Yarn.
//
// The last bell has rung, the lantern festival starts at seven, and whoever
// you talk to -- and what you say -- decides how the evening ends: at the
// festival with Mika, in the front row of Sora's concert, or at home.
//
// What the framework does here, and therefore what is NOT in these files:
//
//   rmp::Tilemap     resources/maps/world.ldtk: the town, its walls, every
//                    person, tree and street lamp in it and the places they
//                    walk to, from the editor.
//   rmp::Dialogue    resources/dialogue/school.yarn: everything anyone says,
//                    its branches and its endings, compiled by the framework.
//                    Its $variables ARE the game's (Dialogue::bind), so
//                    every conversation knows what the others decided.
//   rmp::behavior    the people are Talkers (talk with E or the A button)
//                    and walk where the script sends them with Pathfind,
//                    around the walls; you walk with TopDown; the flyer is a
//                    Collectible.
//   rmp::ui          the conversations are a DialogueStage, Persona style:
//                    big portraits that slide in, the speaker in front, each
//                    with a voice of their own; Kai's race is a timed choice.
//   rmp::lang        English and Spanish (resources/lang.tsv): every line's
//                    #line: id is its key.
//   rmp::save        the afternoon, so Continue picks it up again.
//
// The files: src/story.cpp is the afternoon so far, src/people.cpp who walks
// and who is drawn in front of whom, src/scenery.cpp the town's map and its
// trees, src/look.cpp the theme and the Stage, src/scenes/ the four screens.
// resources/ is in folders by kind.
//
// Move with the arrows or WASD, talk with E (or A), pause with Escape.
// Run it: `rmp example 09_after_school`.
// ---------------------------------------------------------------------------

#include <rmp/app.h>

#include "school.h"

RMP_GAME(game::TitleScene);
include/school.h 128 lines
#pragma once
// ---------------------------------------------------------------------------
// What every file of the afternoon shares: the story so far, the people, the
// scenes and the look.
// ---------------------------------------------------------------------------

#include <rmp/dialogue.h>
#include <rmp/scene.h>
#include <rmp/ui.h>

#include <string>

namespace game {

inline constexpr float TILE = 16; // the grid of maps/tiles.png and of the town

// Three pixels of the screen for each one of the art's, at the [window] size.
// A whole number: at 2.14 some of a tile's pixels were drawn wider than others.
inline constexpr float ZOOM = 3;

inline constexpr int FIRST_HOUR = 15; // the last bell
inline constexpr int FESTIVAL_HOUR = 19; // seven: the lanterns, and the evening's end

// THE STORY SO FAR: what every conversation reads and writes -- the
// $variables of dialogue/school.yarn are these, bound -- and what Continue
// restores.
struct Story {
    int hour = FIRST_HOUR; // of the afternoon
    float minutes = 0;
    std::string with; // "", "mika" or "sora": who you go with
    bool met_mika = false;
    bool met_sora = false;
    bool met_aki = false;
    bool met_kai = false;
    bool raced = false;
    bool flyer = false; // picked up by the east trees
};
Story &story();
void new_story();
bool has_saved_story();
void load_story();
void save_story();
void forget_story();
// How the evening ends, from who you go with: "festival", "concert" or "home".
std::string evening();

// The look of every screen: Kenney's frames and font, a voice for each
// person, sounds on hover and click. Set once, by the title.
void set_look();
// The conversations: one Stage, Persona style, its portraits and voices.
rmp::ui::DialogueStage make_stage();
// The dusk that comes over the town as the afternoon goes: none at three.
Color dusk(const Story &at);
// The town into a scene's map, with a factory for its trees and street lamps
// and nobody else in it: the town scene registers the people before it calls
// map.spawn_objects(), the title and the ending call it as it is.
void load_town(rmp::Scene &scene);

// Anyone who walks, you included: the sheet's tag for where they go, or last
// went, and drawn in front of whatever stands further up the screen.
struct Character {
    Vector2 facing{ 0, 1 }; // south, towards the screen

    void _update(rmp::Object &self, float delta);
};
// Turns `who` to look at `at`.
void face(rmp::Object &who, Vector2 at);

// ---------------------------------------------------------------------------
// The scenes
// ---------------------------------------------------------------------------

class TitleScene : public rmp::Scene {
public:
    void _ready() override;
    void _update(float delta) override;
    void _draw() override;

private:
    float _clock = 0;
};

class TownScene : public rmp::Scene {
public:
    void _ready() override;
    void _update(float delta) override;
    void _draw() override;

    // A conversation began with whoever stands at `speaker`, or ended.
    void talking(rmp::Handle<rmp::Object> speaker);
    void done_talking();
    // An ending the script asked for: shown once its last line has been read.
    void ending(std::string kind);
    // What the story's conversations need from the game.
    void prepare(rmp::Dialogue &talk);

private:
    void build();
    void pass_time(float delta);
    void draw_clock() const;
    void draw_prompts() const;

    rmp::Handle<rmp::Object> _you;
    rmp::Handle<rmp::Object> _speaker; // whose Talker holds the conversation
    rmp::Dialogue _seven; // what the clock says at seven, to nobody's Talker
    rmp::ui::DialogueStage _stage = make_stage();
    std::string _ending;
};

class PauseScene : public rmp::Scene {
public:
    void _update(float delta) override;
    void _draw() override;
};

class EndScene : public rmp::Scene {
public:
    explicit EndScene(std::string kind);
    void _ready() override;
    void _update(float delta) override;
    void _draw() override;

private:
    std::string _kind;
    float _clock = 0;
};

} // namespace game
src/look.cpp 109 lines
// The look: Kenney's beige frames and brown plates, his Kenpixel font, and a
// Stage whose people each have a face for every mood and a voice of their own.

#include "school.h"

#include <rmp/app.h>
#include <rmp/assets.h>
#include <rmp/ui.h>

#include <array>
#include <string>
#include <string_view>

namespace game {

namespace {

constexpr float FRAME = 12; // panel.png's border, in its pixels
constexpr float PLATE = 10; // button.png's and plate.png's
constexpr float PORTRAIT_HEIGHT = 250;

const Color INK = { 62, 39, 35, 255 };
const Color CREAM = { 255, 246, 226, 255 };
const Color DUSK = { 255, 178, 92, 255 };

rmp::ui::Picture frame(std::string_view file, float border) {
    return rmp::ui::NineSlice{ .texture =
                                   rmp::assets::load_texture("ui/" + std::string(file)),
                               .left = border,
                               .top = border,
                               .right = border,
                               .bottom = border,
                               .scale = 2 };
}

// Who is in the script, their voice's pitch, and the colour of their plate.
struct Person {
    std::string_view name;
    std::string_view look;
    float pitch;
    Color plate;
};
constexpr std::array<Person, 4> PEOPLE{ {
    { "Mika", "mika", 1.25f, { 226, 92, 92, 255 } },
    { "Sora", "sora", 0.85f, { 92, 132, 226, 255 } },
    { "Aki", "aki", 1.1f, { 120, 180, 96, 255 } },
    { "Kai", "kai", 0.95f, { 230, 160, 60, 255 } },
} };
constexpr std::array<std::string_view, 3> MOODS{ "happy", "sad", "think" };

} // namespace

void set_look() {
    rmp::ui::set_font(rmp::assets::load_font("fonts/font.ttf", 16));
    rmp::ui::Theme look = rmp::ui::theme_light();
    look.text = INK;
    look.primary = DUSK;
    look.sounds = { .hover = "audio/tap", .click = "audio/click", .volume = 0.5f };
    look.styles.panel = {
        .skin = rmp::ui::Skin{ .normal = frame("panel.png", FRAME) },
        .shadow =
            rmp::ui::Shadow{ .offset = { 0, 6 }, .blur = 12, .color = { 0, 0, 0, 110 } },
        .padding_x = 30,
        .padding_y = 24,
        .gap = 12,
        .motion = rmp::ui::Motion{ .appear = 0.25f, .appear_offset = 18 },
    };
    look.styles.button = {
        .skin = rmp::ui::Skin{ .normal = frame("button.png", PLATE),
                               .press = frame("button_down.png", PLATE) },
        .padding_x = 26,
        .padding_y = 12,
        .text = INK,
        .motion = rmp::ui::Motion{ .hover_scale = 1.04f, .press_scale = 0.96f },
    };
    rmp::ui::set_theme(look);
}

rmp::ui::DialogueStage make_stage() {
    rmp::ui::DialogueStage stage{
        .flow = { .letters_per_second = 50,
                  .blip = "audio/tap",
                  .blip_every = 3,
                  .blip_jitter = 0.06f },
        .portrait_height = PORTRAIT_HEIGHT,
        .name_style = { .skin = rmp::ui::Skin{ .normal = frame("plate.png", PLATE) },
                        .padding_x = 22,
                        .padding_y = 8,
                        .text = CREAM },
    };
    for (const Person &p : PEOPLE) {
        const std::string face = "portraits/" + std::string(p.look) + "_";
        stage.portraits.push_back(
            { .speaker = std::string(p.name),
              .picture = rmp::assets::load_texture(face + "neutral.png") });
        for (const std::string_view mood : MOODS) {
            stage.portraits.push_back({ .speaker = std::string(p.name),
                                        .mood = std::string(mood),
                                        .picture = rmp::assets::load_texture(
                                            face + std::string(mood) + ".png") });
        }
        stage.speakers.push_back({ .name = std::string(p.name),
                                   .pitch = p.pitch,
                                   .name_style = { .tint = p.plate } });
    }
    return stage;
}

} // namespace game
src/people.cpp 39 lines
// Everyone who walks through town: which way they look, and who is drawn in
// front of whom.

#include "school.h"

#include <cmath>
#include <string>
#include <string_view>

namespace game {

namespace {

// The sheet's tags end in the side they face: idle_s, walk_e.
std::string_view side(Vector2 facing) {
    if (std::abs(facing.x) > std::abs(facing.y)) return facing.x > 0 ? "e" : "w";
    return facing.y > 0 ? "s" : "n";
}

} // namespace

void Character::_update(rmp::Object &self, float /*delta*/) {
    const bool walking = self.velocity.x != 0 || self.velocity.y != 0;
    if (walking) facing = self.velocity;
    self.sprite.play(std::string(walking ? "walk_" : "idle_") +
                     std::string(side(facing)));
    // Every tag is drawn for its own side: nothing is mirrored.
    self.flip_x = false;
    // Lower on the screen is nearer: over whoever, and whatever, stands behind.
    self.layer = static_cast<int>(self.position.y);
}

void face(rmp::Object &who, Vector2 at) {
    if (auto character = who.get<Character>()) {
        character->facing = { at.x - who.position.x, at.y - who.position.y };
    }
}

} // namespace game
src/scenery.cpp 53 lines
// The town as every scene shows it: the map, and the trees and street lamps
// standing in it, which are entities so that they can be drawn over whoever
// walks behind them.

#include "school.h"

#include <rmp/assets.h>
#include <rmp/tilemap.h>

#include <array>
#include <string_view>

namespace game {

namespace {

// The two tiles of each in maps/tiles.png, top-left first.
constexpr Rectangle GREEN_TREE{ 16 * TILE, 8 * TILE, TILE, 2 * TILE };
constexpr Rectangle ORANGE_TREE{ 16 * TILE, 11 * TILE, TILE, 2 * TILE };
constexpr Rectangle STREET_LAMP{ 7 * TILE, 6 * TILE, TILE, 2 * TILE };

// Who and what else the map holds: the town scene's, and nobody's elsewhere.
constexpr std::array<std::string_view, 5> CAST{ "Player", "Person", "Home", "Place",
                                                "Flyer" };

// Two tiles standing on the lower one, in front of whoever is further up.
void stand(rmp::Scene &scene, const rmp::MapObject &o, Rectangle tiles) {
    auto &standing = scene.spawn({ .position = o.position });
    standing.sprite.texture = rmp::assets::load_texture("maps/tiles.png");
    standing.sprite.source = tiles;
    standing.sprite.origin = { 0.5f, 0.75f };
    standing.layer = static_cast<int>(o.position.y);
    // The map's cell under it is what stops you; the picture touches nothing.
    standing.collision_layer = 0;
    standing.collision_mask = 0;
}

} // namespace

void load_town(rmp::Scene &scene) {
    scene.map = rmp::assets::load_map("maps/world.ldtk", "Town");
    scene.map.on_object("Tree", [](rmp::Scene &into, const rmp::MapObject &o) {
        stand(into, o, o.property_string("kind") == "green" ? GREEN_TREE : ORANGE_TREE);
    });
    scene.map.on_object("Lamp", [](rmp::Scene &into, const rmp::MapObject &o) {
        stand(into, o, STREET_LAMP);
    });
    for (const std::string_view name : CAST) {
        scene.map.on_object(name, [](rmp::Scene &, const rmp::MapObject &) {});
    }
}

} // namespace game
src/scenes/end.cpp 91 lines
// How the evening ended: the town at dusk, and -- at the festival, at the
// concert -- a sky of lanterns rising over it.

#include "school.h"

#include <rmp/assets.h>
#include <rmp/random.h>
#include <rmp/ui.h>

#include <array>
#include <cmath>
#include <utility>

namespace game {

namespace {

constexpr int LANTERNS = 40;
constexpr float RISE = 16; // world units a second
constexpr float SWAY = 0.7f; // turns of a sine a second
const Color DUSK = { 24, 20, 60, 150 };
const Color FLAME = { 255, 170, 70, 255 };
const Color GLOW = { 255, 120, 40, 60 };

// Where each lantern starts and how it drifts: seeded, so every run (and
// every e2e shot) draws the same sky.
struct Lantern {
    Vector2 from;
    float phase;
    float size;
};
std::array<Lantern, LANTERNS> &lanterns() {
    static std::array<Lantern, LANTERNS> all{};
    return all;
}

} // namespace

EndScene::EndScene(std::string kind) : _kind(std::move(kind)) {}

void EndScene::_ready() {
    load_town(*this);
    map.spawn_objects(*this);
    const Rectangle b = map.bounds();
    camera.zoom = ZOOM;
    camera.position = { b.x + b.width / 2, b.y + b.height / 3 };
    for (Lantern &l : lanterns()) {
        l = { { rmp::random::range(b.x, b.x + b.width),
                rmp::random::range(b.y, b.y + b.height * 1.2f) },
              rmp::random::range(0.0f, 6.28f),
              rmp::random::range(2.0f, 4.0f) };
    }
}

void EndScene::_update(float delta) { _clock += delta; }

void EndScene::_draw() {
    // Dusk over the town; the lanterns are drawn in the world's coordinates.
    DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), DUSK);
    if (_kind != "home") {
        BeginMode2D(camera.raylib());
        for (const Lantern &l : lanterns()) {
            const Vector2 at{ l.from.x + std::sin(_clock * SWAY + l.phase) * 6,
                              l.from.y - _clock * RISE };
            DrawCircleV(at, l.size * 2.5f, GLOW);
            DrawCircleV(at, l.size, FLAME);
        }
        EndMode2D();
    }
    rmp::ui::begin();
    rmp::ui::panel([this] {
        if (_kind == "festival") {
            rmp::ui::text("The Lantern Festival",
                          { .size = rmp::ui::Size::LARGE, .wrap = false });
            rmp::ui::text("You and Mika watch a thousand lanterns rise.",
                          { .wrap = false });
        } else if (_kind == "concert") {
            rmp::ui::text("Front Row", { .size = rmp::ui::Size::LARGE, .wrap = false });
            rmp::ui::text("Sora plays the best set of his life.", { .wrap = false });
        } else {
            rmp::ui::text("A Quiet Evening",
                          { .size = rmp::ui::Size::LARGE, .wrap = false });
            rmp::ui::text("The lanterns rise far away. Maybe next year.",
                          { .wrap = false });
        }
        if (rmp::ui::button("Back to the title")) rmp::Scene::change<TitleScene>();
    });
    rmp::ui::end();
}

} // namespace game
src/scenes/pause.cpp 27 lines
// The pause: the town waits below.

#include "school.h"

#include <rmp/input.h>
#include <rmp/ui.h>

namespace game {

void PauseScene::_update(float /*delta*/) {
    if (rmp::input::just_pressed("pause")) rmp::Scene::pop();
}

void PauseScene::_draw() {
    rmp::ui::overlay([] {
        rmp::ui::panel([] {
            rmp::ui::text("Paused", { .size = rmp::ui::Size::LARGE, .wrap = false });
            if (rmp::ui::button("Back to town")) rmp::Scene::pop();
            if (rmp::ui::button("To the title")) {
                save_story();
                rmp::Scene::change<TitleScene>();
            }
        });
    });
}

} // namespace game
src/scenes/title.cpp 73 lines
// The title: the town behind the menu, the camera drifting over it, and the
// language you read it in.

#include "school.h"

#include <rmp/app.h>
#include <rmp/assets.h>
#include <rmp/text.h>
#include <rmp/ui.h>

#include <cmath>

namespace game {

namespace {
constexpr float DRIFT = 0.1f; // how fast the camera wanders
const Color TITLE = { 255, 214, 140, 255 };
const Color OUTLINE = { 62, 39, 35, 255 };
} // namespace

void TitleScene::_ready() {
    rmp::app::set_stretch(rmp::app::Stretch::EXPAND);
    set_look();
    background = Color{ 60, 200, 168, 255 };
    load_town(*this);
    map.spawn_objects(*this);
    camera.limits = map.bounds();
    camera.zoom = ZOOM;
}

void TitleScene::_update(float delta) {
    _clock += delta;
    const Rectangle b = map.bounds();
    camera.position = { b.x + (b.width / 2) + (std::sin(_clock * DRIFT) * b.width / 4),
                        b.y + (b.height / 2) +
                            (std::cos(_clock * DRIFT) * b.height / 5) };
}

void TitleScene::_draw() {
    rmp::ui::begin();
    rmp::ui::panel([] {
        rmp::ui::Label title{ .text = "After School",
                              .size = 46,
                              .wrap = false,
                              .style = { .text = TITLE,
                                         .text_outline = rmp::ui::TextOutline{
                                             .width = 3, .color = OUTLINE } } };
        title.show();
        rmp::ui::text("The lantern festival starts at seven.",
                      { .color = rmp::ui::ColorRole::MUTED, .wrap = false });
        if (has_saved_story() && rmp::ui::button("Continue")) {
            load_story();
            rmp::Scene::change<TownScene>();
        }
        if (rmp::ui::button("New afternoon")) {
            new_story();
            rmp::Scene::change<TownScene>();
        }
        // The languages lang.tsv has, each in its own words.
        rmp::ui::row([] {
            for (const std::string &code : rmp::lang::available()) {
                if (rmp::ui::button(rmp::Text(rmp::lang::name(code))))
                    rmp::lang::set(code);
            }
        });
#if !defined(PLATFORM_IOS)
        if (rmp::ui::button("Quit")) rmp::app::quit();
#endif
    });
    rmp::ui::end();
}

} // namespace game
src/scenes/town.cpp 300 lines
// The town: the map, you, whoever LDtk put in it, and the conversations.
//
// Everything here is an entity of maps/world.ldtk. A Person is a Talker: their
// `node` of dialogue/school.yarn, their `look` (which sheet walks around, which
// portraits the Stage shows). A Place is where a <<walk who place>> of the
// script goes, and Home is the way out of the afternoon. The trees and the
// street lamps are src/scenery.cpp's, in every scene that shows the town.

#include "school.h"

#include <rmp/app.h>
#include <rmp/assets.h>
#include <rmp/behavior.h>
#include <rmp/dialogue.h>
#include <rmp/input.h>
#include <rmp/tilemap.h>
#include <rmp/ui.h>

#include <cmath>
#include <map>
#include <string>
#include <utility>

namespace game {

namespace {

constexpr float SPEED = 72; // yours, in world units a second
constexpr float STROLL = 44; // theirs, walking where the script sends them
constexpr float ARRIVED = 6; // close enough to a place
constexpr float MINUTES_A_SECOND = 3; // the afternoon's pace
constexpr float MINUTES_AN_HOUR = 60;
constexpr float KAI_SECONDS = 4; // Kai's race: say yes in time
constexpr float CAMERA_DRIFT = 8; // how quickly the view catches up with you
constexpr Vector2 FEET{ 10, 6 }; // what of a person stops at a wall
constexpr Vector2 OVER_HEAD{ 0, -14 }; // where a person's prompt floats
constexpr int ON_THE_GROUND = -1; // drawn under everyone

const Color INK = { 62, 39, 35, 235 };
const Color CREAM = { 255, 246, 226, 255 };

constexpr Rectangle POSTER{ 11 * TILE, 13 * TILE, TILE, TILE }; // in maps/tiles.png

// Where a <<walk>> goes, by the names LDtk gives them, and who is in town.
struct Town {
    std::map<std::string, Vector2, std::less<>> places;
    std::map<std::string, rmp::Handle<rmp::Object>, std::less<>> people;
};
Town &town() { return rmp::global<Town>(); }

bool close_to(Vector2 a, Vector2 b) {
    return std::hypot(a.x - b.x, a.y - b.y) <= ARRIVED;
}

// Someone with a sheet of their own, standing on their feet.
rmp::Object &person(rmp::Scene &scene, Vector2 position, std::string_view look) {
    auto &someone = scene.spawn({ .position = position });
    someone.sprite.sheet =
        rmp::assets::load_sheet("sprites/" + std::string(look) + ".aseprite");
    someone.collider = rmp::rect(FEET);
    someone.solid = true;
    return someone;
}

// Sends `who` to one of the map's places; the dialogue waits until they are there.
void walk(rmp::Dialogue &talk, std::string_view who, std::string_view where) {
    const auto walker = town().people.find(who);
    const auto place = town().places.find(where);
    if (walker == town().people.end() || place == town().places.end()) return;
    const rmp::Handle<rmp::Object> them = walker->second;
    const Vector2 to = place->second;
    if (const auto o = them.get()) {
        if (auto path = o->get<rmp::behavior::Pathfind>()) path->goal = to;
    }
    talk.wait_until([them, to, asked = 0]() mutable {
        const auto o = them.get();
        if (!o || close_to(o->position, to)) return true;
        // With no way there the script goes on, rather than wait for ever.
        const auto path = o->get<rmp::behavior::Pathfind>();
        return ++asked > 2 && (!path || path->arrived());
    });
}

} // namespace

void TownScene::prepare(rmp::Dialogue &talk) {
    Story &s = story();
    talk.bind("$hour", s.hour);
    talk.bind("$with", s.with);
    talk.bind("$met_mika", s.met_mika);
    talk.bind("$met_sora", s.met_sora);
    talk.bind("$met_aki", s.met_aki);
    talk.bind("$met_kai", s.met_kai);
    talk.bind("$raced", s.raced);
    // Whether you carry the item: "flyer" is the only one in town.
    talk.on_function("has_item", [](const std::string &item) -> bool {
        return item == "flyer" && story().flyer;
    });
    // The view goes with whoever the script walks somewhere, until the
    // conversation is over.
    talk.on_command("walk",
                    [this, &talk](const std::string &who, const std::string &where) {
                        walk(talk, who, where);
                        if (const auto walker = town().people.find(who);
                            walker != town().people.end()) {
                            camera.follow = walker->second;
                        }
                    });
    // The evening's end: festival, concert or home.
    talk.on_command("ending", [this](std::string kind) { ending(std::move(kind)); });
}

void TownScene::_ready() {
    background = Color{ 60, 200, 168, 255 };
    rmp::input::action("pause", KEY_ESCAPE, KEY_P, GAMEPAD_BUTTON_MIDDLE_RIGHT);
    rmp::input::action("interact", KEY_E, KEY_SPACE, GAMEPAD_BUTTON_RIGHT_FACE_DOWN);
    build();
}

void TownScene::build() {
    town() = Town{};
    load_town(*this);
    _seven = rmp::assets::load_dialogue("dialogue/school.yarn");
    prepare(_seven);

    auto &you = person(*this, {}, "you");
    you.add<rmp::behavior::TopDown>({ .speed = SPEED, .idle = "", .walk = "" });
    you.add<Character>({ .facing = { 0, -1 } });
    _you = you.handle();

    map.on_object("Player", [this](rmp::Scene &, const rmp::MapObject &o) {
        if (const auto y = _you.get()) y->position = o.position;
    });
    map.on_object("Place", [](rmp::Scene &, const rmp::MapObject &o) {
        town().places[std::string(o.property_string("name"))] = o.position;
    });
    map.on_object("Person", [this](rmp::Scene &scene, const rmp::MapObject &o) {
        auto &them = person(scene, o.position, o.property_string("look", "mika"));
        // Nobody is pushed out of their conversation.
        them.immovable = true;
        them.add<rmp::behavior::Pathfind>({ .speed = STROLL, .clearance = FEET.x / 2 });
        them.add<Character>();
        rmp::behavior::Talker talker = rmp::behavior::Talker::from(o);
        talker.player = _you;
        talker.on_load = [this](rmp::Dialogue &d) { prepare(d); };
        const rmp::Handle<rmp::Object> me = them.handle();
        talker.on_talk = [this, me](rmp::Dialogue &) { talking(me); };
        talker.on_done = [this] { done_talking(); };
        them.add<rmp::behavior::Talker>(std::move(talker));
        town().people[std::string(o.property_string("name", "Mika"))] = me;
    });
    map.on_object("Home", [this](rmp::Scene &scene, const rmp::MapObject &o) {
        auto &home = scene.spawn({ .position = o.position });
        home.visible = false;
        rmp::behavior::Talker talker = rmp::behavior::Talker::from(o);
        talker.player = _you;
        talker.action = ""; // walking onto it is enough
        talker.on_load = [this](rmp::Dialogue &d) { prepare(d); };
        const rmp::Handle<rmp::Object> me = home.handle();
        talker.on_talk = [this, me](rmp::Dialogue &) { talking(me); };
        talker.on_done = [this] { done_talking(); };
        home.add<rmp::behavior::Talker>(std::move(talker));
    });
    map.on_object("Flyer", [](rmp::Scene &scene, const rmp::MapObject &o) {
        if (story().flyer) return;
        auto &flyer = scene.spawn({ .position = o.position, .shape = rmp::circle(6) });
        flyer.sprite.texture = rmp::assets::load_texture("maps/tiles.png");
        flyer.sprite.source = POSTER;
        flyer.layer = ON_THE_GROUND;
        flyer.add<rmp::behavior::Collectible>(
            { .sound = "audio/switch", .on_collect = [](rmp::Object &, rmp::Object &) {
                 story().flyer = true;
                 rmp::ui::notify("You found a festival flyer!");
             } });
    });
    map.spawn_objects(*this);

    camera.follow = _you;
    camera.limits = map.bounds();
    camera.smoothing = CAMERA_DRIFT;
    camera.zoom = ZOOM;
}

void TownScene::talking(rmp::Handle<rmp::Object> speaker) {
    _speaker = speaker;
    _stage.ours = {};
    const auto them = speaker.get();
    const auto talker =
        them ? them->get<rmp::behavior::Talker>() : rmp::Ref<rmp::behavior::Talker>{};
    // Kai's race: a choice with a clock on it.
    _stage.flow.choice_seconds = talker && talker->node == "Kai" ? KAI_SECONDS : 0;
    _stage.flow.default_choice = 1;
    const auto you = _you.get();
    if (!you) return;
    // You stop where you are, and the two of you look at each other.
    you->enable<rmp::behavior::TopDown>(false);
    you->velocity = {};
    if (them) {
        face(*you, them->position);
        face(*them, you->position);
    }
}

void TownScene::done_talking() {
    _speaker = {};
    camera.follow = _you;
    if (const auto you = _you.get()) you->enable<rmp::behavior::TopDown>(true);
    save_story();
    if (_ending.empty()) return;
    forget_story();
    rmp::Scene::change<EndScene>(std::exchange(_ending, {}));
}

void TownScene::ending(std::string kind) { _ending = std::move(kind); }

// The afternoon goes on while you walk, not while you talk; at seven it is over.
void TownScene::pass_time(float delta) {
    Story &s = story();
    if (s.hour >= FESTIVAL_HOUR) {
        s.hour = FESTIVAL_HOUR;
        s.minutes = 0;
        if (_seven.start("Seven")) talking({});
        return;
    }
    s.minutes += delta * MINUTES_A_SECOND;
    while (s.minutes >= MINUTES_AN_HOUR && s.hour < FESTIVAL_HOUR) {
        s.minutes -= MINUTES_AN_HOUR;
        ++s.hour;
    }
}

void TownScene::_update(float delta) {
    const bool at_seven = _seven.running();
    if (_speaker || at_seven) return;
    // Seven's last line was read: the evening it asked for.
    if (!_ending.empty()) {
        done_talking();
        return;
    }
    if (rmp::input::just_pressed("pause")) {
        rmp::Scene::push<PauseScene>();
        return;
    }
    pass_time(delta);
}

void TownScene::draw_clock() const {
    const Story &s = story();
    rmp::ui::begin({ .placement = rmp::ui::Align::TOP_LEFT, .padding = 10 });
    rmp::ui::panel({ .box = { .gap = 2, .padding = 12 } }, [&] {
        rmp::ui::text(
            rmp::Text("{hour}:{minutes} pm",
                      { { "hour", s.hour - 12 },
                        { "minutes", TextFormat("%02d", static_cast<int>(s.minutes)) } }),
            { .wrap = false });
        rmp::ui::text(s.flyer ? rmp::Text("A festival flyer")
                              : rmp::Text("The festival is at seven"),
                      { .color = rmp::ui::ColorRole::MUTED, .wrap = false });
    });
    rmp::ui::end();
}

// "Talk" over whoever is close enough to talk to.
void TownScene::draw_prompts() const {
    for (const auto &[name, handle] : town().people) {
        const auto them = handle.get();
        const auto talker =
            them ? them->get<rmp::behavior::Talker>() : rmp::Ref<rmp::behavior::Talker>{};
        if (!talker || !talker->in_range()) continue;
        rmp::ui::begin();
        rmp::ui::at(them->position, { .offset = OVER_HEAD, .id = name }, [] {
            rmp::ui::Label prompt{ .text = "Talk",
                                   .wrap = false,
                                   .style = { .background = INK,
                                              .radius = 6,
                                              .padding_x = 8,
                                              .padding_y = 3,
                                              .text = CREAM } };
            prompt.show();
        });
        rmp::ui::end();
    }
}

void TownScene::_draw() {
    DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), dusk(story()));
    draw_clock();
    const auto them = _speaker.get();
    auto talker =
        them ? them->get<rmp::behavior::Talker>() : rmp::Ref<rmp::behavior::Talker>{};
    if (!talker && !_seven.running()) {
        draw_prompts();
        return;
    }
    rmp::ui::begin({ .placement = rmp::ui::Align::BOTTOM_CENTER, .grow = true });
    _stage.show(talker ? talker->conversation() : _seven);
    rmp::ui::end();
}

} // namespace game
src/story.cpp 76 lines
// The story so far, kept with rmp::save, and what follows from it: how the
// evening ends, and how late the light says it is.

#include "school.h"

#include <rmp/app.h>
#include <rmp/save.h>

#include <algorithm>
#include <string>

namespace game {

namespace {

constexpr std::string_view SLOT = "after_school";
constexpr float MINUTES_AN_HOUR = 60;
// The light at seven, over everything: the afternoon fades towards it.
constexpr Color NIGHTFALL = { 52, 28, 96, 120 };

} // namespace

Story &story() { return rmp::global<Story>(); }

void new_story() { story() = Story{}; }

bool has_saved_story() { return rmp::save::exists(SLOT); }

void load_story() {
    rmp::Value v;
    rmp::save::read(SLOT, v);
    Story &s = story();
    s.hour = std::clamp(v["hour"].as_int(FIRST_HOUR), FIRST_HOUR, FESTIVAL_HOUR);
    s.minutes = std::clamp(v["minutes"].as_float(0), 0.0f, MINUTES_AN_HOUR - 1);
    s.with = std::string(v["with"].as_string(""));
    s.met_mika = v["met_mika"].as_bool();
    s.met_sora = v["met_sora"].as_bool();
    s.met_aki = v["met_aki"].as_bool();
    s.met_kai = v["met_kai"].as_bool();
    s.raced = v["raced"].as_bool();
    s.flyer = v["flyer"].as_bool();
}

void save_story() {
    const Story &s = story();
    rmp::Value v;
    v["hour"] = s.hour;
    v["minutes"] = s.minutes;
    v["with"] = s.with;
    v["met_mika"] = s.met_mika;
    v["met_sora"] = s.met_sora;
    v["met_aki"] = s.met_aki;
    v["met_kai"] = s.met_kai;
    v["raced"] = s.raced;
    v["flyer"] = s.flyer;
    rmp::save::write(SLOT, v);
}

void forget_story() { rmp::save::remove(SLOT); }

std::string evening() {
    const Story &s = story();
    if (s.with == "mika") return "festival";
    if (s.with == "sora") return "concert";
    return "home";
}

Color dusk(const Story &at) {
    const float hours =
        static_cast<float>(at.hour - FIRST_HOUR) + at.minutes / MINUTES_AN_HOUR;
    const float gone = std::clamp(hours / (FESTIVAL_HOUR - FIRST_HOUR), 0.0f, 1.0f);
    // Slow at first, then quickly: the last hour is the one that darkens.
    return Fade(NIGHTFALL, gone * gone * NIGHTFALL.a / 255.0f);
}

} // namespace game