Roll a die in your game
This adds one action to the starter project: Space rolls a six-sided die and the greeting shows the roll and its points. A six scores ten points; every other roll scores its own number. The state decides when to roll. A small rule decides what the roll means, and its tests supply numbers directly.
This uses the Random API shipped in v0.3.0 and available in current development. It needs no newer engine API or move of Random into the rules library. Start with an unchanged starter, or your game after Make a first change. Add a rule and a test explains the file and build-list steps in more detail; it does not need to be completed first. Allow about 15 minutes.
All commands below run in an x64 Native Tools Command Prompt, in your project:
cd /d C:\dev\mygameAdd the rule and its tests
Section titled “Add the rule and its tests”-
Make the rule’s two files. Open each file, paste its complete contents below, then save and close Notepad:
Terminal window if not exist game\rules\dice.h type nul > game\rules\dice.hnotepad game\rules\dice.hgame\rules\dice.h #pragma once// A six earns a bonus. Other rolls score their own number.// Throws invalid_argument for a value outside a six-sided die's range.int points_for_roll(int roll);Terminal window if not exist game\rules\dice.cpp type nul > game\rules\dice.cppnotepad game\rules\dice.cppgame\rules\dice.cpp #include "game/rules/dice.h"#include <stdexcept>int points_for_roll(int roll){if (roll < 1 || roll > 6){throw std::invalid_argument("points_for_roll: roll must be from 1 to 6");}return roll == 6 ? 10 : roll;}This rule takes an
int, a whole number, and returns another. It does not read the keyboard, a clock or Random, so testing it needs none of those things. The last line’s? :means “if the roll is six, return ten; otherwise return the roll”.throwreports a mistake for a number outside the die’s range. -
Make the tests. Open the new file and paste its complete contents:
Terminal window if not exist game\tests\dice_tests.cpp type nul > game\tests\dice_tests.cppnotepad game\tests\dice_tests.cppgame\tests\dice_tests.cpp #include <doctest/doctest.h>#include "game/rules/dice.h"#include <stdexcept>TEST_CASE("ordinary rolls score their own number"){CHECK(points_for_roll(1) == 1);CHECK(points_for_roll(3) == 3);CHECK(points_for_roll(5) == 5);}TEST_CASE("a six scores ten points"){CHECK(points_for_roll(6) == 10);}TEST_CASE("a roll outside the die's range is a mistake"){CHECK_THROWS_AS(points_for_roll(0), std::invalid_argument);CHECK_THROWS_AS(points_for_roll(7), std::invalid_argument);}Leave out
DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN:motion_tests.cppalready supplies the test program’smain. Each test always receives the same values. A random roll in a test could miss the six and never check the bonus. -
List both source files once. Open
game\CMakeLists.txt. Search forrules/motion.cppand addrules/dice.cppafter it, inMyGameRules:add_library(MyGameRules STATICrules/motion.cpprules/dice.cpp)Search for
tests/motion_tests.cppand addtests/dice_tests.cppafter it:add_executable(MyGameTeststests/motion_tests.cpptests/dice_tests.cpp)Save and close Notepad. Do not change
MyGameRules’ libraries: it still linksLabradorMathandlabrador_settings. Random is inLabradorEngine, which the game’s states already link. Keeping it out of this rule preserves that boundary. -
Give the state its own Random. Open
game\states\hello_state.h. Add this include beside its otherengine/core/includes:#include "engine/core/random.h"Search for
Motion motion_;and add one member after it:12345uis the seed, the number that chooses the starting point in the sequence. Theumarks an unsigned number. Keep this member between updates: making a new Random insideupdate()would restart the sequence on every step. -
Roll on a new Space press. Open
game\states\hello_state.cpp. Search forgame/states/confirm_state.hand add this include above it:#include "game/rules/dice.h"Search for
bool quit_requested = keyboard.pressed(Key::escape);. Paste the following block above that line, leaving an empty line after it:{const int roll = this->random_.uniform_int(1, 6);const int points = points_for_roll(roll);this->greeting_->set_text(L"Roll " + std::to_wstring(roll) +L". Points: " + std::to_wstring(points) + L".");}uniform_int(1, 6)includes both ends. The state draws one roll and hands the plain number to the rule.pressed, rather thanheld, rolls once per press; holding Space does not spend another draw every step.std::to_wstringmakes display text from each number, and the file already includes<string>. Save and close Notepad. -
Build, test and play. Quit the game if it is open, then run:
Terminal window cmake --build --preset x64-debug && ctest --preset x64-debug && out\build\x64-debug\game\MyGame.exeCMake runs again because its source lists changed.
MyGameTestsandMyGameSmokeTestsshould both pass. The rules program gains three test cases and six checks; its total depends on the starter version and any earlier guides you completed. If a build or test fails, the&&line stops before opening the game: use Read a build error.Click the game, press Space, release it, and press it again. The greeting now reports the roll and points. With
12345u, the first four presses give:Press Roll Points 1 2 2 2 2 2 3 1 1 4 6 10 Restarting the game with the same seed repeats the sequence. Arrows still move the greeting; Escape still asks to quit.
The same seed is only part of reproducing a game
Section titled “The same seed is only part of reproducing a game”The same seed and the same calls in the same order give the same Random results on
Windows and in the browser. Adding a draw for an effect before the die changes the die’s
next result. Creating a fresh HelloState starts this member at 12345u again; covering
and resuming the existing state keeps its position. There is no hidden global stream.
The C++ standard specifies its random engines, but does not prescribe the algorithms of
std::uniform_int_distribution and std::uniform_real_distribution. They can map the same
engine output differently in MSVC’s library and the browser’s libc++. Labrador’s
Random defines its mapping too, and its engine tests pin
the results across native and wasm builds. uniform_int may reject a draw to avoid bias;
one call need not consume exactly one underlying number.
This is predictable game randomness, not a cryptographic generator. Neither this guide nor the seed defines a replay file format or promises that a whole game with different inputs will repeat.
Choose a changing seed in game code
Section titled “Choose a changing seed in game code”For a different start on each launch, the game may choose its seed from a clock. Add
#include <chrono> and #include <cstdint> to hello_state.cpp’s standard includes.
Replace its constructor with:
app_(app), random_(static_cast<std::uint32_t>( std::chrono::system_clock::now().time_since_epoch().count())){}This overrides the member’s fixed seed when the state is constructed; do not do it in
update(). The clock reading and conversion are
the game’s choice. Clock-derived seeds can repeat and are not a uniqueness guarantee.
Keep a fixed seed while investigating a result, or record the chosen seed yourself.
In the browser build
Section titled “In the browser build”After Build for the browser has installed and configured its
tools, use that guide’s prompt with emsdk_env.bat run for this session. The same files
build without a second implementation:
cmake --preset wasm-debug && cmake --build --preset wasm-debug && ctest --preset wasm-debugMyGameTests runs under Node, with no browser or Random needed by the rule. Open the
game’s page using that guide, click the canvas and press Space. With the fixed seed, the
roll sequence matches Windows. A new page instance constructs a new state and starts it
again. The clock-seeded variant deliberately has no fixed sequence to compare.
What was checked
Section titled “What was checked”On 2026-11-17 these edits were applied to fresh copies of the v0.3.0 starter ZIP and the
development starter. Both the fixed-seed and clock-seeded versions built and passed the
native rules/smoke tests and the browser build’s rules tests under Node. Headless Chrome
ran each page, pressed Space four times and quit through Escape and Enter without errors.
A separate native-null recording check drove the actual HelloState and matched the first
four displayed rolls and points above, including holding Space without another roll.
The verification record keeps the ZIP identities, command results and the scope of those checks. This is an independent guide verification; the three-guide compilation pilot has not been expanded.
Documentation for Labrador v0.4.0. Built from Labrador f525bc6 of 2026-11-17.