resource.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import random
  2. from decimal import Decimal, getcontext
  3. def generate_resources():
  4. # prepare the resources for the round
  5. # r[0] = name, r[1] = chance of occurrence, rounded to 2 sig digits]
  6. resources_list = [
  7. ['resource a', round(Decimal(0.1), 2)],
  8. ['resource b', round(Decimal(0.1), 2)],
  9. ['resource c', round(Decimal(0.2), 2)]
  10. ]
  11. resources = [ {'name': r[0], 'freq': r[1], 'lower': None, 'upper':
  12. None } for r in resources_list ]
  13. # set up the resources w/ probability distribtions, based on frequencies
  14. # these are non-overlapping windows, used to determine, w/ a random
  15. # number, which reso is on which square
  16. resource_freq_assign(resources, resources_list)
  17. return resources
  18. # setup resource frequency distribution
  19. def resource_freq_assign(resources, resources_list):
  20. for reso in resources_list:
  21. lower = 0
  22. index = resources_list.index(reso)
  23. if index == 0:
  24. for r in resources:
  25. if r['name'] == reso[0]:
  26. r['lower'] = round(Decimal(0), 2)
  27. r['upper'] = reso[1]
  28. else:
  29. for sub_reso in resources_list[0:index]:
  30. lower += sub_reso[1]
  31. for r in resources:
  32. if r['name'] == reso[0]:
  33. r['lower'] = lower
  34. r['upper'] = lower + r['freq']
  35. # determine which reso is on each square
  36. def select_resource(resources):
  37. n = random.random()
  38. for resource in resources:
  39. if n > resource['lower'] and n <= resource['upper']:
  40. return resource
  41. return None