middleware.py 2.3KB

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