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

Dungeon

A dungeon crawler made of the behavior catalogue. Two LDtk levels -- the Crypt and the Sanctum -- in Kenney's Tiny Dungeon art, lit by braziers, gems and the hero's own light in the dark. Every monster is behaviors with the editor's numbers in them (B::from(MapObject)): a Slime is a Chase that finds its way with Pathfind, a Bat a Patrol along a path drawn in LDtk, a Spider a Patrol, a Chase and a StateMachine that flees when hurt, a Wizard a Shooter, the Cyclops a StateMachine of sleep, hunt and a spiral of bolts with Ghosts in Orbit round it. Gems and potions are Collectibles with a magnet, chests, levers, the altar and the stairs Areas, spikes a Hitbox a Timer turns on and off with enable<B>(), the blades an Orbit and a Hitbox, a rune a Draggable laid on the altar with the pointer, and the hero TopDown, Animator and Health with a sword that is a Hitbox. One Theme of nine-slices and a pixel font for the menus and the HUD. Its art, sounds and first world.ldtk come out of tools/make_dungeon_assets.py.

Dungeon, as it starts

Run it

From a clone of the framework:

rmp example 08_dungeon

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
attackSpace, J, gamepad right face down

The code

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

src/main.cpp 46 lines
// ---------------------------------------------------------------------------
// examples/games/08_dungeon -- a dungeon crawler whose levels are made in LDtk,
// and whose monsters are made of the behavior catalogue.
//
// Two levels of one LDtk world, the Crypt and the Sanctum, in Kenney's Tiny
// Dungeon art, under his Ancient frames and his pixel font.
//
// What the framework does here, and therefore what is NOT in these files:
//
//   rmp::Tilemap    resources/world.ldtk: the walls are its IntGrid `Solid`,
//                   drawn only where the camera looks; every monster, gem,
//                   trap, chest, lever, rune and stair is an entity with
//                   fields, built by a factory in src/objects/.
//   the behaviors   the whole cast is the catalogue with LDtk's numbers in
//                   it (B::from(MapObject)): a Slime is a Chase that finds its
//                   way with Pathfind; a Bat a Patrol along a path drawn in
//                   the editor; a Spider a Patrol, a Chase and a StateMachine
//                   that flees when it is hurt; a Wizard a Shooter; the
//                   Cyclops a StateMachine of sleep, hunt and a spiral of
//                   bolts, with Ghosts in Orbit round it. Gems and potions are
//                   Collectibles with a magnet; chests, levers, the altar and
//                   the stairs are Areas; spikes a Hitbox a Timer turns on and
//                   off (enable<B>); the blades an Orbit and a Hitbox; a rune a
//                   Draggable you lay on the altar with the pointer. The hero
//                   is TopDown, Animator and Health, and its sword a Hitbox.
//   rmp::Camera     follows, stays inside the level, shakes on a hit.
//   rmp::ui         the menus, the HUD and its health bar, all in one Theme
//                   of nine-slices and a pixel font (src/look.cpp).
//   rmp::audio      every sound, by name.
//   rmp::save       the most gems ever carried out.
//
// What is left is the game: what a gem is worth, what a potion heals, when
// the gate opens and when you have won.
//
// Move with the arrows or WASD, strike with Space or J (the A button), pause
// with Escape. Drag a rune onto the altar for another heart.
//
// Open resources/world.ldtk in LDtk 1.5 to change the levels.
// Run it: `rmp example 08_dungeon`.
// ---------------------------------------------------------------------------

#include <rmp/app.h>

#include "dungeon.h"

RMP_GAME(game::TitleScene);
include/cast.h 59 lines
#pragma once
// ---------------------------------------------------------------------------
// Everything in a level. Nearly all of it is a plain rmp::Object with the
// catalogue's behaviors on it, built from its LDtk entity by a factory in
// src/objects/: what it IS is which behaviors it carries and with which
// fields. The hero has a class of its own, because the sword is the game's.
// ---------------------------------------------------------------------------

#include "dungeon.h"

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

#include <raylib.h>

#include <string_view>

namespace game {

class Hero : public rmp::Object {
public:
    void _ready() override;
    void _update(float delta) override;

private:
    void swing();
    float _cooldown = 0; // seconds until the sword can swing again
};

// A light in the dark: what the level's darkness lets through, drawn over it
// by add_darkness()'s object. A flame breathes; a gem shines still.
struct Light {
    float radius = 30;
    Color color = { 255, 140, 40, 120 };
    bool flicker = true;
    float clock = 0;
    void _ready(rmp::Object &self);
    void _update(rmp::Object &self, float delta);
};

// The dark over the whole level, and every Light drawn on top of it.
void add_darkness(rmp::Scene &scene);

// One factory per entity type of world.ldtk, registered on the scene's map.
void add_monsters(rmp::Scene &scene, rmp::Handle<rmp::Object> hero);
void add_things(LevelScene &scene, rmp::Handle<rmp::Object> hero);

// Whether this level's Cyclops is still standing.
bool boss_lives();

// A burst of `count` sparks of `color` from `at`: a death, a pickup.
void sparks(rmp::Scene &scene, Vector2 at, Color color, int count);
// A number that rises and fades from `at`: "+1", "-1".
void float_text(rmp::Scene &scene, Vector2 at, std::string_view text, Color color);

// Whether `object` is the hero.
bool is_hero(const rmp::Object &object);

} // namespace game
include/dungeon.h 134 lines
#pragma once
// ---------------------------------------------------------------------------
// What every file of the dungeon shares: the collision layers, the run that
// outlives a level, the scenes, and the look.
// ---------------------------------------------------------------------------

#include <rmp/scene.h>

#include <raylib.h>

#include <string>
#include <string_view>

