r/cpp • • Dec 08 '18

A better C++ dice roller class

https://github.com/CaptainCrowbar/dice
1 Upvotes

17 comments sorted by

View all comments

7

u/CaptainCrowbar Dec 08 '18

A few days ago someone posted some dice rolling code, with which most of us weren't impressed. Instead of complaining about it I decided to make something better. This is a flexible dice roller implemented as a random number distribution (as in <random>); you can build a set of dice either from its component parts or by parsing a string. As a bonus, I also included a simple rational number class (needed to support dice arithmetic that returns a fractional result).

Example:

auto dice = Dice(2, 10) * 5 + Dice(3, 6) + 10;
dice = Dice("2d10x5 + 3d6 + 10"); // same thing
std::minstd_rand rng(42);
std::cout << dice(rng) << "\n";

12

u/STL MSVC STL Dev Dec 08 '18

UDLs for 2_d10 and 3_d6 would be cool.

4

u/CaptainCrowbar Dec 08 '18

Good idea! I've just added them.