player.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from passlib.hash import pbkdf2_sha256
  2. import time
  3. import json
  4. class Unit:
  5. def __init__(self, spec, level):
  6. self.spec = spec
  7. self.level = level
  8. class Job:
  9. def __init__(self, player, product):
  10. self.player = player
  11. self.product = product
  12. self.finish_time = time.time() + product['time']
  13. def check_finish(self):
  14. if time.time() > self.finish_time:
  15. if self.product['type'] == "building":
  16. self.player.buildings[self.product['name']] += 1
  17. elif self.product['type'] == "unit":
  18. self.player.units.append(Unit(self.product['spec'], self.product['level']))
  19. return True
  20. return False
  21. class Player:
  22. def __init__(self, username, password, config):
  23. self.username = username
  24. self.set_password(password)
  25. self.jobs = list()
  26. self.buildings = { key: 0 for key in config['building'] }
  27. self.units = list()
  28. self.resources = {
  29. 'gold': 100,
  30. 'wood': 100,
  31. 'stone': 0,
  32. }
  33. self.research = {
  34. 'footman': 1,
  35. 'archer': 0,
  36. }
  37. def login(self, ws):
  38. self.ws = ws
  39. def set_password(self, password):
  40. self.password = pbkdf2_sha256.encrypt(password, rounds=200000, salt_size=16)
  41. def check_password(self, password):
  42. return pbkdf2_sha256.verify(password, self.password)
  43. def add_job(self, product):
  44. self.jobs.append(Job(self, product))
  45. def update(self, config, tick_length):
  46. self.jobs = [job for job in self.jobs if not job.check_finish()]
  47. # Resource generation
  48. for building in self.buildings.keys():
  49. spec = config['building'][building]
  50. if 'production' in spec:
  51. self.resources[spec['production']] += spec['levels'][self.buildings[building] - 1]['rate'] * tick_length
  52. self.ws.send_json({
  53. 'username': self.username,
  54. 'jobs': [{ 'product': job.product, 'finish_time': job.finish_time } for job in self.jobs],
  55. 'buildings': self.buildings,
  56. 'units': [unit.__dict__ for unit in self.units],
  57. 'resources': self.resources,
  58. 'research': self.research,
  59. })