middleware.py 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. import cocos
  45. return cocos.sprite.Sprite(os.path.join(
  46. self.map_dir_path,
  47. 'background.png',
  48. ))
  49. def get_interior_sprite(self) -> 'cocos.sprite.Sprite':
  50. # TODO: Extract it from tmx
  51. import cocos
  52. return cocos.sprite.Sprite(os.path.join(
  53. self.map_dir_path,
  54. 'background_interiors.png',
  55. ))
  56. def get_ground_layer(self) -> 'cocos.tiles.RectMapLayer':
  57. assert self.tmx
  58. return self.tmx['ground']
  59. def get_top_layer(self) -> 'cocos.tiles.RectMapLayer':
  60. assert self.tmx
  61. return self.tmx['top']
  62. def get_world_height(self) -> int:
  63. return len(self.tmx['ground'].cells[0])
  64. def get_world_width(self) -> int:
  65. return len(self.tmx['ground'].cells)
  66. def get_cell_height(self) -> int:
  67. return self.tmx['ground'].cells[0][0].size[1]
  68. def get_cell_width(self) -> int:
  69. return self.tmx['ground'].cells[0][0].size[0]