namespace game {

inline constexpr float TILE = 16; // the grid of tiles.png and of every level

// How much of the world is on screen: twelve and a half rows of tiles at the
// [window] size, each pixel of the art several of the screen's. A window of
// another shape shows more of the dungeon (Stretch::EXPAND), never less.
inline constexpr float VIEW_HEIGHT = 200;
inline constexpr float ZOOM = RMP_WINDOW_HEIGHT / VIEW_HEIGHT;

// The tiles of tiles.png the game draws by itself, by index (12 to a row).
namespace tiles {
inline constexpr int GEM = 102;
inline constexpr int RUNE = 101;
inline constexpr int POTION = 115;
inline constexpr int CHEST = 89;
inline constexpr int CHEST_OPEN = 91;
inline constexpr int LEVER = 80;
inline constexpr int LEVER_PULLED = 79;
inline constexpr int GATE = 45;
inline constexpr int ALTAR = 64;
inline constexpr int SPIKES = 41;
inline constexpr int BLADE = 103;
inline constexpr int PILLAR = 65;
inline constexpr int BRAZIER = 29;
inline constexpr int STAIRS = 56;
inline constexpr int PORTAL = 60;
inline constexpr int SWORD = 104;
inline constexpr int BOLT = 125;
} // namespace tiles

// Who notices whom.
namespace layer {
inline constexpr unsigned HERO = 1u << 0;
inline constexpr unsigned MONSTER = 1u << 1;
inline constexpr unsigned PICKUP = 1u << 2; // gems, potions, runes
inline constexpr unsigned TRAP = 1u << 3; // spikes, blades, bolts
inline constexpr unsigned PLACE = 1u << 4; // chests, levers, altars, stairs
inline constexpr unsigned WALL = 1u << 5; // the gate
inline constexpr unsigned SWING = 1u << 6; // the hero's sword
} // namespace layer

// THE RUN: what survives going down the stairs into the next level.
struct Run {
    int hp = 6;
    int max_hp = 6;
    int gems = 0;
    float seconds = 0;
};
Run &run();
void new_run();

// The best run, as rmp::save keeps it: the most gems.
int best_gems();
bool keep_if_best(int gems);

// The look of every screen: Kenney's Ancient frames, his pixel font, sounds
// on hover and click. Set once, by the title.
void set_look();

// A tile of tiles.png, centred on `at`, in the world.
void draw_tile(int index, Vector2 at, Color tint = WHITE, float scale = 1,
               float rotation = 0);
// A glow of `radius` around `at`, added to what is under it.
void draw_glow(Vector2 at, float radius, Color color);

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

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

private:
    float _clock = 0;
    int _best = -1;
};

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

    void hero_died();
    void go_down(const std::string &level);
    void win();
    // A line across the top of the screen for a moment: a room's name, a gate.
    void announce(std::string_view text);

private:
    void build();

    std::string _level;
    rmp::Handle<rmp::Object> _hero;
    std::string _banner;
    float _banner_left = 0;
    bool _over = false;
};

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

class EndScene : public rmp::Scene {
public:
    EndScene(bool won, bool record);
    void _draw() override;

private:
    bool _won;
    bool _record;
};

} // namespace game
src/look.cpp 121 lines
// The run, the best run, the look of every screen, and the two ways the game
// draws a tile of its own.

#include "dungeon.h"

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

#include <cmath>

namespace game {

namespace {

constexpr int COLUMNS = 12; // tiles.png, packed

// Kenney's Ancient frames are 48 pixels square; the border is 6 of them, and
// the bottom 8 with its shadow. Drawn three design units to a pixel of the art.
constexpr float FRAME = 6;
constexpr float FRAME_BOTTOM = 8;
constexpr float FRAME_SCALE = 3;

const Color PARCHMENT = { 248, 232, 200, 255 };
const Color INK = { 58, 34, 26, 255 };
const Color EMBER = { 255, 196, 92, 255 };

struct Art {
    rmp::Texture tiles = rmp::assets::load_texture("tiles.png");
};

rmp::ui::Picture frame(std::string_view file, float inset = 0) {
    return rmp::ui::NineSlice{ .texture = rmp::assets::load_texture(file),
                               .left = FRAME - inset,
                               .top = FRAME - inset,
                               .right = FRAME - inset,
                               .bottom = FRAME_BOTTOM - inset,
                               .scale = FRAME_SCALE };
}

} // namespace

Run &run() { return rmp::global<Run>(); }

void new_run() { rmp::global<Run>() = Run{}; }

int best_gems() {
    rmp::Value saved;
    rmp::save::read("dungeon", saved);
    return saved["gems"].as_int(-1);
}

bool keep_if_best(int gems) {
    if (gems <= best_gems()) return false;
    rmp::Value v;
    v["gems"] = gems;
    rmp::save::write("dungeon", v);
    return true;
}

void set_look() {
    rmp::ui::set_font(rmp::assets::load_font("font.ttf", 16));
    rmp::ui::Theme look = rmp::ui::theme_dark();
    look.text = PARCHMENT;
    look.text_muted = Color{ 214, 180, 140, 255 };
    look.primary = EMBER;
    look.sounds = { .hover = "hover", .click = "click", .volume = 0.6f };
    look.styles.panel = {
        .skin = rmp::ui::Skin{ .normal = frame("panel.png") },
        .shadow =
            rmp::ui::Shadow{ .offset = { 0, 8 }, .blur = 14, .color = { 0, 0, 0, 140 } },
        .padding_x = 28,
        .padding_y = 24,
        .gap = 14,
        .text_shadow =
            rmp::ui::TextShadow{ .offset = { 0, 2 }, .color = { 30, 14, 10, 200 } },
        .motion = rmp::ui::Motion{ .appear = 0.22f,
                                   .appear_offset = 14,
                                   .appear_scale = 0.97f },
    };
    look.styles.button = {
        .skin = rmp::ui::Skin{ .normal = frame("button.png"),
                               .press = frame("button_down.png") },
        .shadow =
            rmp::ui::Shadow{ .offset = { 0, 4 }, .blur = 6, .color = { 0, 0, 0, 120 } },
        .padding_x = 26,
        .padding_y = 12,
        .text = INK,
        .motion = rmp::ui::Motion{ .hover_scale = 1.05f, .press_scale = 0.95f },
    };
    look.styles.progress = {
        .skin = rmp::ui::Skin{ .normal = frame("inlay.png", 2) },
    };
    rmp::ui::set_theme(look);
}

void draw_tile(int index, Vector2 at, Color tint, float scale, float rotation) {
    const Texture2D &tiles = rmp::global<Art>().tiles;
    const Rectangle source{ static_cast<float>(index % COLUMNS) * TILE,
                            std::floor(static_cast<float>(index) / COLUMNS) * TILE, TILE,
                            TILE };
    const float size = TILE * scale;
    DrawTexturePro(tiles, source, Rectangle{ at.x, at.y, size, size },
                   Vector2{ size / 2, size / 2 }, rotation, tint);
}

void draw_glow(Vector2 at, float radius, Color color) {
    // Rings from the edge in, each adding a little light: a soft falloff that
    // needs nothing but circles.
    constexpr int RINGS = 14;
    const Color step{ color.r, color.g, color.b,
                      static_cast<unsigned char>(color.a / RINGS) };
    BeginBlendMode(BLEND_ADDITIVE);
    for (int i = 0; i < RINGS; ++i) {
        DrawCircleV(at, radius * static_cast<float>(RINGS - i) / RINGS, step);
    }
    EndBlendMode();
}

} // namespace game
src/objects/effects.cpp 128 lines
// Sparks and rising numbers: small objects that fade and go, made of the
// catalogue's Tween and Lifespan.

