random.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #include "common.h"
  3. #if PK_MODULE_RANDOM
  4. #include <random>
  5. #include "cffi.h"
  6. #include "_generated.h"
  7. namespace pkpy{
  8. struct Random{
  9. PY_CLASS(Random, random, Random)
  10. std::mt19937 gen;
  11. Random(){
  12. gen.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
  13. }
  14. static void _register(VM* vm, PyObject* mod, PyObject* type){
  15. vm->bind_default_constructor<Random>(type);
  16. vm->bind_method<1>(type, "seed", [](VM* vm, ArgsView args) {
  17. Random& self = _CAST(Random&, args[0]);
  18. self.gen.seed(CAST(i64, args[1]));
  19. return vm->None;
  20. });
  21. vm->bind_method<2>(type, "randint", [](VM* vm, ArgsView args) {
  22. Random& self = _CAST(Random&, args[0]);
  23. i64 a = CAST(i64, args[1]);
  24. i64 b = CAST(i64, args[2]);
  25. std::uniform_int_distribution<i64> dis(a, b);
  26. return VAR(dis(self.gen));
  27. });
  28. vm->bind_method<0>(type, "random", [](VM* vm, ArgsView args) {
  29. Random& self = _CAST(Random&, args[0]);
  30. std::uniform_real_distribution<f64> dis(0.0, 1.0);
  31. return VAR(dis(self.gen));
  32. });
  33. vm->bind_method<2>(type, "uniform", [](VM* vm, ArgsView args) {
  34. Random& self = _CAST(Random&, args[0]);
  35. f64 a = CAST(f64, args[1]);
  36. f64 b = CAST(f64, args[2]);
  37. std::uniform_real_distribution<f64> dis(a, b);
  38. return VAR(dis(self.gen));
  39. });
  40. }
  41. };
  42. inline void add_module_random(VM* vm){
  43. PyObject* mod = vm->new_module("random");
  44. Random::register_class(vm, mod);
  45. CodeObject_ code = vm->compile(kPythonLibs["random"], "random.py", EXEC_MODE);
  46. vm->_exec(code, mod);
  47. }
  48. } // namespace pkpy
  49. #else
  50. ADD_MODULE_PLACEHOLDER(random)
  51. #endif