stash.py 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # coding: utf-8
  2. import typing
  3. from _elementtree import Element
  4. from synergine2.config import Config
  5. from opencombat.exception import NotFoundException
  6. from opencombat.strategy.team.model import UnitModel
  7. from opencombat.util import get_text_xml_element
  8. from opencombat.util import get_class_from_string_path
  9. from opencombat.xml import XmlValidator
  10. class UnitStash(object):
  11. def __init__(
  12. self,
  13. config: Config,
  14. units_file_path: str,
  15. ) -> None:
  16. self._config = config
  17. self._units = None # type: typing.List[UnitModel]
  18. self.schema_file_path = self._config.get(
  19. 'global.teams_schema',
  20. 'opencombat/strategy/units.xsd',
  21. )
  22. self._xml_validator = XmlValidator(
  23. config,
  24. self.schema_file_path,
  25. )
  26. self._root_element = self._xml_validator.validate_and_return(
  27. units_file_path,
  28. )
  29. def _get_computed_units(self) -> typing.List[UnitModel]:
  30. units = []
  31. for unit_element in self._root_element.findall('unit'):
  32. unit_element = typing.cast(Element, unit_element)
  33. unit_id = unit_element.attrib['id']
  34. unit_country = unit_element.attrib['country']
  35. unit_name = get_text_xml_element(unit_element, 'name')
  36. unit_class_path = get_text_xml_element(unit_element, 'type')
  37. unit_class = get_class_from_string_path(
  38. self._config,
  39. unit_class_path,
  40. )
  41. units.append(
  42. UnitModel(
  43. id_=unit_id,
  44. name=unit_name,
  45. class_=unit_class,
  46. country=unit_country,
  47. )
  48. )
  49. return units
  50. @property
  51. def units(self) -> typing.List[UnitModel]:
  52. if self._units is None:
  53. self._units = self._get_computed_units()
  54. return self._units
  55. def get_unit(
  56. self,
  57. unit_id: str,
  58. unit_country: str,
  59. ) -> UnitModel:
  60. for unit in self.units:
  61. if unit.id == unit_id and unit.country == unit_country:
  62. return unit
  63. raise NotFoundException(
  64. 'No unit matching with id "{}" and country "{}" in "{}"'.format(
  65. unit_id,
  66. unit_country,
  67. self.schema_file_path,
  68. )
  69. )