#include "cast.h"

#include <rmp/app.h>
#include <rmp/assets.h>
#include <rmp/behavior.h>
#include <rmp/random.h>

#include <cmath>
#include <string>
#include <vector>

namespace game {

namespace {

constexpr float SPARK_SIZE = 2;
constexpr float SPARK_SPEED = 70;
constexpr float SPARK_LIFE = 0.45f;
constexpr float TEXT_RISE = 26;
constexpr float TEXT_LIFE = 0.8f;
constexpr float TEXT_SIZE = 8;

struct Letters {
    rmp::Font font = rmp::assets::load_font("font.ttf", 8);
};

// A word in the world, drawn in the game's font, fading with its object.
struct Words {
    std::string text;
    Color color = WHITE;
    float elapsed = 0;
    void _update(rmp::Object &self, float delta) {
        (void)self;
        elapsed += delta;
    }
    void _draw(rmp::Object &self) {
        const Font &font = rmp::global<Letters>().font;
        const float fade = 1 - (elapsed / TEXT_LIFE);
        const Vector2 size = MeasureTextEx(font, text.c_str(), TEXT_SIZE, 0);
        const Vector2 at{ self.position.x - (size.x / 2),
                          self.position.y - (size.y / 2) };
        DrawTextEx(font, text.c_str(), Vector2{ at.x + 1, at.y + 1 }, TEXT_SIZE, 0,
                   Fade(BLACK, fade * 0.7f));
        DrawTextEx(font, text.c_str(), at, TEXT_SIZE, 0, Fade(color, fade));
    }
};

// How dark the dungeon is between its lights, of 255.
constexpr unsigned char DARK = 150;
const Color NIGHT = { 14, 6, 18, DARK };

// Every object with a Light, for the darkness to draw.
std::vector<rmp::Handle<rmp::Object>> lit;

struct Dark {
    void _update(rmp::Object &self, float delta) {
        (void)self;
        (void)delta;
    }
    void _draw(rmp::Object &self) {
        const Rectangle view = self.scene().camera.view();
        DrawRectangleRec(Rectangle{ view.x - TILE, view.y - TILE, view.width + (2 * TILE),
                                    view.height + (2 * TILE) },
                         NIGHT);
        std::erase_if(lit, [](const rmp::Handle<rmp::Object> &h) { return !h; });
        for (const rmp::Handle<rmp::Object> &h : lit) {
            const auto object = h.get();
            if (!object->visible || !object->enabled<Light>()) continue;
            const Light &light = *object->get<Light>();
            const float breath = light.flicker
                ? 1 + (0.08f * std::sin(light.clock * 7.3f)) +
                    (0.05f * std::sin(light.clock * 13.1f))
                : 1;
            draw_glow(object->position, light.radius * breath, light.color);
        }
    }
};

} // namespace

void Light::_ready(rmp::Object &self) { lit.push_back(self.handle()); }

void Light::_update(rmp::Object &self, float delta) {
    (void)self;
    clock += delta;
}

void add_darkness(rmp::Scene &scene) {
    lit.clear();
    auto &dark = scene.spawn({ .layer = 50 });
    dark.collision_layer = 0;
    dark.collision_mask = 0;
    dark.add<Dark>();
}

void sparks(rmp::Scene &scene, Vector2 at, Color color, int count) {
    for (int i = 0; i < count; ++i) {
        const Vector2 velocity{ rmp::random::range(-SPARK_SPEED, SPARK_SPEED),
                                rmp::random::range(-SPARK_SPEED, SPARK_SPEED) };
        auto &spark = scene.spawn({ .position = at,
                                    .size = { SPARK_SIZE, SPARK_SIZE },
                                    .velocity = velocity,
                                    .layer = 8 });
        spark.shape.color = color;
        spark.collision_layer = 0;
        spark.collision_mask = 0;
        spark.add<rmp::behavior::Tween>({ .property = rmp::behavior::Property::ALPHA,
                                          .from = 255,
                                          .to = 0,
                                          .seconds = SPARK_LIFE,
                                          .ease = rmp::behavior::Ease::IN });
        spark.add<rmp::behavior::Lifespan>({ .seconds = SPARK_LIFE });
    }
}

void float_text(rmp::Scene &scene, Vector2 at, std::string_view text, Color color) {
    auto &words = scene.spawn(
        { .position = at, .velocity = { 0, -TEXT_RISE / TEXT_LIFE }, .layer = 9 });
    words.collision_layer = 0;
    words.collision_mask = 0;
    words.add<Words>({ .text = std::string(text), .color = color });
    words.add<rmp::behavior::Lifespan>({ .seconds = TEXT_LIFE });
}

} // namespace game
src/objects/hero.cpp 119 lines
// The hero: walks with TopDown, is drawn by an Animator, lives with a Health,
// and swings a sword -- a Hitbox that lives a fifth of a second, in front.

#include "cast.h"

#include <rmp/assets.h>
#include <rmp/audio.h>
#include <rmp/behavior.h>
#include <rmp/input.h>

#include <cmath>
#include <numbers>

