middleware.py 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # coding: utf-8
  2. import os
  3. import typing
  4. from synergine2.config import Config
  5. from synergine2.log import get_logger
  6. from synergine2_cocos2d.util import get_map_file_path_from_dir
  7. if typing.TYPE_CHECKING:
  8. import cocos
  9. class MapMiddleware(object):
  10. def __init__(
  11. self,
  12. config: Config,
  13. map_dir_path: str,
  14. ) -> None:
  15. self.config = config
  16. self.logger = get_logger(self.__class__.__name__, config)
  17. self.map_dir_path = map_dir_path
  18. self.tmx = None
  19. def get_map_file_path(self) -> str:
  20. return get_map_file_path_from_dir(self.map_dir_path)
  21. def init(self) -> None:
  22. # import cocos here for prevent test crash when no X server is
  23. # present
  24. import cocos
  25. map_file_path = self.get_map_file_path()
  26. self.tmx = cocos.tiles.load(map_file_path)
  27. def get_background_sprite(self) -> 'cocos.sprite.Sprite':
  28. raise NotImplementedError()
  29. def get_ground_layer(self) -> 'cocos.tiles.RectMapLayer':
  30. raise NotImplementedError()
  31. def get_top_layer(self) -> 'cocos.tiles.RectMapLayer':
  32. raise NotImplementedError()
  33. def get_world_height(self) -> int:
  34. raise NotImplementedError()
  35. def get_world_width(self) -> int:
  36. raise NotImplementedError()
  37. def get_cell_height(self) -> int:
  38. raise NotImplementedError()
  39. def get_cell_width(self) -> int:
  40. raise NotImplementedError()
  41. class TMXMiddleware(MapMiddleware):
  42. def get_background_sprite(self) -> 'cocos.sprite.Sprite':
  43. # TODO: Extract it from tmx
  44. return cocos.sprite.Sprite(os.path.join(
  45. self.map_dir_path,
  46. 'background.png',
  47. ))
  48. def get_interior_sprite(self) -> 'cocos.sprite.Sprite':
  49. # TODO: Extract it from tmx
  50. return cocos.sprite.Sprite(os.path.join(
  51. self.map_dir_path,
  52. 'background_interiors.png',
  53. ))
  54. def get_ground_layer(self) -> 'cocos.tiles.RectMapLayer':
  55. assert self.tmx
  56. return self.tmx['ground']
  57. def get_top_layer(self) -> 'cocos.tiles.RectMapLayer':
  58. assert self.tmx
  59. return self.tmx['top']
  60. def get_world_height(self) -> int:
  61. return len(self.tmx['ground'].cells[0])
  62. def get_world_width(self) -> int:
  63. return len(self.tmx['ground'].cells)
  64. def get_cell_height(self) -> int:
  65. return self.tmx['ground'].cells[0][0].size[1]
  66. def get_cell_width(self) -> int:
  67. return self.tmx['ground'].cells[0][0].size[0]