main.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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.round = 1
  158. self.cells = []
  159. self.obstacles = []
  160. self._neighbors = {}
  161. self.index = {}
  162. self.units = {}
  163. self.threat = {}
  164. self.conversion_path = []
  165. self.cult_leader = None
  166. self.opponent_cult_leader = None
  167. self.allied_cultists = []
  168. self.owned_units = []
  169. self.opponent_units = []
  170. self.opponent_cultists = []
  171. self.neutrals = []
  172. def pre_compute(self):
  173. self.cells = [(x, y) for x in range(self.width) for y in range(self.height)]
  174. for x, y in self.cells:
  175. self._neighbors[(x, y)] = [(xn, yn) for xn, yn in [(x, y - 1), (x - 1, y), (x + 1, y), (x, y + 1)] if
  176. 0 <= xn < self.width and 0 <= yn < self.height]
  177. def reinit_round(self):
  178. self.units = {}
  179. def update_unit(self, id_, type_, hp, x, y, owner):
  180. self.units[id_] = Unit(id_) if type_ != Unit.TYPE_CULT_LEADER else CultLeader(id_)
  181. unit = self.units[id_]
  182. unit.hp = hp
  183. unit.x = x
  184. unit.y = y
  185. unit.owner = owner
  186. def update_index(self):
  187. self.index = {}
  188. self.cult_leader = None
  189. self.opponent_cult_leader = None
  190. self.allied_cultists = []
  191. self.owned_units = []
  192. self.opponent_units = []
  193. self.opponent_cultists = []
  194. self.neutrals = []
  195. for unit in self.units.values():
  196. self.index[(unit.x, unit.y)] = unit
  197. if unit.owner == ME.id:
  198. self.owned_units.append(unit)
  199. if type(unit) is CultLeader:
  200. self.cult_leader = unit
  201. else:
  202. self.allied_cultists.append(unit)
  203. elif unit.owner == OPPONENT.id:
  204. self.opponent_units.append(unit)
  205. if type(unit) is CultLeader:
  206. self.opponent_cult_leader = unit
  207. else:
  208. self.opponent_cultists.append(unit)
  209. else:
  210. self.neutrals.append(unit)
  211. def update_threat_map(self):
  212. self.threat = {(x, y): 0 for x in range(self.width) for y in range(self.height)}
  213. sources = self.opponent_cultists
  214. # On ajoute les neutres voisins du leader ennemi aux sources de menace possible
  215. if self.opponent_cult_leader:
  216. for pos in self.neighbors(*self.opponent_cult_leader.pos):
  217. if pos in self.index and self.index[pos].neutral:
  218. sources.append(self.index[pos])
  219. for u in sources:
  220. shooting_zone = self.zone(u.pos, Unit.SHOOTING_RANGE)
  221. for x, y in shooting_zone:
  222. dist = shooting_zone[(x, y)]
  223. if not self.line_of_sight(u.pos, (x, y)):
  224. continue
  225. threat = Unit.SHOOTING_RANGE + 1 - dist
  226. if u.neutral:
  227. threat //= 2
  228. if threat > self.threat[(x, y)]:
  229. self.threat[(x, y)] = threat
  230. def compute_conversion_path(self):
  231. conversion_path = []
  232. if self.cult_leader and self.neutrals:
  233. conversion_path = self.get_conversion_path(
  234. self.cult_leader,
  235. key=(lambda pos: pos in self.index and self.index[pos].neutral),
  236. limit=min(4, len(self.neutrals))
  237. )
  238. log(conversion_path)
  239. self.conversion_path = conversion_path
  240. def update(self):
  241. log('update indexes')
  242. self.update_index()
  243. self.update_threat_map()
  244. self.compute_conversion_path()
  245. # log(self.obstacles + [u.pos for u in self.allied_cultists])
  246. # log([n.pos for n in self.neutrals])
  247. def build_actions(self):
  248. actions = Queue()
  249. # Leader take cover
  250. k0_protect_cult_leader = 30
  251. k_protect_threat_level = -5
  252. k_cover_threat = 10
  253. k_cover_interest = -10
  254. if self.cult_leader:
  255. current_threat = self.threat[self.cult_leader.pos]
  256. if current_threat:
  257. covers = [n for n in self.neighbors(*self.cult_leader.pos) if self.can_move_on(self.cult_leader, n)]
  258. for pos in covers:
  259. action = ActionMove(self.cult_leader, pos, f'take cover (t: {current_threat})')
  260. interest = self.conversion_path and self.conversion_path.steps and pos in [s.pos for s in
  261. self.conversion_path.steps]
  262. priority = k0_protect_cult_leader
  263. priority += k_protect_threat_level * current_threat
  264. priority += k_cover_threat * self.threat[pos]
  265. priority += k_cover_interest * interest
  266. actions.put(priority, action)
  267. # Convert
  268. k_convert_number = -10
  269. k_convert_distance = 10
  270. k_convert_danger = 20
  271. if self.cult_leader and self.conversion_path:
  272. path = self.conversion_path.next_candidate()
  273. if path:
  274. targets = [self.index[c] for c in path[-1].candidates]
  275. priority = 0
  276. priority += k_convert_number * len(targets)
  277. priority += k_convert_distance * len(path)
  278. priority += k_convert_danger * sum([self.threat[s.pos] for s in path])
  279. if len(path) == 1:
  280. action = ActionConvert(self.cult_leader, targets[0])
  281. else:
  282. action = ActionMove(self.cult_leader, path[1].pos,
  283. f'go convert {",".join([str(t.id) for t in targets])}')
  284. actions.put(priority, action)
  285. # Shoot opponent units
  286. k_shoot_opponent_cultist = 8
  287. k_shoot_opponent_cult_leader = 4
  288. k_shoot_movement_needed = 15
  289. for a in self.allied_cultists:
  290. for u in self.opponent_units:
  291. shooting_distance = self.shooting_distance(a.pos, u.pos)
  292. if not shooting_distance:
  293. continue
  294. if shooting_distance <= u.SHOOTING_RANGE:
  295. # la cible est à portée
  296. action = ActionShoot(a, u)
  297. priority = (k_shoot_opponent_cult_leader if type(
  298. u) is CultLeader else k_shoot_opponent_cultist) * shooting_distance
  299. log(self.line_of_sight(a.pos, u.pos))
  300. actions.put(priority, action)
  301. else:
  302. # la cible est hors de portée, mais elle est plus faible et sans soutien
  303. # TODO: implémenter
  304. pass
  305. # Position
  306. k0_position = 50
  307. k_advantage = 40
  308. k_position_distance = 10
  309. k_position_heat = -2
  310. k_position_danger = 10
  311. advantage = len(self.owned_units) > len(self.opponent_units) + len(self.neutrals)
  312. for a in self.allied_cultists:
  313. if self.threat[a.pos]:
  314. # l'unité est déjà dans une zone à risque
  315. # TODO: envisager un retrait
  316. continue
  317. else:
  318. # l'unité semble en sécurité, go to front-line
  319. nearest_frontline = self.discover(a, key=lambda x: self.threat[x] == 1, limit=1)
  320. if not nearest_frontline:
  321. log(f"<!> {u.id} can not join nearest frontline")
  322. continue
  323. path, target = nearest_frontline[0]
  324. if path:
  325. log(f"{a.id} - {path} - {target}")
  326. # already in place
  327. priority = k0_position
  328. priority += k_position_distance * len(path)
  329. priority += k_position_danger * sum(self.threat[p] for p in path)
  330. priority += k_advantage * advantage
  331. action = ActionMove(a, path[0], f'go to frontline {target} by {path}')
  332. actions.put(priority, action)
  333. # TODO: action 'take cover' pour les unités aussi
  334. # TODO: action 'peace-keeping': tirer sur les neutres qu'on ne pourra pas convertir avant l'ennemi
  335. # TODO: action 'intercept': une unité se place entre un tireur ennemi et le leader; en dernier recours
  336. # TODO: action 'do nothing' : parfois, c'est la meilleure chose à faire
  337. return actions
  338. def in_grid(self, pos):
  339. return 0 <= pos[0] < self.width and 0 <= pos[1] < self.height
  340. def can_see_trough(self, pos):
  341. return self.in_grid(pos) and pos not in self.obstacles and pos not in self.index
  342. def can_move_on(self, unit, pos):
  343. return self.in_grid(pos) and pos not in self.obstacles and (pos not in self.index or self.index[pos] is unit)
  344. def can_discover(self, pos):
  345. return self.in_grid(pos) and pos not in self.obstacles
  346. def moving_cost(self, unit, pos):
  347. if not self.can_move_on(unit, pos):
  348. return -1
  349. return 1 + self.threat[pos]
  350. @staticmethod
  351. def manhattan(from_, to_):
  352. xa, ya = from_
  353. xb, yb = to_
  354. return abs(xa - xb) + abs(ya - yb)
  355. def neighbors(self, x, y):
  356. return self._neighbors[(x, y)]
  357. def zone(self, pos, radius):
  358. x0, y0 = pos
  359. zone = {}
  360. for x in range(max(x0 - radius, 0), min(x0 + radius, self.width)):
  361. for y in range(max(y0 - radius, 0), min(y0 + radius, self.height)):
  362. dist = self.manhattan(pos, (x, y))
  363. if dist <= radius:
  364. zone[(x, y)] = dist
  365. return zone
  366. @classmethod
  367. def line(cls, start, target):
  368. """
  369. adapted from https://github.com/fragkakis/bresenham/blob/master/src/main/java/org/fragkakis/Bresenham.java
  370. if strict is true, None is return if an obstacle interrupted the line; else a partial line is returned (from start to obstacle)
  371. """
  372. line = []
  373. x0, y0 = start
  374. x1, y1 = target
  375. if y0 > y1:
  376. # on fait toujours de bas en haut, du coup on inverse au besoin
  377. x0, y0, x1, y1 = x1, y1, x0, y0
  378. dx = abs(x1 - x0)
  379. dy = abs(y1 - y0)
  380. sx = 1 if x0 < x1 else -1
  381. sy = 1 if y0 < y1 else -1
  382. err = dx - dy
  383. x, y = x0, y0
  384. while 1:
  385. line.append((x, y))
  386. if x == x1 and y == y1:
  387. break
  388. e2 = 2 * err
  389. if e2 > (-1 * dy):
  390. err -= dy
  391. x += sx
  392. if e2 < dx:
  393. err += dx
  394. y += sy
  395. return line
  396. def line_of_sight(self, from_, to_):
  397. line = self.line(from_, to_)[1:]
  398. return line if all(self.can_see_trough(c) for c in line[:-1]) else []
  399. def shooting_distance(self, from_, to_):
  400. return len(self.line_of_sight(from_, to_))
  401. def path(self, unit, target):
  402. nodes = Queue()
  403. its, break_on = 0, 400
  404. origin = PathNode(*unit.pos)
  405. nodes.put(0, origin)
  406. while nodes:
  407. current = nodes.get()
  408. if current == target:
  409. path = []
  410. previous = current
  411. while previous:
  412. if previous != unit.pos:
  413. path.insert(0, previous)
  414. previous = previous.parent
  415. return path
  416. neighbors = self.neighbors(*current)
  417. for x, y in neighbors:
  418. its += 1
  419. if its > break_on:
  420. log("<!> pathfinding broken")
  421. return None
  422. if (x, y) == current.parent:
  423. continue
  424. if not self.can_move_on(unit, (x, y)):
  425. continue
  426. moving_cost = self.moving_cost(unit, (x, y))
  427. cost = current.cost + moving_cost
  428. priority = cost + 10 * Grid.manhattan((x, y), target)
  429. node = PathNode(x, y, current)
  430. node.cost = cost
  431. nodes.put(priority, node)
  432. return None
  433. def discover(self, unit, key, limit=5):
  434. paths = []
  435. nodes = []
  436. its, break_on = 0, 2000
  437. origin = DiscoveryNode(*unit.pos)
  438. nodes.append(origin)
  439. while nodes:
  440. current = nodes.pop(0) # l'ordre est important, pour que les premiers indexés soient les premiers analysés
  441. neighbors = self.neighbors(*current)
  442. for pos in neighbors:
  443. its += 1
  444. if its > break_on:
  445. log(f"<!> discovery broke, {len(paths)} results")
  446. return paths
  447. if current != unit.pos and key(pos):
  448. path = current.ancestors[1:] + [current]
  449. paths.append((path, pos))
  450. if len(paths) >= limit:
  451. return paths
  452. continue
  453. if pos in current.ancestors:
  454. continue
  455. if not self.can_move_on(unit, pos):
  456. continue
  457. node = DiscoveryNode(*pos, 0, current.ancestors + [current])
  458. nodes.append(node)
  459. return paths
  460. def get_conversion_path(self, unit, key, limit=5):
  461. """ essaies de trouver le meilleur chemin pour relier des cases dont au moins une voisine valide
  462. la condition 'key' (dans la limite de 'limit')"""
  463. nodes = Queue()
  464. winners = Queue()
  465. its, break_on = 0, 1000
  466. origin = DiscoveryNode(*unit.pos)
  467. abandon_at = 120 # number of paths explored
  468. nodes.put(0, origin)
  469. for n in self.neighbors(*unit.pos):
  470. if key(n):
  471. origin.matches.append(n)
  472. while nodes:
  473. its += 1
  474. if its > break_on:
  475. log(f"<!> get_conversion_path broke")
  476. break
  477. if len(nodes.items) > abandon_at:
  478. log("> get_conversion_path early exit")
  479. break
  480. current = nodes.get()
  481. for pos in self.neighbors(*current):
  482. if not self.can_move_on(unit, pos):
  483. continue
  484. moving_cost = 1
  485. matches = []
  486. for n in self.neighbors(*pos):
  487. if n not in current.matches and key(n):
  488. matches.append(n)
  489. cost = current.cost + moving_cost
  490. priority = 1000 * cost - (2000 * (len(current.matches) + len(matches)))
  491. priority += 100 * len(
  492. [a for a in current.ancestors if a == pos]) # décourage de revenir à une case visitée
  493. node = DiscoveryNode(
  494. pos[0],
  495. pos[1],
  496. cost,
  497. current.ancestors + [current],
  498. current.matches + matches
  499. )
  500. if matches:
  501. winners.put(40 * node.cost - 100 * len(node.matches), node)
  502. nodes.put(priority, node)
  503. if len(current.matches) >= limit or its > break_on:
  504. break
  505. try:
  506. best_node = winners.get()
  507. except IndexError:
  508. if nodes:
  509. best_node = nodes.get()
  510. else:
  511. best_node = origin
  512. return ConversionPath.make_from_discovery_node(best_node)
  513. def _repr_cell(self, pos):
  514. return f"{self.threat[pos]}"
  515. # return f"{self.control[pos]}/{self.threat[pos]}"
  516. # return self.heat_map[pos]
  517. if pos in self.obstacles:
  518. return "X"
  519. unit = self.index.get(pos, None)
  520. if type(unit) is CultLeader:
  521. return "C"
  522. elif unit is None:
  523. return "."
  524. else:
  525. return "U"
  526. def graph(self):
  527. return "\n".join(
  528. ["|".join([str(self._repr_cell((x, y))) for x in range(self.width)]) for y in range(self.height)])
  529. # Create grid
  530. GRID = Grid(*[int(i) for i in input().split()])
  531. obstacles_input = [input() for y in range(GRID.height)]
  532. GRID.obstacles = [(x, y) for y, row in enumerate(obstacles_input) for x, val in enumerate(row) if val == 'x']
  533. GRID.pre_compute()
  534. while 1:
  535. GRID.reinit_round()
  536. for _ in range(int(input())):
  537. GRID.update_unit(*[int(j) for j in input().split()])
  538. log(f"start round {GRID.round}")
  539. GRID.update()
  540. actions = GRID.build_actions()
  541. # print("\n" + GRID.graph(), file=sys.stderr)
  542. for action in actions.items:
  543. log(f"* {action}")
  544. try:
  545. action = actions.get()
  546. except IndexError:
  547. log("no action...")
  548. action = ActionWait()
  549. log(f"exec : {action}")
  550. action.exec()
  551. GRID.round += 1