namespace game {

namespace {

constexpr float SPEED = 84;
constexpr float SWING_EVERY = 0.32f;
constexpr float SWING_LASTS = 0.18f;
constexpr float SWING_REACH = 13;
constexpr float SWING_SIZE = 18;
constexpr float SWING_KNOCKBACK = 260;
constexpr float GRACE = 0.9f; // seconds safe after a hit
constexpr float SHAKE = 3;

// The blade, drawn turning through its arc while the swing lives.
struct Slash {
    float angle = 0; // degrees, where the arc is centred
    float elapsed = 0;
    void _update(rmp::Object &self, float delta) {
        (void)self;
        elapsed += delta;
    }
    void _draw(rmp::Object &self) {
        const float t = elapsed / SWING_LASTS;
        const float turn = angle - 70 + (140 * t) + 45; // the tile points up-right
        draw_tile(tiles::SWORD, self.position, WHITE, 1.2f, turn);
    }
};

} // namespace

bool is_hero(const rmp::Object &object) { return object.collision_layer == layer::HERO; }

void Hero::_ready() {
    sprite.sheet = rmp::assets::load_sheet("hero.aseprite");
    collider = rmp::rect({ 10, 10 });
    solid = true;
    collision_layer = layer::HERO;
    collision_mask =
        layer::MONSTER | layer::PICKUP | layer::TRAP | layer::PLACE | layer::WALL;
    layer = 5;

    add<rmp::behavior::TopDown>({ .speed = SPEED, .idle = "", .walk = "" });
    add<rmp::behavior::Animator>();
    add<Light>({ .radius = 78, .color = { 255, 200, 140, 80 } });
    add<rmp::behavior::Health>({
        .hp = run().hp,
        .max_hp = run().max_hp,
        .invulnerable_for = GRACE,
        .destroy_on_death = false,
        .on_death =
            [](rmp::Object &self) {
                static_cast<LevelScene &>(self.scene()).hero_died();
            },
        .on_damage =
            [](rmp::Object &self, int amount) {
                run().hp = self.get<rmp::behavior::Health>()->hp;
                self.scene().camera.shake(SHAKE, 0.25f);
                rmp::audio::play("hurt");
                sparks(self.scene(), self.position, Color{ 228, 59, 68, 255 }, 10);
                float_text(self.scene(), self.position, TextFormat("-%d", amount),
                           Color{ 255, 90, 90, 255 });
            },
    });
}

void Hero::_update(float delta) {
    _cooldown -= delta;
    const auto health = get<rmp::behavior::Health>();
    if (health && health->dead()) {
        velocity = Vector2{};
        enable<rmp::behavior::TopDown>(false);
        return;
    }
    if (health) {
        // A potion or the altar heals the run; the Health follows it.
        health->max_hp = run().max_hp;
        if (run().hp > health->hp) health->heal(run().hp - health->hp);
    }
    if (rmp::input::just_pressed("attack") && _cooldown <= 0) swing();
}

void Hero::swing() {
    _cooldown = SWING_EVERY;
    const Vector2 facing = get<rmp::behavior::TopDown>()->direction();
    const Vector2 at{ position.x + (facing.x * SWING_REACH),
                      position.y + (facing.y * SWING_REACH) };
    auto &slash = scene().spawn({ .position = at, .layer = 6 });
    slash.collider = rmp::rect({ SWING_SIZE, SWING_SIZE }); // felt, and drawn by Slash
    slash.collision_layer = layer::SWING;
    slash.collision_mask = layer::MONSTER;
    slash.add<rmp::behavior::Hitbox>({ .damage = 1,
                                       .hits = layer::MONSTER,
                                       .knockback = SWING_KNOCKBACK,
                                       .once_per_target = true,
                                       .on_hit = [](rmp::Object &, rmp::Object &victim) {
                                           rmp::audio::play("hit");
                                           sparks(victim.scene(), victim.position,
                                                  Color{ 255, 236, 180, 255 }, 6);
                                       } });
    slash.add<rmp::behavior::Lifespan>({ .seconds = SWING_LASTS });
    slash.add<Slash>(
        { .angle = std::atan2(facing.y, facing.x) * 180 / std::numbers::pi_v<float> });
    rmp::audio::play("swing", { .volume = 0.5f });
}

} // namespace game
src/objects/monsters.cpp 206 lines
// The monsters. Each is a list of behaviors with the fields LDtk gave it:
//
//   Slime    Chase + Pathfind: it sees you, and finds its way round the walls
//   Bat      Patrol along the Array<Point> drawn in the editor
//   Spider   Patrol + Chase, and a StateMachine that flees when it is hurt
//   Wizard   Shooter, aimed at you, three bolts in a fan, in range
//   Cyclops  a StateMachine: asleep, hunting (Pathfind), a spiral of bolts
//   Ghost    Orbit round the Cyclops
//
// Every one has an Animator, a Health and a Hitbox that hurts on touch.

#include "cast.h"

#include <rmp/assets.h>
#include <rmp/audio.h>
#include <rmp/behavior.h>
#include <rmp/random.h>

#include <raymath.h>

#include <string>
#include <utility>

