ge211
ge211_random.h
1 #pragma once
2 
3 #include "ge211_forward.h"
4 #include <cstdint>
5 #include <random>
6 #include <type_traits>
7 
8 namespace ge211 {
9 
10 namespace detail {
11 
12 template <class T, class Enable = void>
13 struct Between
14 {
15  static_assert(
16  std::is_integral<T>::value || std::is_floating_point<T>::value,
17  "Random::between: only works on built-in numeric types"
18  );
19 };
20 
21 template <class T, class Enable = void>
22 struct Up_to {
23  static_assert(
24  std::is_integral<T>::value || std::is_floating_point<T>::value,
25  "Random::up_to: only works on built-in numeric types"
26  );
27 };
28 
29 template <class T>
30 struct Between<T, std::enable_if_t<std::is_integral<T>::value>>
31  : std::uniform_int_distribution<T>
32 {
33  using std::uniform_int_distribution<T>::uniform_int_distribution;
34 };
35 
36 template <class T>
37 struct Between<T, std::enable_if_t<std::is_floating_point<T>::value>>
38  : std::uniform_real_distribution<T>
39 {
40  using std::uniform_real_distribution<T>::uniform_real_distribution;
41 };
42 
43 template <class T>
44 struct Up_to<T, std::enable_if_t<std::is_integral<T>::value>>
45  : Between<T>
46 {
47  explicit Up_to(T max) : Between<T>{0, max - 1}
48  { }
49 };
50 
51 template <class T>
52 struct Up_to<T, std::enable_if_t<std::is_floating_point<T>::value>>
53  : Between<T>
54 {
55  explicit Up_to(T max) : Between<T>{0, max}
56  { }
57 };
58 
59 } // end namespace detail
60 
63 class Random
64 {
65 public:
76  template <class T>
77  T up_to(T max)
78  {
79  return detail::Up_to<T>{max}(generator_);
80  }
81 
94  template <class T>
95  T between(T min, T max)
96  {
97  return detail::Between<T>{min, max}(generator_);
98  }
99 
102  bool random_bool(double ptrue = 0.5);
103 
104 private:
105  // Creator:
106  friend Abstract_game;
107 
108  Random();
109 
110  Random(Random &) = delete;
111  Random(Random &&) = delete;
112  Random& operator=(Random &) = delete;
113  Random& operator=(Random &&) = delete;
114 
115  std::mt19937_64 generator_;
116 };
117 
118 }
T up_to(T max)
Returns a random T between 0 (inclusive) and max (exclusive).
Definition: ge211_random.h:77
This is the abstract base class for deriving games.
Definition: ge211_base.h:94
The game engine namespace.
Definition: ge211.h:17
bool random_bool(double ptrue=0.5)
Returns a random bool that is true with probability ptrue.
A pseudo-random number generator.
Definition: ge211_random.h:63
T between(T min, T max)
Returns a random T between min and max.
Definition: ge211_random.h:95