script.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. # * if an enemy is near a mine, shoot the mine instead of the ship
  9. # * find a way to change direction without slowing down if possible
  10. # * avoid getting blocked by a side-by-side with an ennemy
  11. # * improve the 'avoid' part of the 'fire_at_will' method
  12. # * use a queue to choose the best shoot instead of a strict equality
  13. # * why do mines explode when turning around?
  14. debug = True
  15. def log(*msg):
  16. if debug:
  17. print(*msg, file=sys.stderr)
  18. current_turn = 0
  19. class CollisionAlert(Exception):
  20. pass
  21. class Queue():
  22. def __init__(self):
  23. self.items = []
  24. def __bool__(self):
  25. return bool(self.items)
  26. def __repr__(self):
  27. return str(self.items)
  28. def put(self, item, priority):
  29. heapq.heappush(self.items, (priority, item))
  30. def get(self):
  31. return heapq.heappop(self.items)[1]
  32. @classmethod
  33. def merge(cls, *args, reverse=False):
  34. q = cls()
  35. q.items = list(heapq.merge(*[a.items for a in args], key=lambda x: x[1], reverse=reverse))
  36. return q
  37. class InterestQueue(Queue):
  38. def __add__(self, other):
  39. self.items += other.items
  40. return self
  41. def put(self, item):
  42. heapq.heappush(self.items, item)
  43. def get(self):
  44. return heapq.heappop(self.items)
  45. @classmethod
  46. def merge(cls, *args, reverse=False):
  47. q = cls()
  48. q.items = list(heapq.merge(*[a.items for a in args], reverse=reverse))
  49. return q
  50. class ObjectivesQueue(InterestQueue):
  51. @classmethod
  52. def re_eval(cls, q, pos=None, d=None):
  53. new_q = cls()
  54. while q:
  55. o = q.get()
  56. o.eval(pos, d)
  57. new_q.put(o)
  58. return new_q
  59. class Base():
  60. def __repr__(self):
  61. return f"<{self.__class__.__name__}: {self.__dict__}>"
  62. class BaseObjective(Base):
  63. def __init__(self, target):
  64. self.target = target
  65. self.interest = 0
  66. def __lt__(self, other):
  67. return self.interest < other.interest
  68. def __repr__(self):
  69. return f"<{self.__class__.__name__}: target={self.target.id};int={self.interest})>"
  70. def eval(self, pos = None, d = None):
  71. self.distance = Grid.manhattan(pos, self.target.pos) if pos is not None else 0
  72. self.alignment = abs(Grid.diff_directions(Grid.direction_to(*pos, *self.target.pos), d)) if d is not None else 0
  73. self._compute_interest()
  74. def _compute_interest(self):
  75. self.interest = 7 * self.distance + 3 * self.alignment
  76. class GetBarrel(BaseObjective):
  77. def _compute_interest(self):
  78. self.interest = 6 * self.distance + 9 * self.alignment + 3 * self.target.dispersal + self.target.mine_threat ** 2 - 36 * self.target.ennemy_near
  79. class Attack(BaseObjective):
  80. def _compute_interest(self):
  81. self.interest = 7 * self.distance + 3 * self.alignment + self.target.stock // 4 - 20 * self.target.blocked_since
  82. class PathNode(tuple):
  83. def __new__(self, x, y, parent=None):
  84. n = tuple.__new__(self, (x, y))
  85. n.parent = parent
  86. n.cost = 0
  87. n.orientation = 0
  88. return n
  89. def __repr__(self):
  90. return f"<{self[0]}, {self[1]}, c:{self.cost}, o:{self.orientation}>"
  91. class Grid(Base):
  92. def __init__(self):
  93. self.w = 23
  94. self.h = 21
  95. self._neighbors = {}
  96. for x in range(-1, self.w + 1):
  97. for y in range(-1, self.h + 1):
  98. self.cache_neighbors(x, y)
  99. self.load_entities({})
  100. def __contains__(self, key):
  101. return 0 <= key[0] < self.w and 0 <= key[1] < self.h
  102. def __iter__(self):
  103. for item in ((x, y) for x in range(self.w) for y in range(self.h)):
  104. yield item
  105. # data
  106. def load_entities(self, entities):
  107. # special: mines too far from ships are not recorded but still exist
  108. ghost_mines = []
  109. if hasattr(self, "mines"):
  110. for m in self.mines:
  111. if not m.pos in [e.pos for e in entities.values() if type(e) is Mine]:
  112. if all((self.manhattan(m.pos, ship.pos) > 5) for ship in self.owned_ships):
  113. m.ghost = True
  114. ghost_mines.append(m)
  115. self.entities = entities
  116. self.index = {}
  117. self.ships = []
  118. self.owned_ships = []
  119. self.ennemy_ships = []
  120. self.ships = []
  121. self.barrels = []
  122. self.mines = []
  123. self.cannonballs = []
  124. for e in list(entities.values()) + ghost_mines:
  125. self.index[e.pos] = e
  126. type_ = type(e)
  127. if type_ is Ship:
  128. self.ships.append(e)
  129. if e.owned:
  130. self.owned_ships.append(e)
  131. else:
  132. self.ennemy_ships.append(e)
  133. elif type_ is Barrel:
  134. self.barrels.append(e)
  135. elif type_ is Mine:
  136. self.mines.append(e)
  137. elif type_ is Cannonball:
  138. self.cannonballs.append(e)
  139. for s in self.owned_ships:
  140. s.allies = [other for other in self.owned_ships if other is not s]
  141. for s in self.ennemy_ships:
  142. s.allies = [other for other in self.ennemy_ships if other is not s]
  143. self.update_moving_costs()
  144. grav_center = self.barrels_gravity_center()
  145. for b in self.barrels:
  146. b.dispersal = Grid.manhattan(grav_center, b.pos) if grav_center != None else 0
  147. b.mine_threat = any(type(self.at(*c)) is Mine for c in self.neighbors(*b.pos))
  148. b.ennemy_near = any(b.pos in e.next_area for e in self.ennemy_ships)
  149. for s in self.owned_ships:
  150. s._can_move = {c: (s.moving_cost(*c) < 1000) for c in [s.front, s.front_left, s.left, s.front_right,
  151. s.right, s.back_left, s.back_right]}
  152. s.objectives = ObjectivesQueue()
  153. s.ennemies = ObjectivesQueue()
  154. for b in self.barrels:
  155. obj = GetBarrel(b)
  156. obj.eval(s.next_pos if s.speed else s.prow, s.orientation)
  157. s.objectives.put(obj)
  158. for e in self.ennemy_ships:
  159. obj = Attack(e)
  160. obj.eval(s.next_pos, s.orientation)
  161. s.ennemies.put(obj)
  162. def at(self, x, y):
  163. try:
  164. return self.index[(x, y)]
  165. except KeyError:
  166. return None
  167. def collision_at(self, x, y):
  168. e = self.at(x, y)
  169. return type(e) in [Mine, Ship, Cannonball] or not (x, y) in self.__iter__()
  170. def barrels_gravity_center(self):
  171. wx, wy, wtotal = 0,0,0
  172. for b in self.barrels:
  173. wx += (b.x * b.amount)
  174. wy += (b.y * b.amount)
  175. wtotal += b.amount
  176. return (wx // wtotal, wy // wtotal) if wtotal else None
  177. def update_moving_costs(self):
  178. base_costs = {}
  179. self.collisions = []
  180. for x in range(-1, self.w + 1):
  181. for y in range(-1, self.h + 1):
  182. base_costs[(x, y)] = 10 # base moving cost
  183. for x, y in base_costs:
  184. if x in (-1, self.w + 1) or y in (-1, self.h):
  185. base_costs[(x, y)] = 1000 # out of the map
  186. elif x in (0, self.w - 1) or y in (0, self.h - 1):
  187. base_costs[(x, y)] = 15 # borders are a little more expensive
  188. for m in self.mines:
  189. for n in self.neighbors(*m.pos):
  190. base_costs[n] += 30
  191. for m in self.mines:
  192. base_costs[m.pos] += 1000
  193. for c in self.cannonballs:
  194. base_costs[c.pos] += (100 + (5 - c.countdown) * 200)
  195. for ship in self.ships:
  196. ship._moving_costs = {}
  197. ship._moving_costs.update(base_costs)
  198. for other in self.ships:
  199. if other is ship:
  200. continue
  201. dist = self.manhattan(ship.pos, other.pos)
  202. if dist > 8:
  203. continue
  204. if not other.speed:
  205. for c in other.area:
  206. ship._moving_costs[c] += 1000
  207. else:
  208. for c in self.neighbors(*other.pos):
  209. ship._moving_costs[c] += 100 * abs(3 - other.speed)
  210. for c in self.zone(other.next_pos, 4):
  211. ship._moving_costs[c] += 20
  212. def shooting_spot(self, ship, target):
  213. shooting_spots = Queue()
  214. target_pos = target.next_pos if type(target) is Ship else target.pos
  215. for x, y in self.zone(target_pos, 10):
  216. if ship.moving_cost(x, y) > 100:
  217. continue
  218. if self.manhattan((x, y), target_pos) <= 2:
  219. continue
  220. interest = 0 # the lower the better
  221. interest += ship.moving_cost(x, y)
  222. # avoid cells too close from borders
  223. if not 3 < x < (self.w - 3):
  224. interest += 50
  225. if not 3 <= y < (self.h - 3):
  226. interest += 50
  227. diff = abs(Grid.direction_to(*ship.prow, x, y))
  228. if diff > 1:
  229. interest += 15 * abs(diff)
  230. # priorize spots at distance 5 from active ship
  231. interest += (10 * abs(5 - self.manhattan((x, y), ship.pos)))
  232. shooting_spots.put((x, y), interest)
  233. return shooting_spots.get()
  234. # geometrical algorithms
  235. @staticmethod
  236. def from_cubic(xu, yu, zu):
  237. return (zu, int(xu + (zu - (zu & 1)) / 2))
  238. @staticmethod
  239. def to_cubic(x, y):
  240. zu = x
  241. xu = int(y - (x - (x & 1)) / 2)
  242. yu = int(-xu - zu)
  243. return (xu, yu, zu)
  244. @staticmethod
  245. def manhattan(from_, to_):
  246. xa, ya = from_
  247. xb, yb = to_
  248. return abs(xa - xb) + abs(ya - yb)
  249. def zone(self, center, radius):
  250. buffer = frozenset([center])
  251. for _ in range(0, radius):
  252. current = buffer
  253. for x, y in current:
  254. buffer |= frozenset(self.abs_neighbors(x, y))
  255. return [c for c in buffer if 0 <= c[0] < self.w and 0 <= c[1] < self.h]
  256. @staticmethod
  257. def closest(from_, in_):
  258. return min(in_, key=lambda x: Grid.manhattan(from_, x.pos))
  259. @staticmethod
  260. def directions(y):
  261. if y % 2 == 0:
  262. return [(1, 0), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1)]
  263. else:
  264. return [(1, 0), (1,-1), (0,-1), (-1, 0), (0, 1), (1, 1)]
  265. @staticmethod
  266. def direction_to(x0, y0, x, y):
  267. dx, dy = (x - x0), (y - y0)
  268. if dx > 0:
  269. if dy == 0:
  270. return 0
  271. elif dy > 0:
  272. return 5
  273. else:
  274. return 1
  275. elif dx < 0:
  276. if dy == 0:
  277. return 3
  278. elif dy > 0:
  279. return 4
  280. else:
  281. return 2
  282. else:
  283. if dy > 0:
  284. return 5 if y0 % 2 == 0 else 4
  285. else:
  286. return 1 if y0 % 2 == 0 else 2
  287. @staticmethod
  288. def add_directions(d1, d2):
  289. d = d2 + d1
  290. if d < 0:
  291. d += 6
  292. elif d > 5:
  293. d -= 6
  294. return d
  295. @staticmethod
  296. def diff_directions(d1, d2):
  297. d = d2 - d1
  298. if d <= -3:
  299. d += 6
  300. elif d > 3:
  301. d -= 6
  302. return d
  303. @staticmethod
  304. def next_cell(x, y, d, repeat=1):
  305. for _ in range(repeat):
  306. dx, dy = Grid.directions(y)[d]
  307. x, y = x + dx, y + dy
  308. return x, y
  309. @staticmethod
  310. def symetry(d):
  311. return d + 3 if d < 3 else d - 3
  312. @staticmethod
  313. def abs_neighbors(x, y):
  314. return ((x + dx, y + dy) for dx, dy in Grid.directions(y))
  315. def cache_neighbors(self, xc, yc):
  316. 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]
  317. def neighbors(self, x, y):
  318. try:
  319. return self._neighbors[(x, y)]
  320. except KeyError:
  321. self.cache_neighbors(x, y)
  322. return self._neighbors[(x, y)]
  323. def rotate(self, center, coordinates, rotations):
  324. if coordinates == [center] or rotations % 6 == 0:
  325. return coordinates
  326. x0, y0 = center
  327. xu0, yu0, zu0 = self.to_cubic(x0, y0)
  328. result = []
  329. for x, y in coordinates:
  330. xu, yu, zu = self.to_cubic(x, y)
  331. dxu, dyu, dzu = xu - xu0, yu - yu0, zu - zu0
  332. for _ in range(rotations):
  333. dxu, dyu, dzu = -dzu, -dxu, -dyu
  334. xru, yru, zru = dxu + xu0, dyu + yu0, dzu + zu0
  335. xr, yr = self.from_cubic(xru, yru, zru)
  336. result.append((xr, yr))
  337. return result
  338. # pathfinding
  339. def path(self, start, d0, target, moving_costs={}, inertia=0, incl_start=False, limit=10000):
  340. nodes = Queue()
  341. break_on, iteration = limit, 0
  342. inertia_path = []
  343. effective_start = start
  344. for _ in range(inertia):
  345. effective_start = self.next_cell(*effective_start, d0)
  346. n = PathNode(*effective_start)
  347. n.orientation = d0
  348. inertia_path.append(n)
  349. origin = PathNode(*effective_start)
  350. origin.orientation = d0
  351. nodes.put(origin, 0)
  352. neighbors = []
  353. while nodes:
  354. current = nodes.get()
  355. if current == target:
  356. path = []
  357. previous = current
  358. while previous:
  359. if previous != origin or incl_start:
  360. path.insert(0, previous)
  361. previous = previous.parent
  362. return inertia_path + path
  363. neighbors = self.neighbors(*current)
  364. for x, y in neighbors:
  365. if (x, y) == current.parent:
  366. continue
  367. iteration += 1
  368. if break_on > 0 and iteration >= break_on:
  369. return None
  370. moving_cost = moving_costs.get((x, y), 1000)
  371. if moving_cost >= 1000:
  372. continue
  373. d = Grid.direction_to(*current, x, y)
  374. diff = abs(Grid.diff_directions(current.orientation, d))
  375. if diff > 1:
  376. # change direction one degree at a time
  377. continue
  378. if any(moving_costs.get(c, 1000) >= 1000 for c in Ship.get_area(x, y, d)):
  379. continue
  380. cost = current.cost + moving_cost + diff * 10
  381. if (x, y) == effective_start and d == d0:
  382. # prefer to go right at start
  383. cost -= 10
  384. priority = cost + 10 * Grid.manhattan((x, y), target)
  385. node = PathNode(x, y, current)
  386. node.cost = cost
  387. node.orientation = d
  388. nodes.put(node, priority)
  389. else:
  390. return None
  391. class Entity(Base):
  392. def __init__(self, ent_id):
  393. self.id = int(ent_id)
  394. self.x, self.y = 0, 0
  395. self.args = [0,0,0,0]
  396. def update(self, x, y, *args):
  397. self.x, self.y = int(x), int(y)
  398. @property
  399. def pos(self):
  400. return (self.x, self.y)
  401. def __lt__(self, other):
  402. # default comparison, used to avoid errors when used with queues and priorities are equals
  403. return self.id < other.id
  404. class Position(Base):
  405. def __init__(self, pos, d, speed):
  406. self.pos = pos
  407. self.d = d
  408. self.speed = speed
  409. class Ship(Entity):
  410. MAX_SPEED = 2
  411. SCOPE = 10
  412. SLOW_DOWN = 1
  413. SPEED_UP = 2
  414. TURN_LEFT = 3
  415. TURN_RIGHT = 4
  416. MOVES = [SLOW_DOWN, SPEED_UP, TURN_LEFT, TURN_RIGHT]
  417. COMMANDS = {SLOW_DOWN: "SLOWER", SPEED_UP: "FASTER", TURN_LEFT: "PORT", TURN_RIGHT: "STARBOARD"}
  418. def __init__(self, *args, **kwargs):
  419. super().__init__(*args, **kwargs)
  420. self.x, self.y = 0, 0
  421. self.orientation = 0
  422. self.speed = 0
  423. self.stock = 0
  424. self.owned = 0
  425. self.next_cell = None
  426. self.next_pos = None
  427. self.last_fire = None
  428. self.last_mining = None
  429. self.blocked_since = 0
  430. self.same_traject_since = 0
  431. self.last_action = ""
  432. self.allies = []
  433. self._moving_costs = {}
  434. self.objectives = ObjectivesQueue()
  435. self.ennemies = ObjectivesQueue()
  436. self.objective = None
  437. self.objectives_next = []
  438. self.target_ennemy = None
  439. self.path = []
  440. self.distance = 0
  441. self.alignment = 0
  442. def __repr__(self):
  443. 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}>"
  444. def update(self, x, y, *args):
  445. previous_state = self.state()
  446. previous_traject = self.traject()
  447. super().update(x, y)
  448. self.orientation, self.speed, self.stock, self.owned = map(int, args)
  449. self.objectives = ObjectivesQueue()
  450. self.ennemies = ObjectivesQueue()
  451. self.objective = None
  452. self.objectives_next = []
  453. self.target_ennemy = None
  454. self.goto = None
  455. self.path = []
  456. self.area = Ship.get_area(self.x, self.y, self.orientation)
  457. self.prow, _, self.stern = self.area
  458. self.next_cell = self.get_next_cell()
  459. self.next_pos = self.get_next_pos()
  460. self.next_area = Ship.get_area(*self.next_pos, self.orientation)
  461. self.front = Grid.next_cell(*self.prow, self.orientation)
  462. self.front_left = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, 1))
  463. self.left = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, 2))
  464. self.front_right = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, -1))
  465. self.right = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, -2))
  466. self.back_left = Grid.next_cell(*self.stern, Grid.add_directions(self.orientation, 1))
  467. self.back_right = Grid.next_cell(*self.stern, Grid.add_directions(self.orientation, -1))
  468. self._can_move = {}
  469. self.mobility_zone = list(set(self.area + self.next_area))
  470. if self.traject() != previous_traject:
  471. self.same_traject_since += 1
  472. else:
  473. self.same_traject_since = 0
  474. if self.state() == previous_state:
  475. self.blocked_since += 1
  476. else:
  477. self.blocked_since = 0
  478. def traject(self):
  479. return (self.orientation, self.speed)
  480. def state(self):
  481. return (self.x, self.y, self.orientation, self.speed)
  482. @classmethod
  483. def get_pos_in(cls, current, speed, orientation, in_=1):
  484. return Grid.next_cell(*current, orientation, repeat=speed * in_)
  485. @classmethod
  486. def get_area(cls, x, y, orientation):
  487. prow = Grid.next_cell(x, y, orientation)
  488. stern = Grid.next_cell(x, y, Grid.add_directions(orientation, 3))
  489. return [prow, (x, y), stern]
  490. def get_next_pos(self, in_=1):
  491. return self.get_pos_in(self.pos, self.speed, self.orientation, in_)
  492. def next_pos_proba(self, in_=1):
  493. # guess next positions
  494. positions = {0: [Position(self.pos, self.orientation, self.speed)]}
  495. for i in range(in_):
  496. positions[i + 1] = []
  497. for p in positions[i]:
  498. pos, d, speed = p.pos, p.d, p.speed
  499. # next pos with inertia
  500. inertia = Grid.next_cell(*pos, d, repeat=speed)
  501. # wait (or fire or mine)
  502. positions[i + 1].append(Position(inertia, d, speed))
  503. # turn left
  504. positions[i + 1].append(Position(inertia, Grid.add_directions(d, 1), speed))
  505. # turn right
  506. positions[i + 1].append(Position(inertia, Grid.add_directions(d, -1), speed))
  507. # speed up
  508. if speed < self.MAX_SPEED:
  509. positions[i + 1].append(Position(Grid.next_cell(*pos, d, repeat=speed + 1), d, speed + 1))
  510. # slow down
  511. if speed > 1:
  512. positions[i + 1].append(Position(Grid.next_cell(*pos, d, repeat=speed - 1), d, speed - 1))
  513. # we voluntary ignore the case where a ship at speed 1 would slow down,
  514. # as it is not expected to be a standard behaviour for a ship
  515. # agregate
  516. proba = {}
  517. for i, plst in positions.items():
  518. proba[i] = {}
  519. for p in plst:
  520. for c in Ship.get_area(*p.pos, p.d):
  521. if self.moving_cost(*c) >= 1000:
  522. continue
  523. proba[i][c] = proba[i].get(c, 0) + 10
  524. # involve the moving cost
  525. for i in proba:
  526. for c in proba[i]:
  527. proba[i][c] -= (self.moving_cost(*c) // 2)
  528. # if ship is blocked, current area is more accurate
  529. for c in self.area:
  530. proba[i][c] = proba[i].get(c, 0) + 40 * self.blocked_since
  531. return proba
  532. def guess_next_positions(self, in_=3):
  533. proba = self.next_pos_proba(in_)
  534. best = {}
  535. for i in proba:
  536. best[i] = max(proba[i].items(), key=lambda x: x[1])[0]
  537. return best
  538. def get_next_cell(self, in_=1):
  539. return Grid.next_cell(self.x, self.y, self.orientation, repeat=in_)
  540. def in_current_direction(self, x, y):
  541. return self.orientation == Grid.direction_to(*self.pos, x, y)
  542. def moving_cost(self, x, y):
  543. return self._moving_costs.get((x, y), 1000)
  544. def can_turn_left(self):
  545. return self._can_move[self.left] and self._can_move[self.back_right]
  546. def can_turn_right(self):
  547. return self._can_move[self.right] and self._can_move[self.back_left]
  548. def can_move_fwd(self):
  549. return self._can_move[self.front]
  550. def can_move(self):
  551. return self.can_move_fwd() or self.can_turn_left() or self.can_turn_left()
  552. def move(self, path):
  553. if path is None:
  554. if self.can_move():
  555. log(f"(!) broken: automove to {self.goto}")
  556. self.auto_move(*self.goto)
  557. return True
  558. else:
  559. return False
  560. elif not path:
  561. return False
  562. planned = self._plan_move(path)
  563. next_move = planned
  564. available_moves = [next_move] + [m for m in Ship.MOVES if m != planned]
  565. for move in available_moves:
  566. new_speed = self.speed
  567. new_orientation = self.orientation
  568. if move == Ship.SPEED_UP:
  569. new_speed += 1
  570. elif move == Ship.SLOW_DOWN:
  571. new_speed -= 1
  572. elif move == Ship.TURN_LEFT:
  573. new_orientation = Grid.add_directions(self.orientation, 1)
  574. elif move == Ship.TURN_RIGHT:
  575. new_orientation = Grid.add_directions(self.orientation, -1)
  576. new_pos = self.get_next_cell(new_speed)
  577. new_area = self.get_area(*new_pos, new_orientation)
  578. # special: extra-grid cells are not consider as collisions since a part of the ship can go there
  579. if any((self.moving_cost(*c) >= 1000 and c in grid) for c in new_area):
  580. log(f"/!\ Danger: planned move <{Ship.COMMANDS[move]}> would lead to collision")
  581. else:
  582. next_move = move
  583. break
  584. else:
  585. log("* No collision-free move was found, go to the initial one")
  586. if next_move == Ship.SPEED_UP:
  587. self.speed_up()
  588. elif next_move == Ship.SLOW_DOWN:
  589. self.slow_down()
  590. elif next_move == Ship.TURN_LEFT:
  591. self.turn_left()
  592. elif next_move == Ship.TURN_RIGHT:
  593. self.turn_right()
  594. else:
  595. return False
  596. return True
  597. def _plan_move(self, path):
  598. # flags represent direction changes or end of the path
  599. last_flag = len(path) - 1
  600. next_flag = next((i for i, n in enumerate(path) if n.orientation != self.orientation), last_flag)
  601. afternext_flag = next((i for i, n in enumerate(path[next_flag:]) if n.orientation != path[next_flag].orientation), last_flag)
  602. if not self.speed:
  603. diff = Grid.diff_directions(self.orientation, path[0].orientation)
  604. log(self.id, self.speed, self.can_move_fwd(), self.can_turn_left(), self.can_turn_right())
  605. if diff > 0 and self.last_action == "STARBOARD" or diff < 0 and self.last_action == "PORT":
  606. # special: avoid the starting hesitation
  607. return Ship.SPEED_UP
  608. if diff and next_flag == 0:
  609. # start, with a direction change
  610. if diff > 0:
  611. if self.can_turn_left():
  612. return Ship.TURN_LEFT
  613. elif diff < 0:
  614. if self.can_turn_right():
  615. return Ship.TURN_RIGHT
  616. # start straight
  617. if self.can_move_fwd():
  618. return Ship.SPEED_UP
  619. elif self.speed == self.MAX_SPEED:
  620. if self.speed == next_flag and afternext_flag >= (next_flag + 2): # there is at least one straight cell after this drift
  621. # drift
  622. diff = Grid.diff_directions(self.orientation, path[next_flag].orientation)
  623. if diff > 0:
  624. return Ship.TURN_LEFT
  625. elif diff < 0:
  626. return Ship.TURN_RIGHT
  627. if (self.speed + 1) >= next_flag:
  628. # next direction change or target will be passed at current speed
  629. return Ship.SLOW_DOWN
  630. elif self.speed == 1:
  631. if self.speed == next_flag:
  632. diff = Grid.diff_directions(self.orientation, path[next_flag].orientation)
  633. if diff > 0:
  634. return Ship.TURN_LEFT
  635. elif diff < 0:
  636. return Ship.TURN_RIGHT
  637. elif next_flag > 3 or (next_flag > 2 and afternext_flag >= (next_flag + 2)):
  638. return Ship.SPEED_UP
  639. return None
  640. def fire_at_will(self, *args, **kwargs):
  641. return self._fire_at_will(*args, **kwargs)
  642. def _fire_at_will(self, target, allies = []):
  643. if not self.can_fire():
  644. return False
  645. avoid = []
  646. if not self in allies:
  647. allies.append(self)
  648. for ally in allies:
  649. avoid += ally.mobility_zone
  650. next_positions = target.guess_next_positions(in_=4)
  651. for t, next_pos in next_positions.items():
  652. dist = Grid.manhattan(self.prow, next_pos)
  653. if dist > self.SCOPE:
  654. continue
  655. if next_pos in avoid:
  656. continue
  657. dt = 1 + (1 + round(dist / 3)) # time for the cannonball to reach this pos (including fire turn)
  658. if dt == t:
  659. log(f"[x] precise shoot: dt={dt}, pos={next_pos}")
  660. ship.fire(*next_pos)
  661. return True
  662. # give a try
  663. next_pos = next_positions[2]
  664. if not next_pos in avoid:
  665. dist_p = Grid.manhattan(self.prow, next_pos)
  666. if dist_p <= self.SCOPE:
  667. ship.fire(*next_pos)
  668. return True
  669. return False
  670. def can_mine(self):
  671. return self.last_mining is None or (current_turn - self.last_mining) >= 4
  672. def can_fire(self):
  673. return self.last_fire is None or (current_turn - self.last_fire) >= 1
  674. # --- Basic commands
  675. def _act(self, cmd, *args):
  676. self.last_action = cmd
  677. output = " ".join([cmd] + [str(a) for a in args])
  678. log(f"ship {self.id}: {output}")
  679. print(output)
  680. def auto_move(self, x, y):
  681. self._act("MOVE", x, y)
  682. def speed_up(self):
  683. self._act("FASTER")
  684. def slow_down(self):
  685. self._act("SLOWER")
  686. def turn_right(self):
  687. self._act("STARBOARD")
  688. def turn_left(self):
  689. self._act("PORT")
  690. def wait(self):
  691. self._act("WAIT")
  692. def mine(self):
  693. self.last_mining = current_turn
  694. self._act("MINE")
  695. def fire(self, x, y):
  696. self.last_fire = current_turn
  697. self._act("FIRE", x, y)
  698. class Barrel(Entity):
  699. def __init__(self, *args, **kwargs):
  700. super().__init__(*args, **kwargs)
  701. self.amount = 0
  702. self.dispersal = 0
  703. self.mine_threat = False
  704. self.ennemy_near = False
  705. def __repr__(self):
  706. return f"<Barrel {self.id}: pos=({self.x}, {self.y}), amount={self.amount}>"
  707. def update(self, x, y, *args):
  708. super().update(x, y)
  709. self.amount = int(args[0])
  710. class Mine(Entity):
  711. def __init__(self, *args, **kwargs):
  712. super().__init__(*args, **kwargs)
  713. self.ghost = False
  714. def __repr__(self):
  715. return f"<Mine {self.id}: pos=({self.x}, {self.y}), ghost={self.ghost}>"
  716. class Cannonball(Entity):
  717. def update(self, x, y, *args):
  718. super().update(x, y)
  719. self.sender, self.countdown = int(args[0]), int(args[1])
  720. entities = {}
  721. map_entity = {"SHIP": Ship,
  722. "BARREL": Barrel,
  723. "MINE": Mine,
  724. "CANNONBALL": Cannonball}
  725. grid = Grid()
  726. ### *** Main Loop ***
  727. while True:
  728. seen = []
  729. current_turn += 1
  730. # <--- get input
  731. my_ship_count, entity_count = int(input()), int(input())
  732. previous_ent, entities = grid.entities, {}
  733. for _ in range(entity_count):
  734. ent_id, ent_type, *data = input().split()
  735. ent_id = int(ent_id)
  736. entities[ent_id] = grid.entities.get(ent_id, map_entity[ent_type](ent_id))
  737. entities[ent_id].update(*data)
  738. # --->
  739. grid.load_entities(entities)
  740. log(f"### TURN {current_turn}")
  741. # log(f"Owned Ships: {grid.owned_ships}")
  742. log(f"Ennemy Ships: {grid.ennemy_ships}")
  743. log(f"Barrels: {grid.barrels}")
  744. # log(f"Mines: {grid.mines}")
  745. log(f"Cannonballs: {grid.cannonballs}")
  746. max_it = 6000 // len(grid.owned_ships)
  747. ### Acquire
  748. log("# Acquiring")
  749. # main objective
  750. while not all(s.objective for s in grid.owned_ships):
  751. try:
  752. acquired = sorted([(s, s.objectives.get()) for s in grid.owned_ships if not s.objective], key= lambda x: x[1].interest)
  753. for s, o in acquired:
  754. if not s.objective and not any(al.objective.target is o.target for al in s.allies if al.objective):
  755. s.objective = o
  756. except IndexError:
  757. break
  758. # targetted ennemy
  759. for s in grid.owned_ships:
  760. s.target_ennemy = s.ennemies.get()
  761. ### Plan
  762. log("# Planning")
  763. for ship in grid.owned_ships:
  764. it_consumed = 0
  765. if ship.objective:
  766. ship.goto = ship.objective.target.pos
  767. elif ship.target_ennemy:
  768. ship.goto = grid.shooting_spot(ship, ship.target_ennemy.target)
  769. else:
  770. log("ERROR: No target")
  771. continue
  772. ship.path = grid.path(ship.pos,
  773. ship.orientation,
  774. ship.goto,
  775. moving_costs=ship._moving_costs,
  776. inertia=ship.speed,
  777. limit=(max_it - it_consumed))
  778. if ship.objective and ship.path:
  779. while ship.objectives and len(ship.path) < 10:
  780. pos, d = ship.path[-1], ship.path[-1].orientation
  781. ship.objectives = ObjectivesQueue.re_eval(ship.objectives, pos, d)
  782. current_obj = ship.objectives.get()
  783. ship.objectives_next.append(current_obj)
  784. new_path = grid.path(pos, d,
  785. current_obj.target.pos,
  786. ship._moving_costs,
  787. limit=(max_it - it_consumed)) or []
  788. if new_path:
  789. ship.path += new_path
  790. else:
  791. break
  792. for ship in grid.owned_ships:
  793. log(f"---- ship {ship.id} ---")
  794. log(f"ship: {ship}")
  795. log(f"obj: {ship.objective}; next: {ship.objectives_next}")
  796. log(f"target: {ship.target_ennemy}")
  797. log(f"goto: {ship.goto}")
  798. log(f"path: {ship.path}")
  799. ### Process
  800. log("# Processing")
  801. for ship in grid.owned_ships:
  802. if not ship.objective and not ship.target_ennemy:
  803. log("No target: wait")
  804. ship.wait()
  805. if ship.move(ship.path):
  806. continue
  807. # no movement was required, can fire
  808. if ship.fire_at_will(ship.target_ennemy.target, allies=grid.owned_ships):
  809. continue
  810. log("ERROR: Did not act, wait")
  811. ship.wait()