namespace game {

namespace {

namespace b = rmp::behavior;

constexpr float TOUCH_KNOCKBACK = 240;
constexpr float BOLT_RADIUS = 3;
constexpr float BOLT_LIFE = 2.5f;
constexpr float BOLT_GLOW = 14;
constexpr float BODY = 11; // a monster's collider, square
constexpr float FLEE_SPEED = 70;
constexpr float FLEE_SECONDS = 2;
constexpr float WAKE_DISTANCE = 120;
constexpr float HUNT_SECONDS = 3.5f;
constexpr float VOLLEY_SECONDS = 2.8f;
constexpr float BOSS_SPEED = 38;
const Color BOLT = { 190, 120, 255, 255 };
const Color FIRE = { 255, 150, 60, 255 };
const Color GORE = { 120, 220, 120, 255 };

// The Cyclops the Ghosts circle: built first, because LDtk lists it first.
rmp::Handle<rmp::Object> boss;

float distance(Vector2 a, Vector2 c) { return Vector2Distance(a, c); }

rmp::Object &monster(rmp::Scene &s, const rmp::MapObject &o, std::string_view sheet,
                     int hp) {
    auto &m = s.spawn({ .position = o.position, .layer = 4 });
    m.sprite.sheet = rmp::assets::load_sheet(sheet);
    m.collider = rmp::rect({ BODY, BODY });
    m.solid = true;
    m.collision_layer = layer::MONSTER;
    m.collision_mask = layer::HERO | layer::SWING | layer::MONSTER | layer::WALL;
    m.add<b::Hitbox>({ .damage = 1, .hits = layer::HERO, .knockback = TOUCH_KNOCKBACK });
    m.add<b::Health>(
        { .hp = hp, .invulnerable_for = 0.25f, .on_death = [](rmp::Object &self) {
             rmp::audio::play("hit", { .pitch = 0.7f });
             sparks(self.scene(), self.position, GORE, 14);
         } });
    m.add<b::Animator>();
    return m;
}

// A bolt of the wizard's or the cyclops's: a violet spark that hurts the hero
// and ends at a wall.
void bolt(rmp::Scene &s, Vector2 at, Vector2 velocity) {
    auto &shot = s.spawn({ .position = at,
                           .shape = rmp::circle(BOLT_RADIUS),
                           .velocity = velocity,
                           .layer = 7 });
    shot.shape.color = BOLT;
    shot.collision_layer = layer::TRAP;
    shot.collision_mask = layer::HERO;
    shot.add<b::Hitbox>(
        { .damage = 1, .hits = layer::HERO, .knockback = 160, .destroy_on_hit = true });
    shot.add<b::Projectile>({ .destroy_on_wall = true });
    shot.add<b::Lifespan>({ .seconds = BOLT_LIFE });
    shot.add<Light>(
        { .radius = BOLT_GLOW, .color = Color{ 150, 80, 255, 170 }, .flicker = false });
}

} // namespace

bool boss_lives() { return static_cast<bool>(boss); }

void add_monsters(rmp::Scene &scene, rmp::Handle<rmp::Object> hero) {
    rmp::Tilemap &map = scene.map;
    boss = {};

    map.on_object("Slime", [hero](rmp::Scene &s, const rmp::MapObject &o) {
        auto &slime = monster(s, o, "slime.aseprite", 2);
        b::Chase chase = b::Chase::from(o);
        chase.target = hero;
        slime.add<b::Pathfind>({ .clearance = 4 });
        slime.add(std::move(chase));
    });

    map.on_object("Bat", [](rmp::Scene &s, const rmp::MapObject &o) {
        auto &bat = monster(s, o, "bat.aseprite", 1);
        bat.solid = false; // it flies
        bat.add(b::Patrol::from(o));
    });

    map.on_object("Spider", [hero](rmp::Scene &s, const rmp::MapObject &o) {
        auto &spider = monster(s, o, "spider.aseprite", 3);
        b::Chase chase = b::Chase::from(o);
        chase.target = hero;
        spider.add(b::Patrol::from(o));
        spider.add(std::move(chase));
        // Hurt down to its last point, it runs from you for a while.
        b::StateMachine mind;
        mind.states.push_back(
            { .name = "hunt", .enables = b::kinds<b::Patrol, b::Chase>() });
        mind.states.push_back(
            { .name = "flee", .on_update = [hero](rmp::Object &self, float) {
                 if (const auto h = hero.get()) {
                     const Vector2 away =
                         Vector2Normalize(Vector2Subtract(self.position, h->position));
                     self.velocity = Vector2Scale(away, FLEE_SPEED);
                 }
             } });
        mind.transitions.push_back(
            { .from = "hunt", .to = "flee", .when = [](rmp::Object &self) {
                 return self.get<b::Health>()->hp == 1;
             } });
        mind.transitions.push_back(
            { .from = "flee", .to = "hunt", .when = [](rmp::Object &self) {
                 return self.get<b::StateMachine>()->seconds_in_state() > FLEE_SECONDS;
             } });
        spider.add(std::move(mind));
    });

    map.on_object("Wizard", [hero](rmp::Scene &s, const rmp::MapObject &o) {
        auto &wizard = monster(s, o, "wizard.aseprite", 2);
        wizard.solid = false;
        wizard.immovable = true;
        b::Shooter staff = b::Shooter::from(o);
        staff.automatic = true;
        staff.target = hero;
        staff.on_shoot = [](rmp::Scene &scene, Vector2 at, Vector2 velocity) {
            bolt(scene, at, velocity);
        };
        wizard.add(std::move(staff));
        wizard.add<Light>({ .radius = 22, .color = Color{ 90, 40, 160, 90 } });
    });

    map.on_object("Cyclops", [hero](rmp::Scene &s, const rmp::MapObject &o) {
        auto &cyclops = monster(s, o, "cyclops.aseprite", o.property_int("hp", 14));
        cyclops.scale = { 2, 2 };
        cyclops.collider = rmp::rect({ BODY * 1.4f, BODY * 1.4f });
        boss = cyclops.handle();
        cyclops.get<b::Health>()->on_death = [](rmp::Object &self) {
            sparks(self.scene(), self.position, FIRE, 40);
            self.scene().camera.shake(6, 0.6f);
            static_cast<LevelScene &>(self.scene()).announce("The Sanctum falls silent");
        };
        cyclops.add<b::Pathfind>({ .target = hero, .speed = BOSS_SPEED, .clearance = 6 });
        cyclops.add<b::Shooter>({ .every = 0.3f,
                                  .speed = 90,
                                  .count = 6,
                                  .spread = 360,
                                  .rotate_per_shot = 17,
                                  .on_shoot = [](rmp::Scene &scene, Vector2 at,
                                                 Vector2 v) { bolt(scene, at, v); } });
        // Asleep until you come near; then it hunts you, and stops to throw
        // a spiral of bolts, and hunts again.
        b::StateMachine mind;
        mind.states.push_back({ .name = "asleep" });
        mind.states.push_back({ .name = "hunt", .enables = b::kinds<b::Pathfind>() });
        mind.states.push_back({ .name = "volley",
                                .on_enter = [](rmp::Object &self) { self.velocity = {}; },
                                .enables = b::kinds<b::Shooter>() });
        mind.transitions.push_back(
            { .from = "asleep", .to = "hunt", .when = [hero](rmp::Object &self) {
                 const auto h = hero.get();
                 return h && distance(h->position, self.position) < WAKE_DISTANCE;
             } });
        mind.transitions.push_back(
            { .from = "hunt", .to = "volley", .when = [](rmp::Object &self) {
                 return self.get<b::StateMachine>()->seconds_in_state() > HUNT_SECONDS;
             } });
        mind.transitions.push_back(
            { .from = "volley", .to = "hunt", .when = [](rmp::Object &self) {
                 return self.get<b::StateMachine>()->seconds_in_state() > VOLLEY_SECONDS;
             } });
        cyclops.add(std::move(mind));
        cyclops.get<b::Shooter>()->automatic = true;
        cyclops.add<Light>({ .radius = 40, .color = Color{ 160, 40, 30, 90 } });
    });

    map.on_object("Ghost", [](rmp::Scene &s, const rmp::MapObject &o) {
        auto &ghost = monster(s, o, "ghost.aseprite", 1);
        ghost.solid = false;
        b::Orbit orbit = b::Orbit::from(o);
        orbit.centre = boss;
        orbit.point = o.position;
        ghost.add(orbit);
        ghost.sprite.tint = Color{ 255, 255, 255, 200 };
    });
}

} // namespace game
src/objects/things.cpp 246 lines
// What is not alive: gems and potions (Collectible), chests, levers, the
// altar and the stairs (Area), runes (Draggable), spikes (Hitbox and Timer),
// the blades round their pillar (Orbit and Hitbox), the gate a lever opens,
// and the braziers that light it all.

#include "cast.h"

#include <rmp/assets.h>
#include <rmp/audio.h>
#include <rmp/behavior.h>
#include <rmp/random.h>

