random.cpp 1.6 KB

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