PheromonesManager.py 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from intelligine.core.exceptions import BestPheromoneHere
  2. from intelligine.cst import PHEROMON_INFOS
  3. from intelligine.core.exceptions import NoPheromone
  4. class PheromonesManager():
  5. def __init__(self, context):
  6. self._context = context
  7. def get_pheromones(self, position, prepare=[]):
  8. point_pheromones = self._context.metas.value.get(PHEROMON_INFOS,
  9. position,
  10. allow_empty=True,
  11. empty_value={})
  12. current_check = point_pheromones
  13. for prepare_key in prepare:
  14. if prepare_key not in current_check:
  15. current_check[prepare_key] = {}
  16. current_check = current_check[prepare_key]
  17. return point_pheromones
  18. def set_pheromones(self, position, pheromones):
  19. self._context.metas.value.set(PHEROMON_INFOS, position, pheromones)
  20. def get_info(self, position, address, allow_empty=False, empty_value=None):
  21. pheromones = self.get_pheromones(position, address[:-1])
  22. pheromone = pheromones
  23. for key in address[:-1]:
  24. pheromone = pheromone[key]
  25. if address[-1] not in pheromone:
  26. if allow_empty:
  27. pheromone[address[-1]] = empty_value
  28. else:
  29. raise KeyError()
  30. return pheromone[address[-1]]
  31. def increment(self, position, address, distance, increment_value=1):
  32. pheromones = self.get_pheromones(position, address[:-1])
  33. pheromone = pheromones
  34. for key in address[:-1]:
  35. pheromone = pheromone[key]
  36. if address[-1] not in pheromone:
  37. pheromone[address[-1]] = (distance, 0)
  38. # On se retrouve avec un {} dans pheromone[address[-1]]. A cause de la recherche de pheromone avant (et main process)
  39. if not pheromone[address[-1]]:
  40. pheromone[address[-1]] = (distance, 0)
  41. pheromone_distance = pheromone[address[-1]][0]
  42. pheromone_intensity = pheromone[address[-1]][1]
  43. pheromone_intensity += increment_value
  44. if distance < pheromone_distance:
  45. pheromone_distance = distance
  46. pheromone[address[-1]] = (pheromone_distance, pheromone_intensity)
  47. self.set_pheromones(position, pheromones)
  48. if distance > pheromone_distance:
  49. raise BestPheromoneHere(pheromone_distance)