map_grids.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import operator
  2. import typing as t
  3. class SelectedGrids:
  4. def __init__(self, grids):
  5. self.grids = grids
  6. self.indexes: t.Dict[tuple, SelectedGrids] = {}
  7. def __iter__(self):
  8. return iter(self.grids)
  9. def __getitem__(self, item):
  10. if isinstance(item, int):
  11. return self.grids[item]
  12. else:
  13. return SelectedGrids(self.grids[item])
  14. def __contains__(self, item):
  15. return item in self.grids
  16. def __str__(self):
  17. # return str([str(grid) for grid in self])
  18. return '[' + ', '.join([str(grid) for grid in self]) + ']'
  19. def __len__(self):
  20. return len(self.grids)
  21. def __bool__(self):
  22. return self.count > 0
  23. # def __getattr__(self, item):
  24. # return [grid.__getattribute__(item) for grid in self.grids]
  25. @property
  26. def location(self):
  27. """
  28. Returns:
  29. list[tuple]:
  30. """
  31. return [grid.location for grid in self.grids]
  32. @property
  33. def cost(self):
  34. """
  35. Returns:
  36. list[int]:
  37. """
  38. return [grid.cost for grid in self.grids]
  39. @property
  40. def weight(self):
  41. """
  42. Returns:
  43. list[int]:
  44. """
  45. return [grid.weight for grid in self.grids]
  46. @property
  47. def count(self):
  48. """
  49. Returns:
  50. int:
  51. """
  52. return len(self.grids)
  53. def select(self, **kwargs):
  54. """
  55. Args:
  56. **kwargs: Attributes of Grid.
  57. Returns:
  58. SelectedGrids:
  59. """
  60. def matched(obj):
  61. flag = True
  62. for k, v in kwargs.items():
  63. obj_v = obj.__getattribute__(k)
  64. if type(obj_v) != type(v) or obj_v != v:
  65. flag = False
  66. return flag
  67. return SelectedGrids([grid for grid in self.grids if matched(grid)])
  68. def create_index(self, *attrs):
  69. indexes = {}
  70. # index_keys = [(grid.__getattribute__(attr) for attr in attrs) for grid in self.grids]
  71. for grid in self.grids:
  72. k = tuple(grid.__getattribute__(attr) for attr in attrs)
  73. try:
  74. indexes[k].append(grid)
  75. except KeyError:
  76. indexes[k] = [grid]
  77. indexes = {k: SelectedGrids(v) for k, v in indexes.items()}
  78. self.indexes = indexes
  79. return indexes
  80. def indexed_select(self, *values):
  81. return self.indexes.get(values, SelectedGrids([]))
  82. def left_join(self, right, on_attr, set_attr, default=None):
  83. """
  84. Args:
  85. right (SelectedGrids): Right table to join
  86. on_attr:
  87. set_attr:
  88. default:
  89. Returns:
  90. SelectedGrids:
  91. """
  92. right.create_index(*on_attr)
  93. for grid in self:
  94. attr_value = tuple([grid.__getattribute__(attr) for attr in on_attr])
  95. right_grid = right.indexed_select(*attr_value).first_or_none()
  96. if right_grid is not None:
  97. for attr in set_attr:
  98. grid.__setattr__(attr, right_grid.__getattribute__(attr))
  99. else:
  100. for attr in set_attr:
  101. grid.__setattr__(attr, default)
  102. return self
  103. def filter(self, func):
  104. """
  105. Filter grids by a function.
  106. Args:
  107. func (callable): Function should receive an grid as argument, and return a bool.
  108. Returns:
  109. SelectedGrids:
  110. """
  111. return SelectedGrids([grid for grid in self if func(grid)])
  112. def set(self, **kwargs):
  113. """
  114. Set attribute to each grid.
  115. Args:
  116. **kwargs:
  117. """
  118. for grid in self:
  119. for key, value in kwargs.items():
  120. grid.__setattr__(key, value)
  121. def get(self, attr):
  122. """
  123. Get an attribute from each grid.
  124. Args:
  125. attr: Attribute name.
  126. Returns:
  127. list:
  128. """
  129. return [grid.__getattribute__(attr) for grid in self.grids]
  130. def call(self, func, **kwargs):
  131. """
  132. Call a function in reach grid, and get results.
  133. Args:
  134. func (str): Function name to call.
  135. **kwargs:
  136. Returns:
  137. list:
  138. """
  139. return [grid.__getattribute__(func)(**kwargs) for grid in self]
  140. def first_or_none(self):
  141. """
  142. Returns:
  143. """
  144. try:
  145. return self.grids[0]
  146. except IndexError:
  147. return None
  148. def add(self, grids):
  149. """
  150. Args:
  151. grids(SelectedGrids):
  152. Returns:
  153. SelectedGrids:
  154. """
  155. return SelectedGrids(list(set(self.grids + grids.grids)))
  156. def add_by_eq(self, grids):
  157. """
  158. Another `add()` method, but de-duplicates with `__eq__` instead of `__hash__`.
  159. Args:
  160. grids(SelectedGrids):
  161. Returns:
  162. SelectedGrids:
  163. """
  164. new = []
  165. for grid in self.grids + grids.grids:
  166. if grid not in new:
  167. new.append(grid)
  168. return SelectedGrids(new)
  169. def intersect(self, grids):
  170. """
  171. Args:
  172. grids(SelectedGrids):
  173. Returns:
  174. SelectedGrids:
  175. """
  176. return SelectedGrids(list(set(self.grids).intersection(set(grids.grids))))
  177. def intersect_by_eq(self, grids):
  178. """
  179. Another `intersect()` method, but de-duplicates with `__eq__` instead of `__hash__`.
  180. Args:
  181. grids(SelectedGrids):
  182. Returns:
  183. SelectedGrids:
  184. """
  185. new = []
  186. for grid in self.grids:
  187. if grid in grids.grids:
  188. new.append(grid)
  189. return SelectedGrids(new)
  190. def delete(self, grids):
  191. """
  192. Args:
  193. grids(SelectedGrids):
  194. Returns:
  195. SelectedGrids:
  196. """
  197. g = [grid for grid in self.grids if grid not in grids]
  198. return SelectedGrids(g)
  199. def sort(self, *args):
  200. """
  201. Args:
  202. args (str): Attribute name to sort.
  203. Returns:
  204. SelectedGrids:
  205. """
  206. if not self:
  207. return self
  208. if len(args):
  209. grids = sorted(self.grids, key=operator.attrgetter(*args))
  210. return SelectedGrids(grids)
  211. else:
  212. return self
  213. def sort_by_camera_distance(self, camera):
  214. """
  215. Args:
  216. camera (tuple):
  217. Returns:
  218. SelectedGrids:
  219. """
  220. import numpy as np
  221. if not self:
  222. return self
  223. location = np.array(self.location)
  224. diff = np.sum(np.abs(location - camera), axis=1)
  225. # grids = [x for _, x in sorted(zip(diff, self.grids))]
  226. grids = tuple(np.array(self.grids)[np.argsort(diff)])
  227. return SelectedGrids(grids)
  228. def sort_by_clock_degree(self, center=(0, 0), start=(0, 1), clockwise=True):
  229. """
  230. Args:
  231. center (tuple): Origin point.
  232. start (tuple): Start coordinate, this point will be considered as theta=0.
  233. clockwise (bool): True for clockwise, false for counterclockwise.
  234. Returns:
  235. SelectedGrids:
  236. """
  237. import numpy as np
  238. if not self:
  239. return self
  240. vector = np.subtract(self.location, center)
  241. theta = np.arctan2(vector[:, 1], vector[:, 0]) / np.pi * 180
  242. vector = np.subtract(start, center)
  243. theta = theta - np.arctan2(vector[1], vector[0]) / np.pi * 180
  244. if not clockwise:
  245. theta = -theta
  246. theta[theta < 0] += 360
  247. grids = tuple(np.array(self.grids)[np.argsort(theta)])
  248. return SelectedGrids(grids)
  249. class RoadGrids:
  250. def __init__(self, grids):
  251. """
  252. Args:
  253. grids (list):
  254. """
  255. self.grids = []
  256. for grid in grids:
  257. if isinstance(grid, list):
  258. self.grids.append(SelectedGrids(grids=grid))
  259. else:
  260. self.grids.append(SelectedGrids(grids=[grid]))
  261. def __str__(self):
  262. return str(' - '.join([str(grid) for grid in self.grids]))
  263. def roadblocks(self):
  264. """
  265. Returns:
  266. SelectedGrids:
  267. """
  268. grids = []
  269. for block in self.grids:
  270. if block.count == block.select(is_enemy=True).count:
  271. grids += block.grids
  272. return SelectedGrids(grids)
  273. def potential_roadblocks(self):
  274. """
  275. Returns:
  276. SelectedGrids:
  277. """
  278. grids = []
  279. for block in self.grids:
  280. if any([grid.is_fleet for grid in block]):
  281. continue
  282. if any([grid.is_cleared for grid in block]):
  283. continue
  284. if block.count - block.select(is_enemy=True).count == 1:
  285. grids += block.select(is_enemy=True).grids
  286. return SelectedGrids(grids)
  287. def first_roadblocks(self):
  288. """
  289. Returns:
  290. SelectedGrids:
  291. """
  292. grids = []
  293. for block in self.grids:
  294. if any([grid.is_fleet for grid in block]):
  295. continue
  296. if any([grid.is_cleared for grid in block]):
  297. continue
  298. if block.select(is_enemy=True).count >= 1:
  299. grids += block.select(is_enemy=True).grids
  300. return SelectedGrids(grids)
  301. def combine(self, road):
  302. """
  303. Args:
  304. road (RoadGrids):
  305. Returns:
  306. RoadGrids:
  307. """
  308. out = RoadGrids([])
  309. for select_1 in self.grids:
  310. for select_2 in road.grids:
  311. select = select_1.add(select_2)
  312. out.grids.append(select)
  313. return out