script.py 26 KB

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