physics.py 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # coding: utf-8
  2. import typing
  3. import tmx
  4. from dijkstar import Graph
  5. from dijkstar import find_path
  6. from synergine2.config import Config
  7. from synergine2_xyz.map import TMXMap
  8. from synergine2_xyz.tmx_utils import get_layer_by_name
  9. class Physics(object):
  10. def __init__(
  11. self,
  12. config: Config,
  13. ) -> None:
  14. self.config = config
  15. self.graph = Graph()
  16. def load(self) -> None:
  17. raise NotImplementedError()
  18. def position_to_key(self, position: typing.Tuple[int, int]) -> str:
  19. return '{}.{}'.format(*position)
  20. def found_path(
  21. self,
  22. start: typing.Tuple[int, int],
  23. end: typing.Tuple[int, int],
  24. ) -> typing.List[typing.Tuple[int, int]]:
  25. start_key = self.position_to_key(start)
  26. end_key = self.position_to_key(end)
  27. found_path = find_path(self.graph, start_key, end_key)
  28. regular_path = []
  29. for position in found_path[0][1:]:
  30. x, y = map(int, position.split('.'))
  31. regular_path.append((x, y))
  32. return regular_path
  33. class TMXPhysics(Physics):
  34. def __init__(
  35. self,
  36. config: Config,
  37. map_file_path: str,
  38. ) -> None:
  39. super().__init__(config)
  40. self.map_file_path = map_file_path
  41. def load(self) -> None:
  42. self.load_graph_from_map(self.map_file_path)
  43. def load_graph_from_map(self, map_file_path: str) -> None:
  44. tmx_map = TMXMap(map_file_path)
  45. # TODO: tmx_map contient tout en cache, faire le dessous en exploitant tmx_map.
  46. for y in range(tmx_map.height):
  47. for x in range(tmx_map.width):
  48. position = self.position_to_key((x, y))
  49. neighbors = []
  50. for modifier_x, modifier_y in (
  51. (+1, +1),
  52. (+1, +0),
  53. (+1, -1),
  54. (+0, -1),
  55. (-1, -1),
  56. (-1, +0),
  57. (-1, -1),
  58. (+0, +1),
  59. ):
  60. try:
  61. neighbors.append('{}.{}'.format(x + modifier_x, y + modifier_y))
  62. except ValueError:
  63. pass
  64. for neighbor in neighbors:
  65. neighbor_x, neighbor_y = map(int, neighbor.split('.'))
  66. if neighbor_x > 69 or neighbor_x < 0:
  67. continue
  68. if neighbor_y > 69 or neighbor_y < 0:
  69. continue
  70. # TODO: Voir https://pypi.python.org/pypi/Dijkstar/2.2
  71. self.graph.add_edge(position, neighbor, 1)