script.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. '''
  2. @author: olivier.massot, 2019
  3. '''
  4. import heapq
  5. import sys
  6. # TODO:
  7. # * add an esquive manoeuvre / try to avoid cannonballs
  8. # * consider targeting rum barrels if an ennemy is nearer
  9. # * compute first and second target instead of only one to anticipate the next move
  10. # * if an enemy is near a mine, shoot the mine instead of the ship
  11. # * compute the probabilities of presence of an ennemy on dirrefent coords at next turn
  12. debug = True
  13. def log(*msg):
  14. if debug:
  15. print(*msg, file=sys.stderr)
  16. current_turn = 0
  17. class DidNotAct(Exception):
  18. pass
  19. class Queue():
  20. def __init__(self):
  21. self.items = []
  22. def put(self, item, priority):
  23. heapq.heappush(self.items, (priority, item))
  24. def get(self):
  25. return heapq.heappop(self.items)[1]
  26. @classmethod
  27. def merge(cls, *args, reverse=False):
  28. q = cls()
  29. q.items = list(heapq.merge(*[a.items for a in args], key=lambda x: x[1], reverse=reverse))
  30. return q
  31. class InterestQueue(Queue):
  32. def __add__(self, other):
  33. self.items += other.items
  34. return self
  35. def __bool__(self):
  36. return bool(self.items)
  37. def put(self, item):
  38. heapq.heappush(self.items, item)
  39. def get(self):
  40. return heapq.heappop(self.items)
  41. @classmethod
  42. def merge(cls, *args, reverse=False):
  43. q = cls()
  44. q.items = list(heapq.merge(*[a.items for a in args], reverse=reverse))
  45. return q
  46. class ObjectivesQueue(InterestQueue):
  47. pass
  48. class Base():
  49. def __repr__(self):
  50. return f"<{self.__class__.__name__}: {self.__dict__}>"
  51. class BaseObjective(Base):
  52. def __init__(self, target):
  53. self.target = target
  54. self.interest = 0
  55. def __lt__(self, other):
  56. return self.interest < other.interest
  57. def __repr__(self):
  58. return f"<{self.__class__.__name__}({self.target.id})>"
  59. def eval(self, pos = None, d = None):
  60. self.distance = Grid.manhattan(pos, self.target.pos) if pos is not None else 0
  61. self.alignment = abs(Grid.diff_directions(Grid.direction_to(*pos, *self.target.pos), d)) if d is not None else 0
  62. self._compute_interest()
  63. def _compute_interest(self):
  64. self.interest = 7 * self.distance + 3 * self.alignment
  65. class GetBarrel(BaseObjective):
  66. def _compute_interest(self):
  67. self.interest = 6 * self.distance + 9 * self.alignment + 3 * self.target.dispersal + self.target.mine_threat ** 2 - 36 * self.target.ennemy_near
  68. class Attack(BaseObjective):
  69. def _compute_interest(self):
  70. self.interest = 7 * self.distance + 3 * self.alignment - 20 * self.target.blocked_since - 10 * self.target.same_traject_since
  71. class PathNode(tuple):
  72. def __new__(self, x, y, parent=None):
  73. n = tuple.__new__(self, (x, y))
  74. n.parent = parent
  75. n.cost = 0
  76. n.orientation = 0
  77. return n
  78. def __repr__(self):
  79. return f"<{self[0]}, {self[1]}, c:{self.cost}, o:{self.orientation}>"
  80. class Grid(Base):
  81. def __init__(self):
  82. self.w = 23
  83. self.h = 21
  84. self._neighbors = {}
  85. for x in range(-1, self.w + 1):
  86. for y in range(-1, self.h + 1):
  87. self.cache_neighbors(x, y)
  88. self.load_entities({})
  89. def __contains__(self, key):
  90. return 0 <= key[0] < self.w and 0 <= key[1] < self.h
  91. def __iter__(self):
  92. for item in ((x, y) for x in range(self.w) for y in range(self.h)):
  93. yield item
  94. # data
  95. def load_entities(self, entities):
  96. # special: mines too far from ships are not recorded but still exist
  97. ghost_mines = []
  98. if hasattr(self, "mines"):
  99. for m in self.mines:
  100. if not m.pos in [e.pos for e in entities.values() if type(e) is Mine]:
  101. if all((self.manhattan(m.pos, ship.pos) > 5) for ship in self.owned_ships):
  102. m.ghost = True
  103. ghost_mines.append(m)
  104. self.entities = entities
  105. self.index = {}
  106. self.ships = []
  107. self.owned_ships = []
  108. self.ennemy_ships = []
  109. self.ships = []
  110. self.barrels = []
  111. self.mines = []
  112. self.cannonballs = []
  113. for e in list(entities.values()) + ghost_mines:
  114. self.index[e.pos] = e
  115. type_ = type(e)
  116. if type_ is Ship:
  117. self.ships.append(e)
  118. if e.owned:
  119. self.owned_ships.append(e)
  120. else:
  121. self.ennemy_ships.append(e)
  122. elif type_ is Barrel:
  123. self.barrels.append(e)
  124. elif type_ is Mine:
  125. self.mines.append(e)
  126. elif type_ is Cannonball:
  127. self.cannonballs.append(e)
  128. for s in self.owned_ships:
  129. s.allies = [other for other in self.owned_ships if other is not s]
  130. grav_center = self.barrels_gravity_center()
  131. for b in self.barrels:
  132. b.dispersal = Grid.manhattan(grav_center, b.pos) if grav_center != None else 0
  133. b.mine_threat = any(type(self.at(*c)) is Mine for c in self.neighbors(*b.pos))
  134. b.ennemy_near = any(b.pos in e.next_area for e in self.ennemy_ships)
  135. for s in self.owned_ships:
  136. for b in self.barrels:
  137. obj = GetBarrel(b)
  138. obj.eval(s.next_pos, s.orientation)
  139. s.objectives.put(obj)
  140. for e in self.ennemy_ships:
  141. obj = Attack(e)
  142. obj.eval(s.next_pos, s.orientation)
  143. s.ennemies.put(obj)
  144. def at(self, x, y):
  145. try:
  146. return self.index[(x, y)]
  147. except KeyError:
  148. return None
  149. def collision_at(self, x, y):
  150. e = self.at(x, y)
  151. return type(e) in [Mine, Ship, Cannonball] or not (x, y) in self.__iter__()
  152. def barrels_gravity_center(self):
  153. wx, wy, wtotal = 0,0,0
  154. for b in self.barrels:
  155. wx += (b.x * b.amount)
  156. wy += (b.y * b.amount)
  157. wtotal += b.amount
  158. return (wx // wtotal, wy // wtotal) if wtotal else None
  159. def update_moving_costs(self):
  160. base_costs = {}
  161. for x in range(-1, self.w + 1):
  162. for y in range(-1, self.h + 1):
  163. if x in (0, self.w) or y in (0, self.h):
  164. base_costs[(x, y)] = 15 # borders are a little more expensive
  165. elif x in (-1, self.w + 1) or y in (-1, self.h + 1):
  166. base_costs[(x, y)] = 1000 # out of the map
  167. else:
  168. base_costs[(x, y)] = 10 # base moving cost
  169. for m in self.mines:
  170. for n in self.neighbors(*m.pos):
  171. base_costs[n] += 30
  172. for m in self.mines:
  173. base_costs[m.pos] += 1000
  174. for c in self.cannonballs:
  175. base_costs[c.pos] += (100 + (5 - c.countdown) * 200)
  176. for ship in self.ships:
  177. ship._moving_costs = base_costs
  178. for other in self.ships:
  179. if other is ship:
  180. continue
  181. dist = self.manhattan(ship.pos, other.pos)
  182. if dist > 8:
  183. continue
  184. for c in self.neighbors(*other.pos):
  185. ship._moving_costs[c] += 100 * abs(3 - other.speed)
  186. for c in self.zone(other.next_pos, 4):
  187. ship._moving_costs[c] += 20
  188. def shooting_spot(self, ship, target):
  189. shooting_spots = Queue()
  190. target_pos = target.next_pos if type(target) is Ship else target.pos
  191. for x, y in self.zone(target_pos, 10):
  192. if ship.moving_cost(x, y) > 10:
  193. continue
  194. if self.manhattan((x, y), target_pos) < 2:
  195. continue
  196. interest = 0 # the lower the better
  197. # avoid cells too close from borders
  198. if not (3 <= x <= (self.w - 3) and 3 <= y < (self.h - 3)):
  199. interest += 10
  200. # priorize spots at distance 5 from active ship
  201. interest -= 10 * abs(5 - self.manhattan((x, y), ship.pos))
  202. shooting_spots.put((x, y), interest)
  203. return shooting_spots.get()
  204. # geometrical algorithms
  205. @staticmethod
  206. def from_cubic(xu, yu, zu):
  207. return (zu, int(xu + (zu - (zu & 1)) / 2))
  208. @staticmethod
  209. def to_cubic(x, y):
  210. zu = x
  211. xu = int(y - (x - (x & 1)) / 2)
  212. yu = int(-xu - zu)
  213. return (xu, yu, zu)
  214. @staticmethod
  215. def manhattan(from_, to_):
  216. xa, ya = from_
  217. xb, yb = to_
  218. return abs(xa - xb) + abs(ya - yb)
  219. def zone(self, center, radius):
  220. buffer = frozenset([center])
  221. for _ in range(0, radius):
  222. current = buffer
  223. for x, y in current:
  224. buffer |= frozenset(self.neighbors(x, y))
  225. return [c for c in buffer if 0 <= c[0] < self.w and 0 <= c[1] < self.h]
  226. @staticmethod
  227. def closest(from_, in_):
  228. return min(in_, key=lambda x: Grid.manhattan(from_, x.pos))
  229. @staticmethod
  230. def directions(y):
  231. if y % 2 == 0:
  232. return [(1, 0), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1)]
  233. else:
  234. return [(1, 0), (1,-1), (0,-1), (-1, 0), (0, 1), (1, 1)]
  235. @staticmethod
  236. def direction_to(x0, y0, x, y):
  237. dx, dy = (x - x0), (y - y0)
  238. if dx > 0:
  239. if dy == 0:
  240. return 0
  241. elif dy > 0:
  242. return 5
  243. else:
  244. return 1
  245. elif dx < 0:
  246. if dy == 0:
  247. return 3
  248. elif dy > 0:
  249. return 4
  250. else:
  251. return 2
  252. else:
  253. if dy > 0:
  254. return 5 if y0 % 2 == 0 else 4
  255. else:
  256. return 1 if y0 % 2 == 0 else 2
  257. @staticmethod
  258. def diff_directions(d1, d2):
  259. d = d2 - d1
  260. if d <= -3:
  261. d += 6
  262. elif d > 3:
  263. d -= 6
  264. return d
  265. @staticmethod
  266. def symetry(d):
  267. return d + 3 if d < 3 else d - 3
  268. @staticmethod
  269. def abs_neighbors(x, y):
  270. return ((x + dx, y + dy) for dx, dy in Grid.directions(y))
  271. def cache_neighbors(self, xc, yc):
  272. self._neighbors[(xc, yc)] = [(x, y) for x, y in Grid.abs_neighbors(xc, yc) if 0 <= x < self.w and 0 <= y < self.h]
  273. def neighbors(self, x, y):
  274. try:
  275. return self._neighbors[(x, y)]
  276. except KeyError:
  277. self.cache_neighbors(x, y)
  278. return self._neighbors[(x, y)]
  279. def rotate(self, center, coordinates, rotations):
  280. if coordinates == [center] or rotations % 6 == 0:
  281. return coordinates
  282. x0, y0 = center
  283. xu0, yu0, zu0 = self.to_cubic(x0, y0)
  284. result = []
  285. for x, y in coordinates:
  286. xu, yu, zu = self.to_cubic(x, y)
  287. dxu, dyu, dzu = xu - xu0, yu - yu0, zu - zu0
  288. for _ in range(rotations):
  289. dxu, dyu, dzu = -dzu, -dxu, -dyu
  290. xru, yru, zru = dxu + xu0, dyu + yu0, dzu + zu0
  291. xr, yr = self.from_cubic(xru, yru, zru)
  292. result.append((xr, yr))
  293. return result
  294. # pathfinding
  295. def path(self, origin, orientat0, target, moving_costs={}, incl_start=False, limit=10000):
  296. nodes = Queue()
  297. break_on, iteration = limit, 0
  298. origin = PathNode(*origin)
  299. origin.orientation = orientat0
  300. nodes.put(origin, 0)
  301. neighbors = []
  302. while nodes:
  303. current = nodes.get()
  304. if current == target:
  305. path = []
  306. previous = current
  307. while previous:
  308. if previous != origin or incl_start:
  309. path.insert(0, previous)
  310. previous = previous.parent
  311. return path
  312. neighbors = self.neighbors(*current)
  313. for x, y in neighbors:
  314. if (x, y) == current.parent:
  315. continue
  316. iteration += 1
  317. if break_on > 0 and iteration >= break_on:
  318. return None
  319. moving_cost = moving_costs[(x, y)]
  320. if moving_cost >= 1000:
  321. continue
  322. d = Grid.direction_to(*current, x, y)
  323. diff = abs(Grid.diff_directions(current.orientation, d))
  324. if diff > 1:
  325. # change direction one degree at a time
  326. continue
  327. cost = current.cost + moving_cost + diff * 10
  328. if diff != 0 and any(moving_costs[c] >= 1000 for c in neighbors):
  329. # a direction change here is dangerous
  330. cost += 50
  331. priority = cost + 10 * Grid.manhattan((x, y), target)
  332. node = PathNode(x, y, current)
  333. node.cost = cost
  334. node.orientation = d
  335. nodes.put(node, priority)
  336. else:
  337. return None
  338. class Entity(Base):
  339. def __init__(self, ent_id):
  340. self.id = int(ent_id)
  341. self.x, self.y = 0, 0
  342. self.args = [0,0,0,0]
  343. def update(self, x, y, *args):
  344. self.x, self.y = int(x), int(y)
  345. @property
  346. def pos(self):
  347. return (self.x, self.y)
  348. def __lt__(self, other):
  349. # default comparison, used to avoid errors when used with queues and priorities are equals
  350. return self.id < other.id
  351. class Ship(Entity):
  352. MAX_SPEED = 2
  353. SCOPE = 10
  354. def __init__(self, *args, **kwargs):
  355. super().__init__(*args, **kwargs)
  356. self.x, self.y = 0, 0
  357. self.orientation = 0
  358. self.speed = 0
  359. self.stock = 0
  360. self.owned = 0
  361. self.next_cell = None
  362. self.next_pos = None
  363. self.last_fire = None
  364. self.last_mining = None
  365. self.blocked_since = 0
  366. self.same_traject_since = 0
  367. self.last_action = ""
  368. self.allies = []
  369. self._moving_costs = {}
  370. self.objectives = ObjectivesQueue()
  371. self.ennemies = ObjectivesQueue()
  372. self.objective = None
  373. self.objective_next = None
  374. self.target_ennemy = None
  375. self.path = []
  376. self.distance = 0
  377. self.alignment = 0
  378. def __repr__(self):
  379. return f"<Ship {self.id}: pos=({self.x}, {self.y}), orientation={self.orientation}, speed={self.speed}, blocked={self.blocked_since}, last_fire={self.last_fire}, next_pos={self.next_pos}, area={self.area}>"
  380. def update(self, x, y, *args):
  381. previous_state = self.state()
  382. previous_traject = self.traject()
  383. super().update(x, y)
  384. self.orientation, self.speed, self.stock, self.owned = map(int, args)
  385. self.objectives = ObjectivesQueue()
  386. self.ennemies = ObjectivesQueue()
  387. self.objective = None
  388. self.objective_next = None
  389. self.target_ennemy = None
  390. self.path = []
  391. self.area = Ship.get_area(self.x, self.y, self.orientation)
  392. self.prow, _, self.stern = self.area
  393. self.next_cell = self.get_next_cell()
  394. self.next_pos = self.get_next_pos()
  395. self.next_area = Ship.get_area(*self.next_pos, self.orientation)
  396. self.mobility_zone = list(set(self.area + self.next_area))
  397. if self.traject() != previous_traject:
  398. self.same_traject_since += 1
  399. else:
  400. self.same_traject_since = 0
  401. if self.state() == previous_state:
  402. self.blocked_since += 1
  403. else:
  404. self.blocked_since = 0
  405. def traject(self):
  406. return (self.orientation, self.speed)
  407. def state(self):
  408. return (self.x, self.y, self.orientation, self.speed)
  409. @classmethod
  410. def get_area(cls, x, y, orientation):
  411. dx, dy = Grid.directions(y)[((orientation + 3) % 6)]
  412. stern = (x + dx, y + dy)
  413. dx, dy = Grid.directions(y)[orientation]
  414. prow = (x + dx, y + dy)
  415. return [prow, (x, y), stern]
  416. def get_next_pos(self, in_=1):
  417. x, y = self.x, self.y
  418. for _ in range(in_):
  419. for _ in range(self.speed):
  420. dx, dy = Grid.directions(y)[self.orientation]
  421. x, y = x + dx, y + dy
  422. return x, y
  423. def get_next_cell(self, in_=1):
  424. x, y = self.x, self.y
  425. for _ in range(in_):
  426. dx, dy = Grid.directions(y)[self.orientation]
  427. x, y = x + dx, y + dy
  428. return x, y
  429. def in_current_direction(self, x, y):
  430. return self.orientation == Grid.direction_to(*self.pos, x, y)
  431. def moving_cost(self, x, y):
  432. return self._moving_costs[(x, y)]
  433. def move(self, *args, **kwargs):
  434. try:
  435. self._move(*args, **kwargs)
  436. return True
  437. except DidNotAct:
  438. return False
  439. def _move(self, path):
  440. if path is None:
  441. log(f"(!) broken: automove to {goto}")
  442. ship.auto_move(*goto)
  443. return
  444. elif not path:
  445. raise DidNotAct()
  446. # <--- special: avoid blocking situations
  447. if current_turn > 1 and self.blocked_since >= 1:
  448. dx, dy = Grid.directions(self.y)[((self.orientation + 1) % 6)]
  449. if self.moving_cost(self.x + dx, self.y + dy) <= 50:
  450. self.turn_left()
  451. else:
  452. self.turn_right()
  453. return
  454. # --->
  455. # speed shall be at 1 when arriving on the "flag"
  456. next_flag = next((i for i, n in enumerate(path) if n.orientation != self.orientation), None)
  457. if next_flag is None:
  458. next_flag = len(path)
  459. if next_flag < (2 * self.speed):
  460. # the end of the path or a direction change is coming
  461. diff = Grid.diff_directions(self.orientation, path[0].orientation)
  462. # <--- special: avoid the left/right hesitation when stopped
  463. if diff and not self.speed and self.last_action in ["STARBOARD", "PORT"]:
  464. self.speed_up()
  465. return
  466. # --->
  467. if diff > 0:
  468. self.turn_left()
  469. return
  470. elif diff < 0:
  471. self.turn_right()
  472. return
  473. elif self.speed > 1:
  474. self.slow_down()
  475. return
  476. else:
  477. if not self.speed or (next_flag > (2 * self.speed + 1) and self.speed < self.MAX_SPEED):
  478. # long path and no direction change coming: speed up
  479. self.speed_up()
  480. return
  481. raise DidNotAct()
  482. def fire_at_will(self, *args, **kwargs):
  483. try:
  484. self._fire_at_will(*args, **kwargs)
  485. return True
  486. except DidNotAct:
  487. return False
  488. def _fire_at_will(self, target, allies = []):
  489. if not self.can_fire():
  490. raise DidNotAct()
  491. log("** fire at will")
  492. next_positions = [target.get_next_pos(i) for i in range(1, 3)]
  493. log(f"ennemy next pos: {next_positions}")
  494. avoid = []
  495. if not self in allies:
  496. allies.append(self)
  497. for ally in allies:
  498. avoid += ally.mobility_zone
  499. log(f"avoid: {avoid}")
  500. for i, p in enumerate(next_positions):
  501. turn = i + 1
  502. if p in avoid:
  503. continue
  504. dist_p = Grid.manhattan(self.prow, p)
  505. if dist_p > self.SCOPE:
  506. continue
  507. if (1 + round(dist_p / 3)) == turn:
  508. log(f"Precision: {p}, {dist_p}, {turn}")
  509. ship.fire(*p)
  510. return
  511. next_pos = next_positions[0]
  512. dist_p = Grid.manhattan(self.prow, next_pos)
  513. if dist_p <= self.SCOPE:
  514. ship.fire(*p)
  515. return
  516. raise DidNotAct()
  517. def can_mine(self):
  518. return self.last_mining is None or (current_turn - self.last_mining) >= 4
  519. def can_fire(self):
  520. return self.last_fire is None or (current_turn - self.last_fire) >= 1
  521. # --- Basic commands
  522. def auto_move(self, x, y):
  523. self.last_action = "MOVE"
  524. print(f"MOVE {x} {y}")
  525. def speed_up(self):
  526. self.last_action = "FASTER"
  527. print("FASTER")
  528. def slow_down(self):
  529. self.last_action = "SLOWER"
  530. print("SLOWER")
  531. def turn_right(self):
  532. self.last_action = "STARBOARD"
  533. print("STARBOARD")
  534. def turn_left(self):
  535. self.last_action = "PORT"
  536. print("PORT")
  537. def wait(self):
  538. self.last_action = "WAIT"
  539. print("WAIT")
  540. def mine(self):
  541. self.last_mining = current_turn
  542. self.last_action = "MINE"
  543. print("MINE")
  544. def fire(self, x, y):
  545. self.last_fire = current_turn
  546. self.last_action = "FIRE"
  547. print(f"FIRE {x} {y}")
  548. class Barrel(Entity):
  549. def __init__(self, *args, **kwargs):
  550. super().__init__(*args, **kwargs)
  551. self.amount = 0
  552. self.dispersal = 0
  553. self.mine_threat = False
  554. self.ennemy_near = False
  555. def __repr__(self):
  556. return f"<Barrel {self.id}: pos=({self.x}, {self.y}), amount={self.amount}>"
  557. def update(self, x, y, *args):
  558. super().update(x, y)
  559. self.amount = int(args[0])
  560. class Mine(Entity):
  561. def __init__(self, *args, **kwargs):
  562. super().__init__(*args, **kwargs)
  563. self.ghost = False
  564. def __repr__(self):
  565. return f"<Mine {self.id}: pos=({self.x}, {self.y}), ghost={self.ghost}>"
  566. class Cannonball(Entity):
  567. def update(self, x, y, *args):
  568. super().update(x, y)
  569. self.sender, self.countdown = int(args[0]), int(args[1])
  570. entities = {}
  571. map_entity = {"SHIP": Ship,
  572. "BARREL": Barrel,
  573. "MINE": Mine,
  574. "CANNONBALL": Cannonball}
  575. grid = Grid()
  576. ### *** Main Loop ***
  577. while True:
  578. seen = []
  579. current_turn += 1
  580. # <--- get input
  581. my_ship_count, entity_count = int(input()), int(input())
  582. for _ in range(entity_count):
  583. ent_id, ent_type, *data = input().split()
  584. ent_id = int(ent_id)
  585. seen.append(ent_id)
  586. if not ent_id in entities:
  587. entities[ent_id] = map_entity[ent_type](ent_id)
  588. ent = entities[ent_id]
  589. ent.update(*data)
  590. entities = {k: v for k, v in entities.items() if k in seen}
  591. # --->
  592. grid.load_entities(entities)
  593. log(f"### TURN {current_turn}")
  594. # log(f"Owned Ships: {grid.owned_ships}")
  595. log(f"Ennemy Ships: {grid.ennemy_ships}")
  596. # log(f"Barrels: {grid.barrels}")
  597. # log(f"Mines: {grid.mines}")
  598. log(f"Cannonballs: {grid.cannonballs}")
  599. ### Evaluate
  600. grid.update_moving_costs()
  601. ### Acquire
  602. log("# Acquiring")
  603. # main objective
  604. while not all(s.objective for s in grid.owned_ships):
  605. try:
  606. acquired = sorted([(s, s.objectives.get()) for s in grid.owned_ships if not s.objective], key= lambda x: x[1].interest)
  607. for s, o in acquired:
  608. if not s.objective and not any(al.objective.target is o.target for al in s.allies):
  609. s.objective = o
  610. except IndexError:
  611. break
  612. # after_that objective
  613. for s in grid.owned_ships:
  614. if not s.objective:
  615. continue
  616. after_that = ObjectivesQueue()
  617. for b in grid.barrels:
  618. obj = GetBarrel(b)
  619. obj.eval(s.objective.target.pos)
  620. after_that.put(obj)
  621. if after_that:
  622. s.objective_next = after_that.get()
  623. # targetted ennemy
  624. for s in grid.owned_ships:
  625. s.target_ennemy = s.ennemies.get()
  626. for ship in grid.owned_ships:
  627. log(f"Ship {ship.id}: obj: {ship.objective}; next: {ship.objective_next}; target: {ship.target_ennemy}")
  628. ### Plan
  629. log("# Planning")
  630. for ship in grid.owned_ships:
  631. log(f"---- ship {ship.id} ---")
  632. log(f"ship: {ship}")
  633. if ship.objective:
  634. goto = ship.objective.target.pos
  635. elif ship.target_ennemy:
  636. goto = grid.shooting_spot(ship, ship.target_ennemy.target)
  637. else:
  638. log("ERROR: No target")
  639. continue
  640. log(f"goto: {goto}")
  641. ship.path = grid.path(ship.next_pos, ship.orientation, goto, ship._moving_costs, limit=6000 // len(grid.owned_ships))
  642. if ship.objective_next and ship.path:
  643. ship.path += grid.path(goto,
  644. ship.path[-1].orientation,
  645. ship.objective_next.target.pos,
  646. ship._moving_costs,
  647. limit=6000 // len(grid.owned_ships)) or []
  648. log(f"path: {ship.path}")
  649. ### Process
  650. log("# Processing")
  651. for ship in grid.owned_ships:
  652. if not ship.objective and not ship.target_ennemy:
  653. log("No target: wait")
  654. ship.wait()
  655. if ship.move(ship.path):
  656. continue
  657. # no movement was required, can fire
  658. if ship.fire_at_will(ship.target_ennemy.target, allies=grid.owned_ships):
  659. continue
  660. log("ERROR: Did not act, wait")
  661. ship.wait()