main.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. import heapq
  2. import sys
  3. import time
  4. debug = True
  5. t0 = time.time()
  6. def log(*msg):
  7. if debug:
  8. print("{} - ".format(str(time.time() - t0)[1:5]), *msg, file=sys.stderr, flush=True)
  9. def time_to(total, step):
  10. """ number of steps to reach total """
  11. return total // step + (1 if total % step > 0 else 0)
  12. class BaseClass:
  13. def __repr__(self):
  14. return f"<{self.__class__.__name__}: {self.__dict__}>"
  15. class Node(BaseClass):
  16. def __init__(self, pos, path=None):
  17. self.pos = pos
  18. self.path = path or []
  19. class PathNode(tuple):
  20. def __new__(cls, x, y, parent=None):
  21. n = tuple.__new__(cls, (x, y))
  22. n.parent = parent
  23. n.cost = 0
  24. return n
  25. def __repr__(self):
  26. return f"<{self[0]}, {self[1]}, c:{self.cost}>"
  27. class DiscoveryNode(tuple):
  28. def __new__(cls, x, y, cost=0, ancestors=None, matches=None):
  29. n = tuple.__new__(cls, (x, y))
  30. n.cost = cost
  31. n.ancestors = ancestors if ancestors is not None else []
  32. n.matches = matches if matches is not None else []
  33. return n
  34. def __repr__(self):
  35. return f"<{self[0]}, {self[1]}>"
  36. class Queue(BaseClass):
  37. def __init__(self):
  38. self.items = []
  39. def __bool__(self):
  40. return bool(self.items)
  41. def __repr__(self):
  42. return str(self.items)
  43. def values(self):
  44. return (v for _, v in self.items)
  45. def put(self, priority, item):
  46. while priority in [p for p, _ in self.items]:
  47. priority += 1
  48. heapq.heappush(self.items, (priority, item))
  49. def get(self):
  50. return heapq.heappop(self.items)[1]
  51. def get_items(self):
  52. return heapq.heappop(self.items)
  53. class ConversionStep:
  54. def __init__(self):
  55. self.pos = None
  56. self.candidates = []
  57. def __repr__(self):
  58. return f"<{self.pos}, c:{self.candidates}>"
  59. class ConversionPath:
  60. def __init__(self):
  61. self.steps = []
  62. def __repr__(self):
  63. return f"<{self.steps}>"
  64. @classmethod
  65. def make_from_discovery_node(cls, node):
  66. nodes = node.ancestors + [node]
  67. path = cls()
  68. found = []
  69. for node in nodes:
  70. step = ConversionStep()
  71. step.pos = tuple(node)
  72. for m in node.matches:
  73. if m in found:
  74. continue
  75. step.candidates.append(m)
  76. found.append(m)
  77. path.steps.append(step)
  78. return path
  79. def next_candidate(self):
  80. path = []
  81. for step in self.steps:
  82. path.append(step)
  83. if step.candidates:
  84. return path
  85. return None
  86. class Player(BaseClass):
  87. def __init__(self, id_):
  88. self.id = id_
  89. ME = Player(int(input())) # Input gives the player id: 0 plays first
  90. OPPONENT = Player(1 - ME.id)
  91. PLAYERS_INDEX = {p.id: p for p in [ME, OPPONENT]}
  92. PLAYERS_ORDER = sorted([ME, OPPONENT], key=lambda p: p.id)
  93. class Unit(BaseClass):
  94. TYPE_CULTIST = 0
  95. TYPE_CULT_LEADER = 1
  96. OWNER_0 = 0
  97. OWNER_1 = 1
  98. NO_OWNER = 2
  99. SHOOTING_RANGE = 6
  100. SHOOTING_MAX_DAMAGE = 7
  101. def __init__(self, id_):
  102. self.id = id_
  103. self.hp = 10
  104. self.x = None
  105. self.y = None
  106. self.owner = None
  107. @property
  108. def pos(self):
  109. return self.x, self.y
  110. @property
  111. def owned(self):
  112. return self.owner == ME.id
  113. @property
  114. def opponent(self):
  115. return self.owner == OPPONENT.id
  116. @property
  117. def neutral(self):
  118. return self.owner == self.NO_OWNER
  119. class CultLeader(Unit):
  120. pass
  121. class Action(BaseClass):
  122. pass
  123. class ActionWait(Action):
  124. def __repr__(self):
  125. return f"<ActionWait>"
  126. def exec(self):
  127. print("WAIT")
  128. class ActionMove(Action):
  129. def __init__(self, unit, pos, message=''):
  130. self.unit = unit
  131. self.pos = pos
  132. self.message = message
  133. def __repr__(self):
  134. return f"<ActionMove: {self.unit.id} to {self.pos} ({self.message})>"
  135. def exec(self):
  136. print(f"{self.unit.id} MOVE {self.pos[0]} {self.pos[1]}")
  137. class ActionShoot(Action):
  138. def __init__(self, unit, target):
  139. self.unit = unit
  140. self.target = target
  141. def __repr__(self):
  142. return f"<ActionShoot: {self.unit.id} to {self.target.id}>"
  143. def exec(self):
  144. print(f"{self.unit.id} SHOOT {self.target.id}")
  145. class ActionConvert(Action):
  146. def __init__(self, unit, target):
  147. self.unit = unit
  148. self.target = target
  149. def __repr__(self):
  150. return f"<ActionConvert: {self.unit.id} to {self.target.id}>"
  151. def exec(self):
  152. print(f"{self.unit.id} CONVERT {self.target.id}")
  153. class Grid(BaseClass):
  154. def __init__(self, width, height):
  155. self.width = width
  156. self.height = height
  157. self.cells = []
  158. self.obstacles = []
  159. self._neighbors = {}
  160. self.index = {}
  161. self.units = {}
  162. self.round = 1
  163. self.threat = {}
  164. self.control = {}
  165. self.heat_map = {}
  166. def pre_compute(self):
  167. self.cells = [(x, y) for x in range(self.width) for y in range(self.height)]
  168. for x, y in self.cells:
  169. self._neighbors[(x, y)] = [(xn, yn) for xn, yn in [(x, y - 1), (x - 1, y), (x + 1, y), (x, y + 1)] if
  170. 0 <= xn < self.width and 0 <= yn < self.height]
  171. def reinit_round(self):
  172. self.units = {}
  173. def update_unit(self, id_, type_, hp, x, y, owner):
  174. self.units[id_] = Unit(id_) if type_ != Unit.TYPE_CULT_LEADER else CultLeader(id_)
  175. unit = self.units[id_]
  176. unit.hp = hp
  177. unit.x = x
  178. unit.y = y
  179. unit.owner = owner
  180. def update_threat_map(self):
  181. self.threat = {(x, y): 0 for x in range(self.width) for y in range(self.height)}
  182. sources = self.opponent_cultists()
  183. # On ajoute les neutres voisins du leader ennemi aux sources de menace possible
  184. opponent_cult_leader = self.opponent_cult_leader()
  185. if opponent_cult_leader:
  186. for pos in self.neighbors(*opponent_cult_leader.pos):
  187. if pos in self.index and self.index[pos].neutral:
  188. sources.append(self.index[pos])
  189. for u in sources:
  190. shooting_zone = self.zone(u.pos, Unit.SHOOTING_RANGE)
  191. for x, y in shooting_zone:
  192. dist = shooting_zone[(x, y)]
  193. if not self.line_of_sight(u.pos, (x, y)):
  194. continue
  195. threat = Unit.SHOOTING_RANGE + 1 - dist
  196. if u.neutral:
  197. threat //= 2
  198. if threat > self.threat[(x, y)]:
  199. self.threat[(x, y)] = threat
  200. def update_control(self):
  201. self.control = {(x, y): 0 for x in range(self.width) for y in range(self.height)}
  202. for u in self.allied_cultists():
  203. shooting_zone = self.zone(u.pos, Unit.SHOOTING_RANGE)
  204. for x, y in shooting_zone:
  205. dist = shooting_zone[(x, y)]
  206. if not self.line_of_sight(u.pos, (x, y)):
  207. continue
  208. control = Unit.SHOOTING_RANGE + 1 - dist
  209. if control > self.control[(x, y)]:
  210. self.control[(x, y)] = control
  211. def update_heat_map(self):
  212. lines = []
  213. self.heat_map = {(x, y): 0 for x in range(self.width) for y in range(self.height)}
  214. cult_leader = self.cult_leader()
  215. for o in self.opponent_cultists():
  216. if cult_leader:
  217. lines += self.line(o.pos, cult_leader.pos)
  218. for n in self.neutrals():
  219. lines += self.line(o.pos, n.pos)
  220. for pos in lines:
  221. self.heat_map[pos] += 1
  222. def update(self):
  223. self.index = {}
  224. for unit in self.units.values():
  225. self.index[(unit.x, unit.y)] = unit
  226. self.update_threat_map()
  227. self.update_control()
  228. self.update_heat_map()
  229. def cult_leader(self):
  230. return next((u for u in self.units.values() if type(u) is CultLeader and u.owned), None)
  231. def allied_cultists(self):
  232. return [u for u in self.units.values() if type(u) is not CultLeader and u.owned]
  233. def owned_units(self):
  234. return [u for u in self.units.values() if u.owned]
  235. def opponent_units(self):
  236. return [u for u in self.units.values() if u.opponent]
  237. def opponent_cult_leader(self):
  238. return next((u for u in self.units.values() if type(u) is CultLeader and not u.owned), None)
  239. def opponent_cultists(self):
  240. return [u for u in self.units.values() if type(u) is not CultLeader and u.opponent]
  241. def neutrals(self):
  242. return [u for u in self.units.values() if u.neutral]
  243. def list_actions(self):
  244. actions = Queue()
  245. k_convert_number = -10
  246. k_convert_distance = 10
  247. k_convert_danger = 20
  248. k_shoot_opponent_cultist = 15
  249. k_shoot_opponent_cult_leader = 10
  250. k0_protect_cult_leader = 30
  251. k_protect_threat_level = -5
  252. k_cover_threat = 10
  253. k_cover_interest = -10
  254. k0_position = 50
  255. k_position_distance = 10
  256. k_position_heat = -2
  257. k_position_danger = 10
  258. k_position_advantage = 10
  259. cult_leader = self.cult_leader()
  260. opponent_cult_leader = self.opponent_cult_leader()
  261. # log(self.obstacles + [u.pos for u in self.allied_cultists()])
  262. # log([n.pos for n in self.neutrals()])
  263. # compute conversion paths
  264. conversion_path = []
  265. if cult_leader and self.neutrals():
  266. conversion_path = self.get_conversion_path(
  267. cult_leader,
  268. key=(lambda pos: pos in self.index and self.index[pos].neutral),
  269. limit=min(4, len(self.neutrals()))
  270. )
  271. log(conversion_path)
  272. # Conversion des neutres
  273. if cult_leader and conversion_path:
  274. path = conversion_path.next_candidate()
  275. if path:
  276. targets = [self.index[c] for c in path[-1].candidates]
  277. priority = 0
  278. priority += k_convert_number * len(targets)
  279. priority += k_convert_distance * len(path)
  280. priority += k_convert_danger * sum([self.threat[s.pos] for s in path])
  281. if len(path) == 1:
  282. action = ActionConvert(cult_leader, targets[0])
  283. else:
  284. action = ActionMove(cult_leader, path[1].pos, f'go convert {",".join([str(t.id) for t in targets])}')
  285. actions.put(priority, action)
  286. # Tire sur une unités ennemies
  287. targets = self.opponent_cultists()
  288. if opponent_cult_leader:
  289. targets.append(opponent_cult_leader)
  290. has_advantage = sum([t.hp for t in targets]) < sum([u.hp for u in self.owned_units()])
  291. for a in self.allied_cultists():
  292. for u in targets:
  293. shooting_distance = self.shooting_distance(a.pos, u.pos)
  294. if a.id == 4 and u.id == 1:
  295. log(self.line_of_sight(a.pos, u.pos))
  296. if shooting_distance and shooting_distance < u.SHOOTING_RANGE:
  297. action = ActionShoot(a, u)
  298. priority = (k_shoot_opponent_cult_leader if type(
  299. u) is CultLeader else k_shoot_opponent_cultist) * shooting_distance
  300. actions.put(priority, action)
  301. # Position
  302. for a in self.allied_cultists():
  303. # on garde les trois points les plus chauds
  304. hot_spots = sorted(self.heat_map.items(), key=lambda p: p[1], reverse=True)[:3]
  305. results = self.discover(a, key=lambda x: x in [s[0] for s in hot_spots], limit=3)
  306. for path, target_pos in results:
  307. if not path:
  308. break
  309. heat = self.heat_map[target_pos]
  310. priority = k0_position
  311. priority += k_position_heat * heat
  312. priority += k_position_distance * len(path)
  313. priority += k_position_danger * sum(self.threat[p] for p in path)
  314. action = ActionMove(a, path[0], f'go for hotspot {target_pos} by {path}')
  315. actions.put(priority, action)
  316. # Mise en sécurité du chef
  317. if cult_leader:
  318. current_threat = self.threat[cult_leader.pos]
  319. if current_threat:
  320. covers = [n for n in self.neighbors(*cult_leader.pos) if self.can_move_on(cult_leader, n)]
  321. for pos in covers:
  322. action = ActionMove(cult_leader, pos, f'take cover (t: {current_threat})')
  323. interest = conversion_path and conversion_path.steps and pos in [s.pos for s in conversion_path.steps]
  324. priority = k0_protect_cult_leader
  325. priority += k_protect_threat_level * current_threat
  326. priority += k_cover_threat * self.threat[pos]
  327. priority += k_cover_interest * interest
  328. actions.put(priority, action)
  329. return actions
  330. def in_grid(self, pos):
  331. return 0 <= pos[0] < self.width and 0 <= pos[1] < self.height
  332. def can_see_trough(self, pos):
  333. return self.in_grid(pos) and pos not in self.obstacles and pos not in self.index
  334. def can_move_on(self, unit, pos):
  335. return self.in_grid(pos) and pos not in self.obstacles and (pos not in self.index or self.index[pos] is unit)
  336. def can_discover(self, pos):
  337. return self.in_grid(pos) and pos not in self.obstacles
  338. def moving_cost(self, unit, pos):
  339. if not self.can_move_on(unit, pos):
  340. return -1
  341. return 1 + self.threat[pos]
  342. @staticmethod
  343. def manhattan(from_, to_):
  344. xa, ya = from_
  345. xb, yb = to_
  346. return abs(xa - xb) + abs(ya - yb)
  347. def neighbors(self, x, y):
  348. return self._neighbors[(x, y)]
  349. def zone(self, pos, radius):
  350. x0, y0 = pos
  351. zone = {}
  352. for x in range(max(x0 - radius, 0), min(x0 + radius, self.width)):
  353. for y in range(max(y0 - radius, 0), min(y0 + radius, self.height)):
  354. dist = self.manhattan(pos, (x, y))
  355. if dist <= radius:
  356. zone[(x, y)] = dist
  357. return zone
  358. @classmethod
  359. def line(cls, start, target):
  360. """
  361. adapted from https://github.com/fragkakis/bresenham/blob/master/src/main/java/org/fragkakis/Bresenham.java
  362. if strict is true, None is return if an obstacle interrupted the line; else a partial line is returned (from start to obstacle)
  363. """
  364. line = []
  365. x0, y0 = start
  366. x1, y1 = target
  367. dx = abs(x1 - x0)
  368. dy = abs(y1 - y0)
  369. sx = 1 if x0 < x1 else -1
  370. sy = 1 if y0 < y1 else -1
  371. err = dx - dy
  372. x, y = x0, y0
  373. while 1:
  374. line.append((x, y))
  375. if x == x1 and y == y1:
  376. break
  377. e2 = 2 * err
  378. if e2 > (-1 * dy):
  379. err -= dy
  380. x += sx
  381. if e2 < dx:
  382. err += dx
  383. y += sy
  384. return line
  385. def line_of_sight(self, from_, to_):
  386. line = self.line(from_, to_)[1:]
  387. return line if all(self.can_see_trough(c) for c in line[:-1]) else []
  388. def shooting_distance(self, from_, to_):
  389. return len(self.line_of_sight(from_, to_))
  390. def path(self, unit, target):
  391. nodes = Queue()
  392. its, break_on = 0, 400
  393. origin = PathNode(*unit.pos)
  394. nodes.put(0, origin)
  395. while nodes:
  396. current = nodes.get()
  397. if current == target:
  398. path = []
  399. previous = current
  400. while previous:
  401. if previous != unit.pos:
  402. path.insert(0, previous)
  403. previous = previous.parent
  404. return path
  405. neighbors = self.neighbors(*current)
  406. for x, y in neighbors:
  407. its += 1
  408. if its > break_on:
  409. log("<!> pathfinding broken")
  410. return None
  411. if (x, y) == current.parent:
  412. continue
  413. if not self.can_move_on(unit, (x, y)):
  414. continue
  415. moving_cost = self.moving_cost(unit, (x, y))
  416. cost = current.cost + moving_cost
  417. priority = cost + 10 * Grid.manhattan((x, y), target)
  418. node = PathNode(x, y, current)
  419. node.cost = cost
  420. nodes.put(priority, node)
  421. return None
  422. def discover(self, unit, key, limit=5):
  423. paths = []
  424. nodes = []
  425. its, break_on = 0, 2000
  426. origin = DiscoveryNode(*unit.pos)
  427. nodes.append(origin)
  428. while nodes:
  429. current = nodes.pop(0) # l'ordre est important, pour que les premiers indexés soient les premiers analysés
  430. neighbors = self.neighbors(*current)
  431. for pos in neighbors:
  432. its += 1
  433. if its > break_on:
  434. log(f"<!> discovery broke, {len(paths)} results")
  435. return paths
  436. if current != unit.pos and key(pos):
  437. path = current.ancestors[1:] + [current]
  438. paths.append((path, pos))
  439. if len(paths) >= limit:
  440. return paths
  441. continue
  442. if pos in current.ancestors:
  443. continue
  444. if not self.can_move_on(unit, pos):
  445. continue
  446. node = DiscoveryNode(*pos, 0, current.ancestors + [current])
  447. nodes.append(node)
  448. return paths
  449. def get_conversion_path(self, unit, key, limit=5):
  450. """ essaies de trouver le meilleur chemin pour relier des cases dont au moins une voisine valide
  451. la condition 'key' (dans la limite de 'limit')"""
  452. nodes = Queue()
  453. winners = Queue()
  454. its, break_on = 0, 1000
  455. origin = DiscoveryNode(*unit.pos)
  456. abandon_at = 120 # number of paths explored
  457. nodes.put(0, origin)
  458. for n in self.neighbors(*unit.pos):
  459. if key(n):
  460. origin.matches.append(n)
  461. while nodes:
  462. its += 1
  463. if its > break_on:
  464. log(f"<!> get_conversion_path broke")
  465. break
  466. if len(nodes.items) > abandon_at:
  467. log("> get_conversion_path early exit")
  468. break
  469. current = nodes.get()
  470. for pos in self.neighbors(*current):
  471. if not self.can_move_on(unit, pos):
  472. continue
  473. moving_cost = 1
  474. matches = []
  475. for n in self.neighbors(*pos):
  476. if n not in current.matches and key(n):
  477. matches.append(n)
  478. cost = current.cost + moving_cost
  479. priority = 1000 * cost - (2000 * (len(current.matches) + len(matches)))
  480. priority += 100 * len(
  481. [a for a in current.ancestors if a == pos]) # décourage de revenir à une case visitée
  482. node = DiscoveryNode(
  483. pos[0],
  484. pos[1],
  485. cost,
  486. current.ancestors + [current],
  487. current.matches + matches
  488. )
  489. if matches:
  490. winners.put(40 * node.cost - 100 * len(node.matches), node)
  491. nodes.put(priority, node)
  492. if len(current.matches) >= limit or its > break_on:
  493. break
  494. try:
  495. best_node = winners.get()
  496. except IndexError:
  497. best_node = nodes.get()
  498. return ConversionPath.make_from_discovery_node(best_node)
  499. def _repr_cell(self, pos):
  500. return f"{self.threat[pos]}"
  501. # return f"{self.control[pos]}/{self.threat[pos]}"
  502. # return self.heat_map[pos]
  503. if pos in self.obstacles:
  504. return "X"
  505. unit = self.index.get(pos, None)
  506. if type(unit) is CultLeader:
  507. return "C"
  508. elif unit is None:
  509. return "."
  510. else:
  511. return "U"
  512. def graph(self):
  513. return "\n".join(
  514. ["|".join([str(self._repr_cell((x, y))) for x in range(self.width)]) for y in range(self.height)])
  515. # Create grid
  516. GRID = Grid(*[int(i) for i in input().split()])
  517. obstacles_input = [input() for y in range(GRID.height)]
  518. GRID.obstacles = [(x, y) for y, row in enumerate(obstacles_input) for x, val in enumerate(row) if val == 'x']
  519. GRID.pre_compute()
  520. while 1:
  521. # TODO: le bresenham est à revoir pour les tirs...
  522. # TODO : en cas de choix entre plusieurs neutres à convertir, privilégier un neutre se trouvant entre un ennemi et le leader
  523. # TODO: Laisser l'algo de découverte des cibles à convertir passer outre les alliés, ajouter une action "dégager le passage" pour ces unités
  524. # (prévoir le cas où cet allié ne peut pas se dégager). Le fait de passer outre un allié doit augmenter le coût de mouvement de 1
  525. # TODO : Etre plus prudent dans le positionnement des unités; ne pas s'attaquer à plus fort que soi, et décourager plus fortement l'entrée dans une
  526. # zone de menace
  527. # TODO: donner un coup à l'action "ne rien faire", car c'est parfois la meilleure chose à faire...
  528. # TODO: ajouter une action "s'interposer" où une unité s'interpose entre le leader et un ennemi ; à mettre en balance avec le 'take cover'
  529. # TODO: remplacer le discover par un algo qui cherche le plus court chemin pour relier tous les neutres les uns après les autres
  530. GRID.reinit_round()
  531. for _ in range(int(input())):
  532. GRID.update_unit(*[int(j) for j in input().split()])
  533. log(f"start round {GRID.round}")
  534. GRID.update()
  535. actions = GRID.list_actions()
  536. print("\n" + GRID.graph(), file=sys.stderr)
  537. for action in actions.items:
  538. log(f"* {action}")
  539. try:
  540. action = actions.get()
  541. except IndexError:
  542. log("no action...")
  543. action = ActionWait()
  544. log(f"exec : {action}")
  545. action.exec()
  546. GRID.round += 1