#include <cmath>
#include <raymath.h>

#include <string>
#include <utility>
#include <vector>

namespace game {

namespace {

namespace b = rmp::behavior;

constexpr float PICKUP = 10;
constexpr float SPILL_SPEED = 60;
constexpr float SPIKES_EVERY = 1.1f;
constexpr int POTION_HEALS = 2;
const Color GEM_LIGHT = { 60, 200, 255, 110 };
const Color SHINE = { 255, 214, 102, 255 };
const Color FLAME = { 255, 140, 40, 120 };

Rectangle tile_rect(int index) {
    constexpr int COLUMNS = 12;
    return Rectangle{ static_cast<float>(index % COLUMNS) * TILE,
                      std::floor(static_cast<float>(index) / COLUMNS) * TILE, TILE,
                      TILE };
}

// An object drawn as one tile of tiles.png.
rmp::Object &thing(rmp::Scene &s, Vector2 at, int tile, int draw_layer = 2) {
    auto &t = s.spawn({ .position = at, .layer = draw_layer });
    t.sprite.texture = rmp::assets::load_texture("tiles.png");
    t.sprite.source = tile_rect(tile);
    t.collider = rmp::rect({ PICKUP, PICKUP });
    t.collision_layer = layer::PLACE;
    t.collision_mask = layer::HERO;
    return t;
}

// Slows what was thrown to a stop: a gem out of a chest.
struct Slide {
    float keep = 0.9f; // of its speed, every sixtieth of a second
    void _update(rmp::Object &self, float delta) {
        self.velocity = Vector2Scale(self.velocity, std::pow(keep, delta * 60));
    }
};

// The gates, by their LDtk iid, so that a lever can find the one it opens.
std::vector<std::pair<std::string, rmp::Handle<rmp::Object>>> gates;

void gem(rmp::Scene &s, Vector2 at, Vector2 velocity = {}) {
    auto &g = thing(s, at, tiles::GEM, 3);
    g.velocity = velocity;
    g.collision_layer = layer::PICKUP;
    g.add<b::Collectible>({ .collected_by = layer::HERO,
                            .sound = "coin",
                            .magnet = 26,
                            .on_collect = [](rmp::Object &self, rmp::Object &) {
                                ++run().gems;
                                float_text(self.scene(), self.position, "+1", SHINE);
                            } });
    g.add<Light>({ .radius = 14, .color = GEM_LIGHT, .flicker = false });
    if (velocity.x != 0 || velocity.y != 0) g.add<Slide>();
}

void spill_gems(rmp::Scene &s, Vector2 at, int count) {
    for (int i = 0; i < count; ++i) {
        const float angle = rmp::random::range(0.0f, 6.2831f);
        gem(s, at,
            Vector2{ std::cos(angle) * SPILL_SPEED, std::sin(angle) * SPILL_SPEED });
    }
}

} // namespace

void add_things(LevelScene &scene, rmp::Handle<rmp::Object> hero) {
    rmp::Tilemap &map = scene.map;
    (void)hero;
    gates.clear();

    map.on_object("Gem",
                  [](rmp::Scene &s, const rmp::MapObject &o) { gem(s, o.position); });

    map.on_object("Potion", [](rmp::Scene &s, const rmp::MapObject &o) {
        auto &p = thing(s, o.position, tiles::POTION, 3);
        p.collision_layer = layer::PICKUP;
        p.add<b::Collectible>({ .collected_by = layer::HERO,
                                .sound = "potion",
                                .on_collect = [](rmp::Object &self, rmp::Object &) {
                                    run().hp =
                                        std::min(run().max_hp, run().hp + POTION_HEALS);
                                    float_text(self.scene(), self.position, "+2",
                                               Color{ 255, 110, 110, 255 });
                                } });
        p.add<Light>({ .radius = 12, .color = Color{ 255, 60, 60, 90 } });
    });

    map.on_object("Brazier", [](rmp::Scene &s, const rmp::MapObject &o) {
        auto &fire = thing(s, o.position, tiles::BRAZIER, 1);
        fire.collision_mask = 0;
        fire.add<Light>({ .radius = 70, .color = FLAME });
    });

    map.on_object("Chest", [](rmp::Scene &s, const rmp::MapObject &o) {
        auto &chest = thing(s, o.position, tiles::CHEST);
        const int count = o.property_int("gems", 5);
        chest.add<b::Area>({ .on_enter = [count](rmp::Object &self, rmp::Object &who) {
            if (!is_hero(who) || self.sprite.source.x == tile_rect(tiles::CHEST_OPEN).x)
                return;
            self.sprite.source = tile_rect(tiles::CHEST_OPEN);
            rmp::audio::play("chest");
            spill_gems(self.scene(), self.position, count);
        } });
    });

    map.on_object("Gate", [](rmp::Scene &s, const rmp::MapObject &o) {
        auto &gate = thing(s, o.position, tiles::GATE);
        gate.collider = rmp::rect({ TILE, TILE });
        gate.solid = true;
        gate.immovable = true;
        gate.collision_layer = layer::WALL;
        gate.collision_mask = layer::HERO | layer::MONSTER;
        gate.layer = 3;
        gates.emplace_back(std::string(o.iid), gate.handle());
    });

    map.on_object("Lever", [&scene](rmp::Scene &s, const rmp::MapObject &o) {
        auto &lever = thing(s, o.position, tiles::LEVER);
        const std::string opens(o.property_string("opens"));
        lever.add<b::Area>({ .on_enter = [&scene, opens](rmp::Object &self,
                                                         rmp::Object &who) {
            if (!is_hero(who) || self.sprite.source.x == tile_rect(tiles::LEVER_PULLED).x)
                return;
            self.sprite.source = tile_rect(tiles::LEVER_PULLED);
            rmp::audio::play("door");
            scene.camera.shake(2, 0.4f);
            scene.announce("A gate grinds open");
            for (const auto &[iid, handle] : gates) {
                const auto gate = handle.get();
                if (iid != opens || !gate) continue;
                sparks(scene, gate->position, Color{ 200, 180, 160, 255 }, 16);
                gate->destroy();
            }
        } });
    });

    map.on_object("Spikes", [](rmp::Scene &s, const rmp::MapObject &o) {
        auto &spikes = thing(s, o.position, tiles::SPIKES, 1);
        spikes.collider = rmp::rect({ 12, 12 });
        spikes.collision_layer = layer::TRAP;
        spikes.add(b::Hitbox::from(o));
        // Up and down: a Timer flips the Hitbox on and off, and the tile with it.
        spikes.add<b::Timer>(
            { .seconds = SPIKES_EVERY, .on_timeout = [](rmp::Object &self) {
                 const bool up = !self.enabled<b::Hitbox>();
                 self.enable<b::Hitbox>(up);
                 self.sprite.tint = up ? WHITE : Color{ 120, 110, 110, 255 };
             } });
    });

    map.on_object("Blades", [](rmp::Scene &s, const rmp::MapObject &o) {
        auto &pillar = thing(s, o.position, tiles::PILLAR, 3);
        pillar.collider = rmp::rect({ TILE, TILE });
        pillar.solid = true;
        pillar.immovable = true;
        pillar.collision_layer = layer::WALL;
        const int count = o.property_int("blades", 3);
        for (int i = 0; i < count; ++i) {
            auto &blade = thing(s, o.position, tiles::BLADE, 4);
            blade.collision_layer = layer::TRAP;
            blade.add(b::Hitbox::from(o));
            b::Orbit orbit = b::Orbit::from(o);
            orbit.point = o.position;
            orbit.face = b::Face::OUTWARD;
            orbit.index = i;
            orbit.of = count;
            blade.add(orbit);
            blade.add<Light>({ .radius = 9, .color = Color{ 220, 230, 255, 70 } });
        }
    });

    map.on_object("Altar", [&scene](rmp::Scene &s, const rmp::MapObject &o) {
        auto &altar = thing(s, o.position, tiles::ALTAR);
        altar.collider = rmp::rect({ 22, 22 });
        altar.add<b::Area>();
        altar.add<Light>({ .radius = 26, .color = Color{ 255, 230, 140, 70 } });
        (void)scene;
    });

    map.on_object("Rune", [&scene](rmp::Scene &s, const rmp::MapObject &o) {
        auto &rune = thing(s, o.position, tiles::RUNE, 3);
        rune.collider = rmp::rect({ 14, 14 });
        rune.add<Light>({ .radius = 14, .color = Color{ 255, 230, 120, 110 } });
        // Picked up with the pointer and laid on the altar: a heart more.
        rune.add<b::Draggable>({ .drop_on = layer::PLACE,
                                 .on_drop = [&scene](rmp::Object &self, rmp::Object &) {
                                     rmp::audio::play("rune");
                                     ++run().max_hp;
                                     run().hp = run().max_hp;
                                     sparks(scene, self.position, SHINE, 20);
                                     scene.announce("The altar blesses you");
                                     self.destroy();
                                 } });
    });

    map.on_object("Stairs", [&scene](rmp::Scene &s, const rmp::MapObject &o) {
        auto &stairs = thing(s, o.position, tiles::STAIRS, 1);
        const std::string to(o.property_string("to", "Sanctum"));
        stairs.add<b::Area>({ .on_inside = [&scene, to](rmp::Object &, rmp::Object &who) {
            if (is_hero(who)) scene.go_down(to);
        } });
        stairs.add<Light>({ .radius = 22, .color = Color{ 120, 160, 255, 80 } });
    });

    map.on_object("Exit", [&scene](rmp::Scene &s, const rmp::MapObject &o) {
        auto &exit = thing(s, o.position, tiles::STAIRS, 1);
        exit.collider = rmp::rect({ 18, 18 });
        exit.visible = false;
        // Shut until the Cyclops is gone.
        exit.add<b::Area>({ .on_enter = [&scene](rmp::Object &self, rmp::Object &who) {
            if (is_hero(who) && self.visible) scene.win();
        } });
        exit.add<Light>({ .radius = 36, .color = Color{ 255, 220, 120, 130 } });
        exit.enable<Light>(false);
        exit.add<b::Timer>({ .seconds = 0.25f, .on_timeout = [](rmp::Object &self) {
                                if (self.visible || boss_lives()) return;
                                self.visible = true;
                                self.enable<Light>(true);
                                sparks(self.scene(), self.position, SHINE, 24);
                            } });
    });
}

} // namespace game
src/scenes/end.cpp 29 lines
// The end of a run, won or lost, over the level it ended in.

