main.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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 = 30
  248. k_shoot_opponent_cultist = 10
  249. k_shoot_opponent_cult_leader = 5
  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 = 5
  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. # Attaque d'unités ennemies
  287. targets = self.opponent_cultists()
  288. if opponent_cult_leader:
  289. targets.append(opponent_cult_leader)
  290. 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 shooting_distance and shooting_distance < u.SHOOTING_RANGE:
  295. action = ActionShoot(a, u)
  296. priority = (k_shoot_opponent_cult_leader if type(
  297. u) is CultLeader else k_shoot_opponent_cultist) * shooting_distance
  298. actions.put(priority, action)
  299. # Position
  300. for a in self.allied_cultists():
  301. # on garde les trois points les plus chauds
  302. hot_spots = sorted(self.heat_map.items(), key=lambda p: p[1], reverse=True)[:3]
  303. # results = self.discover(a.pos, key=lambda x: x in [s[0] for s in hot_spots])
  304. # for path, target_pos in results:
  305. # if not path:
  306. # break
  307. for spot_pos, heat in hot_spots:
  308. priority = k0_position
  309. priority += k_position_heat * heat
  310. priority += k_position_distance * self.manhattan(a.pos, spot_pos)
  311. priority += k_position_danger * self.threat[spot_pos]
  312. action = ActionMove(a, spot_pos, f'pos on {spot_pos}')
  313. actions.put(priority, action)
  314. # Mise en sécurité du chef
  315. if cult_leader:
  316. current_threat = self.threat[cult_leader.pos]
  317. if current_threat:
  318. covers = [n for n in self.neighbors(*cult_leader.pos) if self.can_move_on(cult_leader, n)]
  319. for pos in covers:
  320. action = ActionMove(cult_leader, pos, 'take cover')
  321. interest = conversion_path and conversion_path.steps and conversion_path.steps[0].pos == pos
  322. priority = k0_protect_cult_leader
  323. priority += k_protect_threat_level * current_threat
  324. priority += k_cover_threat * self.threat[pos]
  325. priority += k_cover_interest * interest
  326. actions.put(priority, action)
  327. return actions
  328. def in_grid(self, pos):
  329. return 0 <= pos[0] < self.width and 0 <= pos[1] < self.height
  330. def can_see_trough(self, pos):
  331. return self.in_grid(pos) and pos not in self.obstacles and pos not in self.index
  332. def can_move_on(self, unit, pos):
  333. return self.in_grid(pos) and pos not in self.obstacles and (pos not in self.index or self.index[pos] is unit)
  334. def can_discover(self, pos):
  335. return self.in_grid(pos) and pos not in self.obstacles
  336. def moving_cost(self, unit, pos):
  337. if not self.can_move_on(unit, pos):
  338. return -1
  339. return 1 + self.threat[pos]
  340. @staticmethod
  341. def manhattan(from_, to_):
  342. xa, ya = from_
  343. xb, yb = to_
  344. return abs(xa - xb) + abs(ya - yb)
  345. def neighbors(self, x, y):
  346. return self._neighbors[(x, y)]
  347. def zone(self, pos, radius):
  348. x0, y0 = pos
  349. zone = {}
  350. for x in range(max(x0 - radius, 0), min(x0 + radius, self.width)):
  351. for y in range(max(y0 - radius, 0), min(y0 + radius, self.height)):
  352. dist = self.manhattan(pos, (x, y))
  353. if dist <= radius:
  354. zone[(x, y)] = dist
  355. return zone
  356. @classmethod
  357. def line(cls, from_, to_):
  358. """ Implementation of bresenham's algorithm """
  359. xa, ya = from_
  360. xb, yb = to_
  361. if (xa, ya) == (xb, yb):
  362. return [(xa, ya)]
  363. # diagonal symmetry
  364. vertically_oriented = (abs(yb - ya) > abs(xb - xa))
  365. if vertically_oriented:
  366. ya, xa, yb, xb = xa, ya, xb, yb
  367. # horizontal symmetry
  368. reversed_sym = (xa > xb)
  369. if reversed_sym:
  370. xb, yb, xa, ya = xa, ya, xb, yb
  371. # angle
  372. dx, dy = xb - xa, yb - ya
  373. alpha = (abs(dy) / dx)
  374. offset = 0.0
  375. step = 1 if dy > 0 else -1
  376. result = []
  377. y_ = ya
  378. for x_ in range(xa, xb + 1):
  379. result.append((y_, x_) if vertically_oriented else (x_, y_))
  380. offset += alpha
  381. if offset > 0.5:
  382. y_ += step
  383. offset -= 1.0
  384. if reversed_sym:
  385. result.reverse()
  386. return result
  387. def line_of_sight(self, from_, to_):
  388. line = self.line(from_, to_)[1:]
  389. return line if all(self.can_see_trough(c) for c in line[:-1]) else []
  390. def shooting_distance(self, from_, to_):
  391. return len(self.line_of_sight(from_, to_))
  392. def path(self, unit, target):
  393. nodes = Queue()
  394. its, break_on = 0, 400
  395. origin = PathNode(*unit.pos)
  396. nodes.put(0, origin)
  397. while nodes:
  398. current = nodes.get()
  399. if current == target:
  400. path = []
  401. previous = current
  402. while previous:
  403. if previous != unit.pos:
  404. path.insert(0, previous)
  405. previous = previous.parent
  406. return path
  407. neighbors = self.neighbors(*current)
  408. for x, y in neighbors:
  409. its += 1
  410. if its > break_on:
  411. log("<!> pathfinding broken")
  412. return None
  413. if (x, y) == current.parent:
  414. continue
  415. if not self.can_move_on(unit, (x, y)):
  416. continue
  417. moving_cost = self.moving_cost(unit, (x, y))
  418. cost = current.cost + moving_cost
  419. priority = cost + 10 * Grid.manhattan((x, y), target)
  420. node = PathNode(x, y, current)
  421. node.cost = cost
  422. nodes.put(priority, node)
  423. return None
  424. def discover(self, unit, key, limit=5):
  425. paths = []
  426. nodes = []
  427. its, break_on = 0, 2000
  428. origin = DiscoveryNode(*unit.pos)
  429. nodes.append(origin)
  430. while nodes:
  431. current = nodes.pop(0) # l'ordre est important, pour que les premiers indexés soient les premiers analysés
  432. neighbors = self.neighbors(*current)
  433. for pos in neighbors:
  434. its += 1
  435. if its > break_on:
  436. log(f"<!> discovery broke, {len(paths)} results")
  437. return paths
  438. if key(pos):
  439. path = current.ancestors[:-1:-1] + [current] # reverse ancestors after having removed the start
  440. paths.append((path, pos))
  441. if len(paths) >= limit:
  442. return paths
  443. continue
  444. if pos in current.ancestors:
  445. continue
  446. if not self.can_move_on(unit, pos):
  447. continue
  448. node = DiscoveryNode(*pos, current.ancestors + [current])
  449. nodes.append(node)
  450. return paths
  451. def get_conversion_path(self, unit, key, limit=5):
  452. """ essaies de trouver le meilleur chemin pour relier des cases dont au moins une voisine valide
  453. la condition 'key' (dans la limite de 'limit')"""
  454. nodes = Queue()
  455. winners = Queue()
  456. its, break_on = 0, 1000
  457. origin = DiscoveryNode(*unit.pos)
  458. abandon_at = 120 # number of paths explored
  459. nodes.put(0, origin)
  460. for n in self.neighbors(*unit.pos):
  461. if key(n):
  462. origin.matches.append(n)
  463. while nodes:
  464. its += 1
  465. if its > break_on:
  466. log(f"<!> get_conversion_path broke")
  467. break
  468. if len(nodes.items) > abandon_at:
  469. log("> get_conversion_path early exit")
  470. break
  471. current = nodes.get()
  472. for pos in self.neighbors(*current):
  473. if not self.can_move_on(unit, pos):
  474. continue
  475. moving_cost = 1
  476. matches = []
  477. for n in self.neighbors(*pos):
  478. if n not in current.matches and key(n):
  479. matches.append(n)
  480. cost = current.cost + moving_cost
  481. priority = 1000 * cost - (2000 * (len(current.matches) + len(matches)))
  482. priority += 100 * len(
  483. [a for a in current.ancestors if a == pos]) # décourage de revenir à une case visitée
  484. node = DiscoveryNode(
  485. pos[0],
  486. pos[1],
  487. cost,
  488. current.ancestors + [current],
  489. current.matches + matches
  490. )
  491. if matches:
  492. winners.put(40 * node.cost - 100 * len(node.matches), node)
  493. nodes.put(priority, node)
  494. if len(current.matches) >= limit or its > break_on:
  495. break
  496. try:
  497. best_node = winners.get()
  498. except IndexError:
  499. best_node = nodes.get()
  500. return ConversionPath.make_from_discovery_node(best_node)
  501. def _repr_cell(self, pos):
  502. # return f"{self.control[pos]}/{self.threat[pos]}"
  503. # return self.heat_map[pos]
  504. if pos in self.obstacles:
  505. return "X"
  506. unit = self.index.get(pos, None)
  507. if type(unit) is CultLeader:
  508. return "C"
  509. elif unit is None:
  510. return "."
  511. else:
  512. return "U"
  513. def graph(self):
  514. return "\n".join(
  515. ["|".join([str(self._repr_cell((x, y))) for x in range(self.width)]) for y in range(self.height)])
  516. # Create grid
  517. GRID = Grid(*[int(i) for i in input().split()])
  518. obstacles_input = [input() for y in range(GRID.height)]
  519. GRID.obstacles = [(x, y) for y, row in enumerate(obstacles_input) for x, val in enumerate(row) if val == 'x']
  520. GRID.pre_compute()
  521. while 1:
  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. for action in actions.items:
  537. log(f"* {action}")
  538. # print("\n" + GRID.graph(), file=sys.stderr)
  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