stash.py 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 TeamModel
  7. from opencombat.strategy.unit.stash import UnitStash
  8. from opencombat.util import get_text_xml_element
  9. from opencombat.xml import XmlValidator
  10. class TeamStash(object):
  11. def __init__(
  12. self,
  13. config: Config,
  14. teams_file_path: str,
  15. unit_stash: UnitStash,
  16. ) -> None:
  17. self._config = config
  18. self._teams = None # type: typing.List[TeamModel]
  19. self._unit_stash = unit_stash
  20. self.schema_file_path = self._config.get(
  21. 'global.teams_schema',
  22. 'opencombat/strategy/teams.xsd',
  23. )
  24. self._xml_validator = XmlValidator(
  25. config,
  26. self.schema_file_path,
  27. )
  28. self._root_element = self._xml_validator.validate_and_return(
  29. teams_file_path,
  30. )
  31. def _get_computed_teams(self) -> typing.List[TeamModel]:
  32. teams = []
  33. for team_element in self._root_element.findall('team'):
  34. team_element = typing.cast(Element, team_element)
  35. team_id = team_element.attrib['id']
  36. team_country = team_element.attrib['country']
  37. team_name = get_text_xml_element(team_element, 'name')
  38. team_units = []
  39. units_element = team_element.find('units')
  40. for unit_element in units_element.findall('unit'):
  41. unit_id = get_text_xml_element(unit_element, 'id')
  42. unit = self._unit_stash.get_unit(unit_id, team_country)
  43. team_units.append(unit)
  44. teams.append(
  45. TeamModel(
  46. id_=team_id,
  47. country=team_country,
  48. name=team_name,
  49. units=team_units
  50. )
  51. )
  52. return teams
  53. @property
  54. def teams(self) -> typing.List[TeamModel]:
  55. if self._teams is None:
  56. self._teams = self._get_computed_teams()
  57. return self._teams
  58. def get_team(
  59. self,
  60. team_id: str,
  61. team_country: str,
  62. ) -> TeamModel:
  63. for team in self.teams:
  64. if team.id == team_id and team.country == team_country:
  65. return team
  66. raise NotFoundException(
  67. 'No team matching with id "{}" and country "{}" in "{}"'.format(
  68. team_id,
  69. team_country,
  70. self.schema_file_path,
  71. )
  72. )