#include "dungeon.h"

#include <rmp/ui.h>

namespace game {

EndScene::EndScene(bool won, bool record) : _won(won), _record(record) {}

void EndScene::_draw() {
    rmp::ui::overlay({ .blur = 4, .dim = 0.55f }, [this] {
        rmp::ui::panel([this] {
            rmp::ui::text(_won ? "You walk out into the dawn" : "The crypt keeps you",
                          { .size = rmp::ui::Size::LARGE, .wrap = false });
            rmp::ui::text(TextFormat("%d %s in %.0f seconds", run().gems,
                                     run().gems == 1 ? "gem" : "gems", run().seconds),
                          { .color = rmp::ui::ColorRole::MUTED, .wrap = false });
            if (_record) rmp::ui::text("More than ever before!", { .wrap = false });
            if (rmp::ui::button("Again")) {
                new_run();
                rmp::Scene::change<LevelScene>("Crypt");
            }
            if (rmp::ui::button("Title")) rmp::Scene::change<TitleScene>();
        });
    });
}

} // namespace game
src/scenes/level.cpp 150 lines
// A level: the map, the hero, what LDtk placed, and the HUD over it all.

#include "dungeon.h"
#include "cast.h"

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

#include <algorithm>
#include <cmath>
#include <utility>

namespace game {

namespace {

constexpr float BANNER_SECONDS = 2.6f;
constexpr float SHADE = 150; // how dark the edges of the screen go, of 255
constexpr float SHADE_SHARE = 0.22f; // how far in from each edge the shade reaches
constexpr int COLUMNS = 12;

const Color HEALTH = { 214, 64, 64, 255 };

rmp::ui::Picture icon(int tile) {
    return { rmp::assets::load_texture("tiles.png"),
             Rectangle{ static_cast<float>(tile % COLUMNS) * TILE,
                        std::floor(static_cast<float>(tile) / COLUMNS) * TILE, TILE,
                        TILE } };
}

// The torchlight's edge: the screen darkens towards its borders.
void shade_edges() {
    const auto w = static_cast<float>(GetScreenWidth());
    const auto h = static_cast<float>(GetScreenHeight());
    const Color dark{ 10, 4, 6, static_cast<unsigned char>(SHADE) };
    const Color clear{ 10, 4, 6, 0 };
    const float dx = w * SHADE_SHARE;
    const float dy = h * SHADE_SHARE;
    DrawRectangleGradientV(0, 0, static_cast<int>(w), static_cast<int>(dy), dark, clear);
    DrawRectangleGradientV(0, static_cast<int>(h - dy), static_cast<int>(w),
                           static_cast<int>(dy), clear, dark);
    DrawRectangleGradientH(0, 0, static_cast<int>(dx), static_cast<int>(h), dark, clear);
    DrawRectangleGradientH(static_cast<int>(w - dx), 0, static_cast<int>(dx),
                           static_cast<int>(h), clear, dark);
}

} // namespace

LevelScene::LevelScene(std::string level) : _level(std::move(level)) {}

void LevelScene::_ready() {
    background = Color{ 37, 19, 26, 255 };
    rmp::input::action("pause", KEY_ESCAPE, KEY_P, GAMEPAD_BUTTON_MIDDLE_RIGHT);
    rmp::input::action("attack", KEY_SPACE, KEY_J, GAMEPAD_BUTTON_RIGHT_FACE_DOWN);
    build();
}

void LevelScene::build() {
    map = rmp::assets::load_map("world.ldtk", _level);
    add_darkness(*this); // first: every Light from here on is drawn over it
    auto &hero = spawn<Hero>();
    _hero = hero.handle();
    map.on_object("Player", [this](rmp::Scene &, const rmp::MapObject &o) {
        if (const auto h = _hero.get()) h->position = o.position;
    });
    add_monsters(*this, _hero);
    add_things(*this, _hero);
    map.spawn_objects(*this);

    camera.follow = _hero;
    camera.limits = map.bounds();
    camera.smoothing = 8;
    camera.zoom = ZOOM;
    announce(_level == "Crypt" ? "The Crypt" : "The Sanctum");
}

void LevelScene::_update(float delta) {
    if (_over) return;
    if (rmp::input::just_pressed("pause")) {
        rmp::Scene::push<PauseScene>();
        return;
    }
    run().seconds += delta;
    _banner_left = std::max(0.0f, _banner_left - delta);
}

void LevelScene::announce(std::string_view text) {
    _banner = std::string(text);
    _banner_left = BANNER_SECONDS;
}

void LevelScene::hero_died() {
    if (_over) return;
    _over = true;
    camera.shake(6, 0.5f);
    if (const auto h = _hero.get()) h->sprite.play("die", false);
    rmp::Scene::push<EndScene>(false, keep_if_best(run().gems));
}

void LevelScene::go_down(const std::string &level) {
    if (_over) return;
    _over = true;
    rmp::audio::play("door");
    rmp::Scene::change<LevelScene>(level);
}

void LevelScene::win() {
    if (_over) return;
    _over = true;
    rmp::Scene::push<EndScene>(true, keep_if_best(run().gems));
}

void LevelScene::_draw() {
    shade_edges();

    // The HUD: health and gems in a frame at the top left.
    rmp::ui::begin({ .placement = rmp::ui::Align::TOP_LEFT, .padding = 12 });
    rmp::ui::panel([] {
        rmp::ui::row([] {
            rmp::ui::image(icon(tiles::POTION), { .width = 24, .height = 24 });
            rmp::ui::progress(static_cast<float>(run().hp) /
                                  static_cast<float>(run().max_hp),
                              { .width = 120, .fill = HEALTH });
            rmp::ui::text(TextFormat("%d/%d", run().hp, run().max_hp), { .wrap = false });
        });
        rmp::ui::row([] {
            rmp::ui::image(icon(tiles::GEM), { .width = 24, .height = 24 });
            rmp::ui::text(TextFormat("%d", run().gems), { .wrap = false });
        });
    });
    rmp::ui::end();

    rmp::ui::begin({ .placement = rmp::ui::Align::TOP_RIGHT, .padding = 12 });
    if (rmp::ui::button("Pause")) rmp::Scene::push<PauseScene>();
    rmp::ui::end();

    if (_banner_left > 0) {
        rmp::ui::begin({ .placement = rmp::ui::Align::TOP_CENTER, .padding = 70 });
        rmp::ui::panel([this] {
            rmp::ui::text(_banner, { .size = rmp::ui::Size::LARGE, .wrap = false });
        });
        rmp::ui::end();
    }
}

} // namespace game
src/scenes/pause.cpp 24 lines
// The pause: the level frozen and blurred behind it.

