main.py 24 KB

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