Skip to content

Commit 972e408

Browse files
authored
Add util/random, demo in app (#5)
1 parent 279c008 commit 972e408

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,5 @@ file(GLOB_RECURSE sources LIST_DIRECTORIES false "src/*.[hc]pp")
2323
target_sources(${PROJECT_NAME} PRIVATE
2424
${sources}
2525
)
26+
27+
target_precompile_headers(${PROJECT_NAME} REUSE_FROM le2d)

src/app.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include <game.hpp>
55
#include <klib/visitor.hpp>
66
#include <log.hpp>
7+
#include <util/random.hpp>
78

89
namespace miracle {
910
namespace {
@@ -18,6 +19,7 @@ App::App() : m_context(context_ci), m_data_loader(le::FileDataLoader::upfind("as
1819
// test code, remove later.
1920
auto json = dj::Json{};
2021
if (m_services.get<le::IDataLoader>().load_json(json, "test_file.json")) { log.info("loaded JSON: {}", json); }
22+
log.debug("random_range(1, 100): {}", util::random_range(1, 100));
2123
}
2224

2325
void App::run() {

src/util/random.hpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#pragma once
2+
#include <klib/assert.hpp>
3+
#include <klib/concepts.hpp>
4+
#include <random>
5+
6+
namespace miracle::util {
7+
/// \brief Wrapper that reuses the same random engine for all calls.
8+
class Random {
9+
public:
10+
template <klib::NumberT Type>
11+
[[nodiscard]] static auto in_range(Type const min, Type const max) -> Type {
12+
if constexpr (std::integral<Type>) {
13+
auto dist = std::uniform_int_distribution<Type>{min, max};
14+
return dist(m_engine);
15+
} else {
16+
auto dist = std::uniform_real_distribution<Type>{min, max};
17+
return dist(m_engine);
18+
}
19+
}
20+
21+
private:
22+
inline static std::default_random_engine m_engine{std::random_device{}()};
23+
};
24+
25+
/// \returns Random value in the range [min, max].
26+
template <klib::NumberT Type>
27+
[[nodiscard]] auto random_range(Type const min, Type const max) -> Type {
28+
return Random::in_range(min, max);
29+
}
30+
31+
/// \returns Random index in the range [0, size - 1].
32+
/// \pre size must be greater than 0.
33+
[[nodiscard]] inline auto random_index(std::size_t const size) -> std::size_t {
34+
KLIB_ASSERT(size > 0);
35+
return Random::in_range(0uz, size - 1);
36+
}
37+
} // namespace miracle::util

0 commit comments

Comments
 (0)