#include "dungeon.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({ .blur = 6, .dim = 0.5f }, [] {
        rmp::ui::panel([] {
            rmp::ui::text("Paused", { .size = rmp::ui::Size::LARGE, .wrap = false });
            if (rmp::ui::button("Resume")) rmp::Scene::pop();
            if (rmp::ui::button("Leave the dungeon")) rmp::Scene::change<TitleScene>();
        });
    });
}

} // namespace game
src/scenes/title.cpp 64 lines
// The title: the Crypt behind the menu, the camera drifting through it.

#include "dungeon.h"

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

#include <cmath>

namespace game {

namespace {
constexpr float DRIFT = 0.12f; // how fast the camera wanders, in turns of a sine
const Color TITLE = { 255, 210, 120, 255 };
const Color SHADOW = { 20, 8, 6, 255 };
} // namespace

void TitleScene::_ready() {
    rmp::app::set_stretch(rmp::app::Stretch::EXPAND);
    set_look();
    background = Color{ 37, 19, 26, 255 };
    map = rmp::assets::load_map("world.ldtk", "Crypt");
    camera.limits = map.bounds();
    camera.zoom = ZOOM;
    _best = best_gems();
}

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 / 3),
                        b.y + (b.height / 2) +
                            (std::cos(_clock * DRIFT * 0.7f) * b.height / 4) };
}

void TitleScene::_draw() {
    rmp::ui::begin();
    rmp::ui::panel([this] {
        rmp::ui::Label title{ .text = "EMBERFALL",
                              .size = 44,
                              .wrap = false,
                              .style = { .text = TITLE,
                                         .text_outline = rmp::ui::TextOutline{
                                             .width = 2, .color = SHADOW } } };
        title.show();
        rmp::ui::text("A crypt, a cyclops, and you",
                      { .color = rmp::ui::ColorRole::MUTED, .wrap = false });
        if (_best >= 0) {
            rmp::ui::text(TextFormat("Most gems carried out: %d", _best),
                          { .color = rmp::ui::ColorRole::MUTED, .wrap = false });
        }
        if (rmp::ui::button("Descend")) {
            new_run();
            rmp::Scene::change<LevelScene>("Crypt");
        }
#if !defined(PLATFORM_IOS)
        if (rmp::ui::button("Quit")) rmp::app::quit();
#endif
    });
    rmp::ui::end();
}

} // namespace game