Saving a record
A score is more fun with something to beat. This page keeps the most coins anyone has gathered in one game, on disk, so that it is still there the next time the game starts, and shows it on the menu.
The record#
Both the menu and the game need the best score, so it gets two small functions of its own, in
two new files at the top of src/, next to main.cpp:
#pragma once
// The best score, kept on disk from one session to the next.
// The most coins collected in one game, or 0 before the first game ends.
int best_score();
// Keeps `coins` as the best score if it beats it, and says whether it did.
bool keep_if_best(int coins);#include "record.h"
#include <rmp/save.h>
#include <string_view>
namespace {
// The slot: the save file's name, without a folder and without an extension.
constexpr std::string_view SLOT = "record";
} // namespace
int best_score() {
rmp::Value saved;
rmp::save::read(SLOT, saved);
// No save yet, or one without this key: the 0 is what reads then.
return saved["coins"].as_int(0);
}
bool keep_if_best(int coins) {
if (coins <= best_score()) return false;
rmp::Value record;
record["coins"] = coins;
rmp::save::write(SLOT, record);
return true;
}A
save is an rmp::Value: a tree of the shapes JSON has,
which are nothing (JSON's null), true or false, numbers, strings, lists and keyed
objects. So a save can grow into something with structure without changing how it is written. Assigning to a key creates it:
record["coins"] = coins.
rmp::save::write() writes it to a
slot, a file name without a folder or an extension. The file is written beside the old one
first and replaces it only once it is complete, so a game that crashes, or a battery that dies, in
the middle of a save leaves the previous save as it was.
rmp::save::read() fills the
rmp::Value it is given, or leaves it exactly as it was when it cannot: the first time
the game runs there is no save at all. Every read of a value says what to give back when the key
is not there, so saved["coins"].as_int(0) is 0 on the first run and the
record from then on, with no special case. Reading creates nothing, and a key a later version of
the game adds simply reads as its default in an older save.
read() also says why it did not fill the value, when that matters, and here it
does not: no save and a damaged save both mean "no record yet". The
Saving chapter of the manual shows how to tell them
apart.
Keeping it#
The game keeps the record when the rabbit is caught, and tells the game over screen whether it was beaten. Replace the game scene's code; its header does not change:
#include "game.h"
#include "../objects/layers.h"
#include "../objects/player.h"
#include "../record.h"
#include "game_over.h"
#include "pause.h"
#include <rmp/assets.h>
#include <rmp/audio.h>
#include <rmp/behavior.h>
#include <rmp/input.h>
#include <rmp/random.h>
#include <rmp/ui.h>
#include <string>
namespace {
// The arena is the design resolution: [window] width and height in the .toml.
constexpr Rectangle ARENA{ 0, 0, RMP_WINDOW_WIDTH, RMP_WINDOW_HEIGHT };
constexpr float SECONDS_PER_BAT = 4;
} // namespace
void GameScene::_ready() {
background = Color{ 52, 92, 60, 255 }; // grass
// P, Escape, or the gamepad's Start button.
rmp::input::action("pause", KEY_P, KEY_ESCAPE, GAMEPAD_BUTTON_MIDDLE_RIGHT);
auto &player = spawn<Player>({
.position = { ARENA.width / 2, ARENA.height / 2 },
.edges = rmp::Edge::CLAMP,
.bounds = ARENA,
});
player.add<rmp::behavior::Health>({
.hp = 3,
.destroy_on_death = false, // it stays on screen, under the game over
.on_death = [this](rmp::Object &) { caught(); },
.on_damage = [](rmp::Object &, int) { rmp::audio::play("hurt"); },
.hurt_by = layer::BAT,
});
_player = player.handle();
spawn_coin();
}
void GameScene::_update(float delta) {
if (rmp::input::just_pressed("pause")) rmp::Scene::push<PauseScene>();
_next_bat -= delta;
if (_next_bat <= 0) {
spawn_bat();
_next_bat = SECONDS_PER_BAT;
}
}
void GameScene::_draw() {
const int lives = _player->get<rmp::behavior::Health>()->hp;
rmp::ui::begin({ .placement = rmp::ui::Align::TOP_LEFT });
rmp::ui::row({ .gap = 24 }, [&] {
rmp::ui::text("Coins " + std::to_string(_coins));
rmp::ui::text("Lives " + std::to_string(lives));
#if defined(PLATFORM_ANDROID) || defined(PLATFORM_IOS)
// A phone has no key to pause with.
if (rmp::ui::button("Pause", { .style = rmp::ui::Variant::GHOST })) {
rmp::Scene::push<PauseScene>();
}
#endif
});
rmp::ui::end();
}
void GameScene::spawn_coin() {
// Anywhere in the arena, clear of its edges and of the score at the top.
const Vector2 at{ rmp::random::range(40.0f, ARENA.width - 40),
rmp::random::range(80.0f, ARENA.height - 40) };
auto &coin = spawn({ .position = at, .scale = { 2, 2 } });
coin.sprite.sheet = rmp::assets::load_sheet("coin.aseprite");
coin.sprite.play("spin");
coin.collision_layer = layer::COIN;
coin.collision_mask = layer::PLAYER;
coin.on_collision([this](rmp::Object &self, rmp::Object &) {
self.destroy();
++_coins;
rmp::audio::play("coin");
spawn_coin();
});
}
void GameScene::spawn_bat() {
// From just outside the arena, above it or below it.
const Vector2 at{ rmp::random::range(0.0f, ARENA.width),
rmp::random::chance(0.5f) ? -40.0f : ARENA.height + 40 };
auto &bat = spawn({ .position = at, .scale = { 2, 2 } });
bat.sprite.sheet = rmp::assets::load_sheet("bat.aseprite");
bat.sprite.play("fly");
bat.collision_layer = layer::BAT;
bat.collision_mask = layer::PLAYER;
// Each one a little faster or slower, so that they do not fly as one.
bat.add<rmp::behavior::Follow>({
.target = _player,
.speed = rmp::random::range(70.0f, 120.0f),
});
}
void GameScene::caught() {
const bool record = keep_if_best(_coins);
rmp::Scene::push<GameOverScene>(_coins, record);
}The game over scene takes a second argument, and says so when there is a new best:
#pragma once
// Pushed on top of the game when the rabbit is caught. The game stays on
// screen, frozen, underneath.
#include <rmp/scene.h>
class GameOverScene : public rmp::Scene {
public:
GameOverScene(int coins, bool record) : _coins(coins), _record(record) {}
void _draw() override;
private:
int _coins;
bool _record;
};#include "game_over.h"
#include "game.h"
#include "main_menu.h"
#include <rmp/ui.h>
#include <string>
void GameOverScene::_draw() {
// A veil over the game, which has already drawn this frame.
DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), Color{ 0, 0, 0, 150 });
rmp::ui::begin();
rmp::ui::text("Caught!", { .size = rmp::ui::Size::LARGE });
rmp::ui::text(std::to_string(_coins) + " coins");
if (_record) {
rmp::ui::text("A new best!", { .color = rmp::ui::ColorRole::PRIMARY });
}
if (rmp::ui::button("Play again", { .style = rmp::ui::Variant::PRIMARY })) {
rmp::Scene::change<GameScene>();
}
if (rmp::ui::button("Menu")) rmp::Scene::change<MainMenuScene>();
rmp::ui::end();
}Showing it#
The menu shows the record under the title, once there is one:
#pragma once
// The title screen: the game's name, the best score, Play and Quit.
#include <rmp/scene.h>
class MainMenuScene : public rmp::Scene {
public:
void _ready() override;
void _draw() override;
private:
int _best = 0; // read once, when the menu opens
};#include "main_menu.h"
#include "../record.h"
#include "game.h"
#include <rmp/app.h>
#include <rmp/audio.h>
#include <rmp/ui.h>
#include <string>
void MainMenuScene::_ready() {
_best = best_score();
// Already playing when the menu comes back after a game: then it carries on.
rmp::audio::music("music");
}
void MainMenuScene::_draw() {
rmp::ui::begin();
rmp::ui::text(RMP_WINDOW_TITLE, { .size = rmp::ui::Size::LARGE });
if (_best > 0) {
rmp::ui::text("Best: " + std::to_string(_best) + " coins",
{ .color = rmp::ui::ColorRole::MUTED });
}
if (rmp::ui::button("Play", { .style = rmp::ui::Variant::PRIMARY })) {
rmp::Scene::change<GameScene>();
}
#if !defined(PLATFORM_IOS)
if (rmp::ui::button("Quit")) rmp::app::quit();
#endif
rmp::ui::end();
}The menu reads the record once, in _ready(), and keeps it in
_best, rather than reading a file sixty times a second in _draw(). The
menu is a new scene every time a game ends and the player goes back to it, so it always shows the
record as it is now.
Where it goes#
The slot record is a file called record.save, in a folder named
after [project] name, where each platform keeps an application's data:
| Platform | Folder |
|---|---|
| Linux and the BSDs | ~/.local/share/my_game, or my_game in $XDG_DATA_HOME when that is set |
| Windows | %APPDATA%\my_game |
| macOS | ~/Library/Application Support/my_game |
| Android | the app's internal storage |
| iOS | the app's Application Support folder |
| Web | the browser's own storage, IndexedDB, which survives a reload |
rmp::save::directory() says which folder it
is on the machine the game is running on. [save] portable = true in the
.toml puts saves in a saves folder next to the game's executable instead,
on Windows, Linux and FreeBSD, which is what a game handed out as a zip file wants. NetBSD and
OpenBSD cannot say where the executable is, so there the saves stay in the folder above.
The file is a line of header and then the JSON, so anyone can read it in a text editor, and
the framework notices if they change it: every save carries a checksum. [save] encrypt = true also seals it, which stops a
player from simply typing in a better score, but the key is inside the game, so it stops the
curious and not the determined.
Run it#
rmp runGather a coin or two and get caught: the game over screen says "A new best!", and back on the menu the record is under the title. Close the game and start it again, and the record is still there.