script.py 24 KB

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