| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- #pragma once
- #include "common.h"
- #if PK_MODULE_RANDOM
- #include <random>
- #include "cffi.h"
- #include "_generated.h"
- namespace pkpy{
- struct Random{
- PY_CLASS(Random, random, Random)
- std::mt19937 gen;
- Random(){
- gen.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
- }
- static void _register(VM* vm, PyObject* mod, PyObject* type){
- vm->bind_default_constructor<Random>(type);
- vm->bind_method<1>(type, "seed", [](VM* vm, ArgsView args) {
- Random& self = _CAST(Random&, args[0]);
- self.gen.seed(CAST(i64, args[1]));
- return vm->None;
- });
- vm->bind_method<2>(type, "randint", [](VM* vm, ArgsView args) {
- Random& self = _CAST(Random&, args[0]);
- i64 a = CAST(i64, args[1]);
- i64 b = CAST(i64, args[2]);
- std::uniform_int_distribution<i64> dis(a, b);
- return VAR(dis(self.gen));
- });
- vm->bind_method<0>(type, "random", [](VM* vm, ArgsView args) {
- Random& self = _CAST(Random&, args[0]);
- std::uniform_real_distribution<f64> dis(0.0, 1.0);
- return VAR(dis(self.gen));
- });
- vm->bind_method<2>(type, "uniform", [](VM* vm, ArgsView args) {
- Random& self = _CAST(Random&, args[0]);
- f64 a = CAST(f64, args[1]);
- f64 b = CAST(f64, args[2]);
- std::uniform_real_distribution<f64> dis(a, b);
- return VAR(dis(self.gen));
- });
- }
- };
- inline void add_module_random(VM* vm){
- PyObject* mod = vm->new_module("random");
- Random::register_class(vm, mod);
- CodeObject_ code = vm->compile(kPythonLibs["random"], "random.py", EXEC_MODE);
- vm->_exec(code, mod);
- }
- } // namespace pkpy
- #else
- ADD_MODULE_PLACEHOLDER(random)
- #endif
|