daily_spawn.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435
  1. """Daily spawn selection, independent of global random state and call order."""
  2. from datetime import date, datetime, timedelta, timezone
  3. import hashlib
  4. import json
  5. def daily_spawn_date(server=False):
  6. if server:
  7. return datetime.now(timezone(timedelta(hours=8))).date()
  8. return date.today()
  9. def parse_daily_spawn(params):
  10. if not isinstance(params, dict):
  11. raise ValueError('DailyRandomPointSpawn requires dictionary params')
  12. candidates = params.get('candidates')
  13. if (not isinstance(candidates, list) or not candidates
  14. or any(not isinstance(name, str) or not name.strip() for name in candidates)):
  15. raise ValueError('candidates must be a nonempty list of NPC names')
  16. point = params.get('point')
  17. if (not isinstance(point, (list, tuple)) or len(point) != 2
  18. or any(type(value) is not int or value < 0 for value in point)):
  19. raise ValueError('point must contain two nonnegative integer grid coordinates')
  20. key = params.get('seed_key', '')
  21. if not isinstance(key, str):
  22. raise ValueError('seed_key must be a string')
  23. return tuple(candidates), tuple(point), key
  24. def daily_spawn_choice(params, map_name, day):
  25. candidates, point, key = parse_daily_spawn(params)
  26. payload = json.dumps([day.isoformat(), str(map_name), point, key],
  27. ensure_ascii=True, separators=(',', ':')).encode('ascii')
  28. index = int.from_bytes(hashlib.sha256(payload).digest(), 'big') % len(candidates)
  29. return candidates[index]