main.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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 Queue(BaseClass):
  28. def __init__(self):
  29. self.items = []
  30. def __bool__(self):
  31. return bool(self.items)
  32. def __repr__(self):
  33. return str(self.items)
  34. def values(self):
  35. return (v for _, v in self.items)
  36. def put(self, priority, item):
  37. while priority in [p for p, _ in self.items]:
  38. priority += 1
  39. heapq.heappush(self.items, (priority, item))
  40. def get(self):
  41. return heapq.heappop(self.items)[1]
  42. def get_items(self):
  43. return heapq.heappop(self.items)
  44. class Player(BaseClass):
  45. def __init__(self, id_):
  46. self.id = id_
  47. ME = Player(int(input())) # Input gives the player id: 0 plays first
  48. OPPONENT = Player(1 - ME.id)
  49. PLAYERS_INDEX = {p.id: p for p in [ME, OPPONENT]}
  50. PLAYERS_ORDER = sorted([ME, OPPONENT], key=lambda p: p.id)
  51. class Unit(BaseClass):
  52. TYPE_CULTIST = 0
  53. TYPE_CULT_LEADER = 1
  54. OWNER_0 = 0
  55. OWNER_1 = 1
  56. NO_OWNER = 2
  57. SHOOTING_RANGE = 6
  58. SHOOTING_MAX_DAMAGE = 7
  59. def __init__(self, id_):
  60. self.id = id_
  61. self.hp = 10
  62. self.x = None
  63. self.y = None
  64. self.owner = None
  65. @property
  66. def pos(self):
  67. return self.x, self.y
  68. @property
  69. def owned(self):
  70. return self.owner == ME.id
  71. @property
  72. def opponent(self):
  73. return self.owner == OPPONENT.id
  74. @property
  75. def neutral(self):
  76. return self.owner == self.NO_OWNER
  77. class CultLeader(Unit):
  78. pass
  79. class Action(BaseClass):
  80. pass
  81. class ActionWait(Action):
  82. def __repr__(self):
  83. return f"<ActionWait>"
  84. def exec(self):
  85. print("WAIT")
  86. class ActionMove(Action):
  87. def __init__(self, unit, pos, message=''):
  88. self.unit = unit
  89. self.pos = pos
  90. self.message = message
  91. def __repr__(self):
  92. return f"<ActionMove: {self.unit.id} to {self.pos} ({self.message})>"
  93. def exec(self):
  94. print(f"{self.unit.id} MOVE {self.pos[0]} {self.pos[1]}")
  95. class ActionShoot(Action):
  96. def __init__(self, unit, target):
  97. self.unit = unit
  98. self.target = target
  99. def __repr__(self):
  100. return f"<ActionShoot: {self.unit.id} to {self.target.id}>"
  101. def exec(self):
  102. print(f"{self.unit.id} SHOOT {self.target.id}")
  103. class ActionConvert(Action):
  104. def __init__(self, unit, target):
  105. self.unit = unit
  106. self.target = target
  107. def __repr__(self):
  108. return f"<ActionConvert: {self.unit.id} to {self.target.id}>"
  109. def exec(self):
  110. print(f"{self.unit.id} CONVERT {self.target.id}")
  111. class Grid(BaseClass):
  112. def __init__(self, width, height):
  113. self.width = width
  114. self.height = height
  115. self.cells = []
  116. self.obstacles = []
  117. self._neighbors = {}
  118. self.index = {}
  119. self.units = {}
  120. self.round = 0
  121. self.threat = {}
  122. self.control = {}
  123. self.heat_map = {}
  124. def pre_compute(self):
  125. self.cells = [(x, y) for x in range(self.width) for y in range(self.height)]
  126. for x, y in self.cells:
  127. self._neighbors[(x, y)] = [(xn, yn) for xn, yn in [(x, y - 1), (x - 1, y), (x + 1, y), (x, y + 1)] if
  128. 0 <= xn < self.width and 0 <= yn < self.height]
  129. def reinit_round(self):
  130. self.units = {}
  131. def update_unit(self, id_, type_, hp, x, y, owner):
  132. self.units[id_] = Unit(id_) if type_ != Unit.TYPE_CULT_LEADER else CultLeader(id_)
  133. unit = self.units[id_]
  134. unit.hp = hp
  135. unit.x = x
  136. unit.y = y
  137. unit.owner = owner
  138. def update_threat_map(self):
  139. self.threat = {(x, y): 0 for x in range(self.width) for y in range(self.height)}
  140. for u in self.opponent_cultists():
  141. shooting_zone = self.zone(u.pos, Unit.SHOOTING_RANGE)
  142. for x, y in shooting_zone:
  143. dist = shooting_zone[(x, y)]
  144. if not self.line_of_sight(u.pos, (x, y)):
  145. continue
  146. threat = Unit.SHOOTING_RANGE + 1 - dist
  147. if threat > self.threat[(x, y)]:
  148. self.threat[(x, y)] = threat
  149. def update_control(self):
  150. self.control = {(x, y): 0 for x in range(self.width) for y in range(self.height)}
  151. for u in self.allied_cultists():
  152. shooting_zone = self.zone(u.pos, Unit.SHOOTING_RANGE)
  153. for x, y in shooting_zone:
  154. dist = shooting_zone[(x, y)]
  155. if not self.line_of_sight(u.pos, (x, y)):
  156. continue
  157. control = Unit.SHOOTING_RANGE + 1 - dist
  158. if control > self.control[(x, y)]:
  159. self.control[(x, y)] = control
  160. def update_heat_map(self):
  161. lines = []
  162. self.heat_map = {(x, y): 0 for x in range(self.width) for y in range(self.height)}
  163. cult_leader = self.cult_leader()
  164. for o in self.opponent_cultists():
  165. if cult_leader:
  166. lines += self.line(o.pos, cult_leader.pos)
  167. for n in self.neutrals():
  168. lines += self.line(o.pos, n.pos)
  169. for pos in lines:
  170. self.heat_map[pos] += 1
  171. def update(self):
  172. self.index = {}
  173. for unit in self.units.values():
  174. self.index[(unit.x, unit.y)] = unit
  175. self.update_threat_map()
  176. self.update_control()
  177. self.update_heat_map()
  178. def cult_leader(self):
  179. return next((u for u in self.units.values() if type(u) is CultLeader and u.owned), None)
  180. def allied_cultists(self):
  181. return [u for u in self.units.values() if type(u) is not CultLeader and u.owned]
  182. def opponent_units(self):
  183. return [u for u in self.units.values() if u.opponent]
  184. def opponent_cult_leader(self):
  185. return [u for u in self.units.values() if type(u) is CultLeader and not u.owned]
  186. def opponent_cultists(self):
  187. return [u for u in self.units.values() if type(u) is not CultLeader and u.opponent]
  188. def neutrals(self):
  189. return [u for u in self.units.values() if u.neutral]
  190. def list_actions(self):
  191. actions = Queue()
  192. k_convert_neutrals = 10
  193. k_convert_danger = 30
  194. k_shoot_opponent_cultist = 20
  195. k_shoot_opponent_cult_leader = 10
  196. k0_protect_cult_leader = 10
  197. k0_position = 50
  198. k_position_distance = 10
  199. k_position_heat = -5
  200. k_position_danger = 5
  201. cult_leader = self.cult_leader()
  202. # Conversion des neutres
  203. if cult_leader:
  204. results = self.discover(
  205. cult_leader.pos,
  206. key=(lambda pos: pos in self.index and self.index[pos].neutral),
  207. limit=5
  208. )
  209. for path, target_pos in results:
  210. target = self.index[target_pos]
  211. priority = 0
  212. priority += k_convert_neutrals * len(path)
  213. priority += k_convert_danger * sum([self.threat[pos] for pos in path])
  214. if target_pos in self.neighbors(*cult_leader.pos):
  215. action = ActionConvert(cult_leader, target)
  216. else:
  217. action = ActionMove(cult_leader, path[0], f'go convert {target.id}')
  218. actions.put(priority, action)
  219. # Attaque d'unités ennemies
  220. for a in self.allied_cultists():
  221. for u in self.opponent_cultists():
  222. shooting_distance = self.shooting_distance(a.pos, u.pos)
  223. if shooting_distance and shooting_distance < u.SHOOTING_RANGE:
  224. action = ActionShoot(a, u)
  225. priority = (k_shoot_opponent_cult_leader if type(
  226. u) is CultLeader else k_shoot_opponent_cultist) * shooting_distance
  227. actions.put(priority, action)
  228. # Position
  229. for a in self.allied_cultists():
  230. # on garde les trois points les plus chauds
  231. hot_spots = sorted(self.heat_map.items(), key=lambda p: p[1], reverse=True)[:3]
  232. results = self.discover(a.pos, key=lambda x: x in [s[0] for s in hot_spots])
  233. for path, target_pos in results:
  234. if not path:
  235. break
  236. heat = self.heat_map[target_pos]
  237. priority = k0_position
  238. priority += k_position_heat * heat
  239. priority += k_position_distance * len(path)
  240. priority += k_position_danger * sum(self.threat[p] for p in path)
  241. action = ActionMove(a, path[0], f'pos on {path[0]}')
  242. actions.put(priority, action)
  243. # Mise en sécurité du chef
  244. if cult_leader:
  245. current_threat = self.threat[cult_leader.pos]
  246. if current_threat:
  247. target = min(
  248. [n for n in self.neighbors(*cult_leader.pos) if self.can_move_on(n)],
  249. key=lambda x: self.threat[x]
  250. )
  251. action = ActionMove(cult_leader, target)
  252. priority = k0_protect_cult_leader
  253. actions.put(priority, action)
  254. return actions
  255. def in_grid(self, pos):
  256. return 0 <= pos[0] < self.width and 0 <= pos[1] < self.height
  257. def can_see_trough(self, pos):
  258. return self.in_grid(pos) and pos not in self.obstacles and pos not in self.index
  259. def can_move_on(self, pos):
  260. return self.in_grid(pos) and pos not in self.obstacles and pos not in self.index
  261. def can_discover(self, pos):
  262. return self.in_grid(pos) and pos not in self.obstacles
  263. def moving_cost(self, pos):
  264. if not self.can_move_on(pos):
  265. return -1
  266. return 1 + self.threat[pos]
  267. @staticmethod
  268. def manhattan(from_, to_):
  269. xa, ya = from_
  270. xb, yb = to_
  271. return abs(xa - xb) + abs(ya - yb)
  272. def neighbors(self, x, y):
  273. return self._neighbors[(x, y)]
  274. def zone(self, pos, radius):
  275. x0, y0 = pos
  276. zone = {}
  277. for x in range(max(x0 - radius, 0), min(x0 + radius, self.width)):
  278. for y in range(max(y0 - radius, 0), min(y0 + radius, self.height)):
  279. dist = self.manhattan(pos, (x, y))
  280. if dist <= radius:
  281. zone[(x, y)] = dist
  282. return zone
  283. @classmethod
  284. def line(cls, from_, to_):
  285. """ Implementation of bresenham's algorithm """
  286. xa, ya = from_
  287. xb, yb = to_
  288. if (xa, ya) == (xb, yb):
  289. return [(xa, ya)]
  290. # diagonal symmetry
  291. vertically_oriented = (abs(yb - ya) > abs(xb - xa))
  292. if vertically_oriented:
  293. ya, xa, yb, xb = xa, ya, xb, yb
  294. # horizontal symmetry
  295. reversed_sym = (xa > xb)
  296. if reversed_sym:
  297. xb, yb, xa, ya = xa, ya, xb, yb
  298. # angle
  299. dx, dy = xb - xa, yb - ya
  300. alpha = (abs(dy) / dx)
  301. offset = 0.0
  302. step = 1 if dy > 0 else -1
  303. result = []
  304. y_ = ya
  305. for x_ in range(xa, xb + 1):
  306. result.append((y_, x_) if vertically_oriented else (x_, y_))
  307. offset += alpha
  308. if offset > 0.5:
  309. y_ += step
  310. offset -= 1.0
  311. if reversed_sym:
  312. result.reverse()
  313. return result
  314. def line_of_sight(self, from_, to_):
  315. line = self.line(from_, to_)[1:]
  316. return line if all(self.can_see_trough(c) for c in line[:-1]) else []
  317. def shooting_distance(self, from_, to_):
  318. return len(self.line_of_sight(from_, to_))
  319. def path(self, start, target):
  320. nodes = Queue()
  321. its, break_on = 0, 400
  322. origin = PathNode(*start)
  323. nodes.put(0, origin)
  324. while nodes:
  325. current = nodes.get()
  326. if current == target:
  327. path = []
  328. previous = current
  329. while previous:
  330. if previous != start:
  331. path.insert(0, previous)
  332. previous = previous.parent
  333. return path
  334. neighbors = self.neighbors(*current)
  335. for x, y in neighbors:
  336. its += 1
  337. if its > break_on:
  338. log("<!> pathfinding broken")
  339. return None
  340. if (x, y) == current.parent:
  341. continue
  342. if not self.can_move_on((x, y)):
  343. continue
  344. moving_cost = self.moving_cost((x, y))
  345. cost = current.cost + moving_cost
  346. priority = cost + 10 * Grid.manhattan((x, y), target)
  347. node = PathNode(x, y, current)
  348. node.cost = cost
  349. nodes.put(priority, node)
  350. return None
  351. def discover(self, start, key, limit=5):
  352. paths = []
  353. nodes = []
  354. its, break_on = 0, 2000
  355. origin = PathNode(*start)
  356. nodes.append(origin)
  357. while nodes:
  358. current = nodes.pop(0) # l'ordre est important, pour que les premiers indexés soient les premiers analysés
  359. neighbors = self.neighbors(*current)
  360. for pos in neighbors:
  361. its += 1
  362. if its > break_on:
  363. log("<!> discovering ended earlier than expected")
  364. return paths
  365. if key(pos):
  366. path = []
  367. previous = current
  368. while previous:
  369. if previous != start:
  370. path.insert(0, previous)
  371. previous = previous.parent
  372. paths.append((path, pos))
  373. if len(paths) >= limit:
  374. return paths
  375. continue
  376. if pos == current.parent:
  377. continue
  378. if not self.can_move_on(pos):
  379. continue
  380. node = PathNode(*pos, current)
  381. nodes.append(node)
  382. return paths
  383. def _repr_cell(self, pos):
  384. # return f"{self.control[pos]}/{self.threat[pos]}"
  385. # return self.heat_map[pos]
  386. if pos in self.obstacles:
  387. return "X"
  388. unit = self.index.get(pos, None)
  389. if type(unit) is CultLeader:
  390. return "C"
  391. elif unit is None:
  392. return "."
  393. else:
  394. return "U"
  395. def graph(self):
  396. return "\n".join(
  397. ["|".join([str(self._repr_cell((x, y))) for x in range(self.width)]) for y in range(self.height)])
  398. # Create grid
  399. GRID = Grid(*[int(i) for i in input().split()])
  400. obstacles_input = [input() for y in range(GRID.height)]
  401. GRID.obstacles = [(x, y) for y, row in enumerate(obstacles_input) for x, val in enumerate(row) if val == 'x']
  402. GRID.pre_compute()
  403. while 1:
  404. # TODO: prendre en compte le terrain dans la ligne de visée et les déplacements
  405. log(f"start round {GRID.round}")
  406. GRID.reinit_round()
  407. for _ in range(int(input())):
  408. GRID.update_unit(*[int(j) for j in input().split()])
  409. GRID.update()
  410. actions = GRID.list_actions()
  411. # for action in actions.items:
  412. # log(f"* {action}")
  413. # print("\n" + GRID.graph(), file=sys.stderr)
  414. try:
  415. action = actions.get()
  416. except IndexError:
  417. log("no action...")
  418. action = ActionWait()
  419. log(f"exec : {action}")
  420. action.exec()
  421. GRID.round += 1