script.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  1. '''
  2. @author: olivier.massot, 2019
  3. '''
  4. import heapq
  5. import sys
  6. import time
  7. # TODO:
  8. # * find a way to change direction without slowing down if possible
  9. # * Try to integer extra steps into the path algo, instead of adding independents paths
  10. # * Increase the shooting rate in the second part of the game (no barrels left)
  11. # * get_shooting_spots: try to intercept ennemy
  12. # * make a difference between moving cost, mines, cannonballs, out of grid and other ships
  13. # * automove: priorize
  14. # Enhancements
  15. # * interception trajectories
  16. # * paths with extra-steps
  17. # * Part 1: Speed up
  18. # * Part 2: Increase shooting rate
  19. # * If an owned ship has the max stock of rum and no barrels are left: runaway!
  20. debug = True
  21. t0 = time.time()
  22. def log(*msg):
  23. if debug:
  24. print("{} - ".format(str(time.time() - t0)[1:5]), *msg, file=sys.stderr)
  25. current_turn = 0
  26. class Queue():
  27. def __init__(self):
  28. self.items = []
  29. def __bool__(self):
  30. return bool(self.items)
  31. def __repr__(self):
  32. return str(self.items)
  33. def put(self, item, priority):
  34. heapq.heappush(self.items, (priority, item))
  35. def fput(self, item, priority):
  36. while priority in [p for p, _ in self.items]:
  37. priority += 1
  38. self.put(item, priority)
  39. def get(self):
  40. return heapq.heappop(self.items)[1]
  41. @classmethod
  42. def merge(cls, *args, reverse=False):
  43. q = cls()
  44. q.items = list(heapq.merge(*[a.items for a in args], key=lambda x: x[1], reverse=reverse))
  45. return q
  46. class InterestQueue(Queue):
  47. def __add__(self, other):
  48. self.items += other.items
  49. return self
  50. def put(self, item):
  51. heapq.heappush(self.items, item)
  52. def get(self):
  53. return heapq.heappop(self.items)
  54. @classmethod
  55. def merge(cls, *args, reverse=False):
  56. q = cls()
  57. q.items = list(heapq.merge(*[a.items for a in args], reverse=reverse))
  58. return q
  59. class ObjectivesQueue(InterestQueue):
  60. @classmethod
  61. def re_eval(cls, q, pos=None, d=None):
  62. new_q = cls()
  63. while q:
  64. o = q.get()
  65. o.eval(pos, d)
  66. new_q.put(o)
  67. return new_q
  68. class Base():
  69. def __repr__(self):
  70. return f"<{self.__class__.__name__}: {self.__dict__}>"
  71. class BaseObjective(Base):
  72. def __init__(self, target):
  73. self.target = target
  74. self.interest = 0
  75. def __lt__(self, other):
  76. return self.interest < other.interest
  77. def __repr__(self):
  78. return f"<{self.__class__.__name__}: target={self.target.id};int={self.interest})>"
  79. def _pre_eval(self, pos = None, d = None):
  80. self.distance = Grid.manhattan(pos, self.target.pos) if pos is not None else 0
  81. self.alignment = abs(Grid.diff_directions(Grid.direction_to(*pos, *self.target.pos), d)) if d is not None else 0
  82. def eval(self, pos = None, d = None):
  83. self._pre_eval(pos, d)
  84. self._compute_interest()
  85. def _compute_interest(self):
  86. self.interest = 7 * self.distance + 3 * self.alignment
  87. class GetBarrel(BaseObjective):
  88. def _pre_eval(self, pos = None, d = None):
  89. super()._pre_eval(pos, d)
  90. self.ennemy_near = any(Grid.manhattan(e.next_pos, self.target.pos) < self.distance for e in grid.ennemy_ships)
  91. def _compute_interest(self):
  92. self.interest = 6 * self.distance + 9 * self.alignment + 3 * self.target.dispersal + self.target.mine_threat * 2 + 12 * self.ennemy_near
  93. if self.distance <= 2 and self.alignment > 1:
  94. # dead angle
  95. self.interest += 36
  96. class Attack(BaseObjective):
  97. def _compute_interest(self):
  98. self.interest = 7 * self.distance + 3 * self.alignment + self.target.stock // 4 - 20 * self.target.blocked_since
  99. class PathNode(tuple):
  100. def __new__(self, x, y, parent=None):
  101. n = tuple.__new__(self, (x, y))
  102. n.parent = parent
  103. n.cost = 0
  104. n.orientation = 0
  105. return n
  106. def __repr__(self):
  107. return f"<{self[0]}, {self[1]}, c:{self.cost}, o:{self.orientation}>"
  108. class Grid(Base):
  109. w = 23
  110. h = 21
  111. _neighbors = {}
  112. _next_cell = {}
  113. def __init__(self):
  114. self.load_entities({})
  115. @classmethod
  116. def preload(cls):
  117. cls._neighbors = {}
  118. for x in range(-1, cls.w + 1):
  119. for y in range(-1, cls.h + 1):
  120. cls.cache_neighbors(x, y)
  121. cls._next_cell = {}
  122. for x in range(0, cls.w):
  123. for y in range(0, cls.h):
  124. cls.cache_next_cell(x, y)
  125. for x in range(0, cls.w):
  126. for y in range(0, cls.h):
  127. Ship.cache_area(x, y)
  128. @classmethod
  129. def contains(cls, x, y):
  130. return 0 <= x < cls.w and 0 <= y < cls.h
  131. def __contains__(self, key):
  132. return self.contains(*key)
  133. def __iter__(self):
  134. for item in ((x, y) for x in range(self.w) for y in range(self.h)):
  135. yield item
  136. # data
  137. def load_entities(self, entities):
  138. # special: mines too far from ships are not recorded but still exist
  139. ghost_mines = []
  140. if hasattr(self, "mines"):
  141. for m in self.mines:
  142. if not m.id in entities:
  143. if all((self.manhattan(m.pos, ship.pos) > 5) for ship in self.owned_ships):
  144. m.ghost = True
  145. ghost_mines.append(m)
  146. self.entities = entities
  147. self.index = {}
  148. self.ships = []
  149. self.owned_ships = []
  150. self.ennemy_ships = []
  151. self.ships = []
  152. self.barrels = []
  153. self.mines = []
  154. self.cannonballs = []
  155. self.threat = {}
  156. for e in list(entities.values()) + ghost_mines:
  157. self.index[e.pos] = e
  158. type_ = type(e)
  159. if type_ is Ship:
  160. self.ships.append(e)
  161. if e.owned:
  162. self.owned_ships.append(e)
  163. else:
  164. self.ennemy_ships.append(e)
  165. elif type_ is Barrel:
  166. self.barrels.append(e)
  167. elif type_ is Mine:
  168. self.mines.append(e)
  169. elif type_ is Cannonball:
  170. self.cannonballs.append(e)
  171. if e.pos not in self.threat or self.threat[e.pos] > e.countdown:
  172. self.threat = {e.pos: e.countdown}
  173. for s in self.owned_ships:
  174. s.allies = [other for other in self.owned_ships if other is not s]
  175. for s in self.ennemy_ships:
  176. s.allies = [other for other in self.ennemy_ships if other is not s]
  177. for s in self.ships:
  178. s.next_pos_proba(2)
  179. self.next_to_mine = {}
  180. for m in self.mines:
  181. for n in self.neighbors(*m.pos):
  182. self.next_to_mine[n] = m
  183. self.next_to_barrel = {}
  184. for b in self.barrels:
  185. for n in self.neighbors(*b.pos):
  186. self.next_to_barrel[n] = b
  187. self.update_moving_costs()
  188. grav_center = self.barrels_gravity_center()
  189. for b in self.barrels:
  190. b.dispersal = Grid.manhattan(grav_center, b.pos) if grav_center != None else 0
  191. b.mine_threat = any(type(self.at(*c)) is Mine for c in self.neighbors(*b.pos))
  192. for s in self.owned_ships:
  193. s._can_move = {c: (s.moving_cost(*c) < 1000)
  194. for c in [s.front, s.front_left, s.left, s.front_right,
  195. s.right, s.back_left, s.back_right]}
  196. s.objectives = ObjectivesQueue()
  197. s.ennemies = ObjectivesQueue()
  198. for b in self.barrels:
  199. obj = GetBarrel(b)
  200. obj.eval(s.prow, s.orientation)
  201. s.objectives.put(obj)
  202. for e in self.ennemy_ships:
  203. obj = Attack(e)
  204. obj.eval(s.pos, s.orientation)
  205. s.ennemies.put(obj)
  206. def at(self, x, y):
  207. try:
  208. return self.index[(x, y)]
  209. except KeyError:
  210. return None
  211. @classmethod
  212. def is_border(cls, x, y):
  213. return x == -1 or y == -1 or x == cls.w or y == cls.h
  214. def collision_at(self, x, y):
  215. e = self.at(x, y)
  216. return type(e) in [Mine, Ship, Cannonball] or not (x, y) in self.__iter__()
  217. def barrels_gravity_center(self):
  218. wx, wy, wtotal = 0,0,0
  219. for b in self.barrels:
  220. wx += (b.x * b.amount)
  221. wy += (b.y * b.amount)
  222. wtotal += b.amount
  223. return (wx // wtotal, wy // wtotal) if wtotal else None
  224. def update_moving_costs(self):
  225. base_costs = {}
  226. self.collisions = []
  227. for x in range(-1, self.w + 1):
  228. for y in range(-1, self.h + 1):
  229. base_costs[(x, y)] = 10 # base moving cost
  230. for x, y in base_costs:
  231. if x in (-1, self.w + 1) or y in (-1, self.h):
  232. base_costs[(x, y)] = 1000 # out of the map
  233. elif x in (0, self.w - 1) or y in (0, self.h - 1):
  234. base_costs[(x, y)] = 15 # borders are a little more expensive
  235. for c in self.next_to_mine:
  236. base_costs[c] += 30
  237. for m in self.mines:
  238. base_costs[m.pos] += 1000
  239. if m.pos in self.threat:
  240. if self.threat[m.pos] <= 2:
  241. # avoid the area of a mines going to explode
  242. for n in self.neighbors(*m.pos):
  243. base_costs[n] += 1000
  244. for c in self.cannonballs:
  245. if 0 < c.countdown <= 2:
  246. base_costs[c.pos] += 1000
  247. for ship in self.ships:
  248. ship._moving_costs = {}
  249. ship._moving_costs.update(base_costs)
  250. for other in self.ships:
  251. if other is ship:
  252. continue
  253. dist = self.manhattan(ship.pos, other.pos)
  254. if dist > 6:
  255. continue
  256. for c in self.zone(other.pos, 3):
  257. ship._moving_costs[c] += 25
  258. next_positions = other.next_pos_proba()
  259. for c, proba in next_positions[1].items():
  260. if proba >= 20:
  261. ship._moving_costs[c] = ship._moving_costs.get(c, 0) + 20 * proba
  262. def shooting_spot(self, ship, target, current=None):
  263. shooting_spots = Queue()
  264. target_pos = target.next_pos if type(target) is Ship else target.pos
  265. for x, y in self.zone(target_pos, 8):
  266. if ship.moving_cost(x, y) > 100:
  267. continue
  268. if self.manhattan((x, y), target_pos) <= 2:
  269. continue
  270. interest = 0 # the lower the better
  271. if (x, y) == current:
  272. interest -= 20
  273. interest += ship.moving_cost(x, y)
  274. # avoid cells too close from borders
  275. if not 3 < x < (self.w - 3):
  276. interest += 50
  277. if not 3 <= y < (self.h - 3):
  278. interest += 50
  279. # priorize cells in the current direction
  280. diff = abs(Grid.diff_directions(ship.orientation, Grid.direction_to(*ship.prow, x, y)))
  281. interest += 10 * abs(diff)
  282. # priorize spots at distance 6 from active ship
  283. interest += (10 * abs(6 - self.manhattan((x, y), ship.pos)))
  284. # priorize spots at distance 6 from targetted ship
  285. interest += (10 * abs(6 - self.manhattan((x, y), target.pos)))
  286. shooting_spots.put((x, y), interest)
  287. return shooting_spots.get()
  288. def runaway_spot(self, ship):
  289. runaway_spot = Queue()
  290. for x, y in iter(self):
  291. if ship.moving_cost(x, y) > 100:
  292. continue
  293. interest = 0 # the lower the better
  294. interest += ship.moving_cost(x, y)
  295. # avoid cells too close from borders
  296. if not 3 < x < (self.w - 3):
  297. interest += 70
  298. if not 3 <= y < (self.h - 3):
  299. interest += 70
  300. # priorize cells in the current direction
  301. diff = abs(Grid.diff_directions(ship.orientation, Grid.direction_to(*ship.prow, x, y)))
  302. interest += 20 * abs(diff)
  303. # priorize spots at distance 6 from active ship
  304. interest += (20 * abs(6 - self.manhattan((x, y), ship.pos)))
  305. # max distance from ennemies
  306. interest -= (10 * min([Grid.manhattan((x, y), e.next_pos) for e in self.ennemy_ships]))
  307. runaway_spot.put((x, y), interest)
  308. return runaway_spot.get()
  309. # geometrical algorithms
  310. @staticmethod
  311. def from_cubic(xu, yu, zu):
  312. return (zu, int(xu + (zu - (zu & 1)) / 2))
  313. @staticmethod
  314. def to_cubic(x, y):
  315. zu = x
  316. xu = int(y - (x - (x & 1)) / 2)
  317. yu = int(-xu - zu)
  318. return (xu, yu, zu)
  319. @staticmethod
  320. def manhattan(from_, to_):
  321. xa, ya = from_
  322. xb, yb = to_
  323. return abs(xa - xb) + abs(ya - yb)
  324. @classmethod
  325. def zone(cls, center, radius):
  326. return [(x, y) for x in range(0, cls.w) for y in range(0, cls.h) if cls.manhattan(center, (x, y)) <= radius]
  327. @staticmethod
  328. def closest(from_, in_):
  329. return min(in_, key=lambda x: Grid.manhattan(from_, x.pos))
  330. @staticmethod
  331. def directions(y):
  332. if y % 2 == 0:
  333. return [(1, 0), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1)]
  334. else:
  335. return [(1, 0), (1,-1), (0,-1), (-1, 0), (0, 1), (1, 1)]
  336. @staticmethod
  337. def direction_to(x0, y0, x, y):
  338. dx, dy = (x - x0), (y - y0)
  339. if dx > 0:
  340. if dy == 0:
  341. return 0
  342. elif dy > 0:
  343. return 5
  344. else:
  345. return 1
  346. elif dx < 0:
  347. if dy == 0:
  348. return 3
  349. elif dy > 0:
  350. return 4
  351. else:
  352. return 2
  353. else:
  354. if dy > 0:
  355. return 5 if y0 % 2 == 0 else 4
  356. else:
  357. return 1 if y0 % 2 == 0 else 2
  358. @staticmethod
  359. def add_directions(d1, d2):
  360. d = d2 + d1
  361. if d < 0:
  362. d += 6
  363. elif d > 5:
  364. d -= 6
  365. return d
  366. @staticmethod
  367. def diff_directions(d1, d2):
  368. d = d2 - d1
  369. if d <= -3:
  370. d += 6
  371. elif d > 3:
  372. d -= 6
  373. return d
  374. # @staticmethod
  375. # def next_cell(x, y, d, repeat=1):
  376. # for _ in range(repeat):
  377. # dx, dy = Grid.directions(y)[d]
  378. # x, y = x + dx, y + dy
  379. # return x, y
  380. @staticmethod
  381. def symetry(d):
  382. return d + 3 if d < 3 else d - 3
  383. @staticmethod
  384. def abs_neighbors(x, y):
  385. return ((x + dx, y + dy) for dx, dy in Grid.directions(y))
  386. @classmethod
  387. def cache_neighbors(cls, xc, yc):
  388. cls._neighbors[(xc, yc)] = [(x, y) for x, y in Grid.abs_neighbors(xc, yc) if 0 <= x < cls.w and 0 <= y < cls.h]
  389. @classmethod
  390. def neighbors(cls, x, y):
  391. try:
  392. return cls._neighbors[(x, y)]
  393. except KeyError:
  394. cls.cache_neighbors(x, y)
  395. return cls._neighbors[(x, y)]
  396. @classmethod
  397. def abs_next_cell(cls, x, y, d):
  398. dx, dy = Grid.directions(y)[d]
  399. return x + dx, y + dy
  400. @classmethod
  401. def cache_next_cell(cls, x, y):
  402. for d, dv in enumerate(Grid.directions(y)):
  403. dx, dy = dv
  404. cls._next_cell[(x, y, d)] = (x + dx, y + dy)
  405. @classmethod
  406. def next_cell(cls, x, y, d, repeat=1):
  407. for _ in range(repeat):
  408. try:
  409. x, y = cls._next_cell[(x, y, d)]
  410. except KeyError:
  411. x, y = cls.abs_next_cell(x, y, d)
  412. return x, y
  413. def rotate(self, center, coordinates, rotations):
  414. if coordinates == [center] or rotations % 6 == 0:
  415. return coordinates
  416. x0, y0 = center
  417. xu0, yu0, zu0 = self.to_cubic(x0, y0)
  418. result = []
  419. for x, y in coordinates:
  420. xu, yu, zu = self.to_cubic(x, y)
  421. dxu, dyu, dzu = xu - xu0, yu - yu0, zu - zu0
  422. for _ in range(rotations):
  423. dxu, dyu, dzu = -dzu, -dxu, -dyu
  424. xru, yru, zru = dxu + xu0, dyu + yu0, dzu + zu0
  425. xr, yr = self.from_cubic(xru, yru, zru)
  426. result.append((xr, yr))
  427. return result
  428. # pathfinding
  429. def path(self, start, start_d, target, moving_costs={}, inertia=0, incl_start=False, limit=10000):
  430. nodes = Queue()
  431. break_on, iteration = limit, 0
  432. broken = False
  433. effective_start = start
  434. origin = PathNode(*effective_start)
  435. origin.orientation = start_d
  436. if inertia is not None:
  437. for _ in range(inertia):
  438. effective_start = self.next_cell(*effective_start, start_d)
  439. origin = PathNode(*effective_start, origin)
  440. origin.orientation = start_d
  441. nodes.put(origin, 0)
  442. neighbors = []
  443. while nodes:
  444. current = nodes.get()
  445. if broken or current == target:
  446. path = []
  447. previous = current
  448. while previous:
  449. if previous != start or incl_start:
  450. path.insert(0, previous)
  451. previous = previous.parent
  452. return path, iteration
  453. neighbors = self.neighbors(*current)
  454. for x, y in neighbors:
  455. if (x, y) == current.parent:
  456. continue
  457. iteration += 1
  458. if break_on > 0 and iteration >= break_on:
  459. broken = True
  460. moving_cost = moving_costs.get((x, y), 1000)
  461. if moving_cost >= 1000:
  462. continue
  463. d = Grid.direction_to(*current, x, y)
  464. if current == start and inertia == 0 and d != current.orientation:
  465. # special: if started with speed 0, first move will require a speed_up,
  466. # making impossible a direction change at first node
  467. continue
  468. diff = abs(Grid.diff_directions(current.orientation, d))
  469. if diff > 1:
  470. # change direction one degree at a time
  471. continue
  472. area = Ship.get_area(x, y, d)
  473. area = [area[0], area[2]]
  474. if diff:
  475. inertial_area = Ship.get_area(x, y, current.orientation)
  476. area += [inertial_area[0], inertial_area[2]]
  477. if any((moving_costs.get(c, 1000) >= 1000 and not Grid.is_border(*c)) for c in area):
  478. continue
  479. cost = current.cost + moving_cost + diff * 20
  480. if (x, y) == start and d == start_d:
  481. # prefer to go right at start (if not speed)
  482. cost -= 10
  483. priority = cost + 10 * Grid.manhattan((x, y), target)
  484. node = PathNode(x, y, current)
  485. node.cost = cost
  486. node.orientation = d
  487. nodes.put(node, priority)
  488. return None, iteration
  489. class Entity(Base):
  490. def __init__(self, ent_id):
  491. self.id = int(ent_id)
  492. self.x, self.y = 0, 0
  493. self.args = [0,0,0,0]
  494. def update(self, x, y, *args):
  495. self.x, self.y = int(x), int(y)
  496. @property
  497. def pos(self):
  498. return (self.x, self.y)
  499. def __lt__(self, other):
  500. # default comparison, used to avoid errors when used with queues and priorities are equals
  501. return self.id < other.id
  502. class Position(Base):
  503. def __init__(self, pos, d, speed, weight=10):
  504. self.pos = pos
  505. self.d = d
  506. self.speed = speed
  507. self.weight = weight
  508. self.area = Ship.get_area(*self.pos, self.d)
  509. class Ship(Entity):
  510. MAX_SPEED = 2
  511. SCOPE = 10
  512. SLOW_DOWN = 1
  513. SPEED_UP = 2
  514. TURN_LEFT = 3
  515. TURN_RIGHT = 4
  516. MOVES = [None, SPEED_UP, TURN_LEFT, TURN_RIGHT, SLOW_DOWN]
  517. COMMANDS = {SLOW_DOWN: "SLOWER", SPEED_UP: "FASTER", TURN_LEFT: "PORT", TURN_RIGHT: "STARBOARD", None: "NONE"}
  518. areas = {}
  519. def __init__(self, *args, **kwargs):
  520. super().__init__(*args, **kwargs)
  521. self.x, self.y = 0, 0
  522. self.orientation = 0
  523. self.speed = 0
  524. self.stock = 0
  525. self.owned = 0
  526. self.next_cell = None
  527. self.next_pos = None
  528. self.last_fire = None
  529. self.last_mining = None
  530. self.blocked_since = 0
  531. self.same_traject_since = 0
  532. self.last_action = ""
  533. self.allies = []
  534. self._moving_costs = {}
  535. self.objectives = ObjectivesQueue()
  536. self.ennemies = ObjectivesQueue()
  537. self.objective = None
  538. self.objectives_next = []
  539. self.target_ennemy = None
  540. self.path = []
  541. self.distance = 0
  542. self.alignment = 0
  543. def __repr__(self):
  544. 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}>"
  545. @classmethod
  546. def abs_area(cls, x, y, d):
  547. return [Grid.next_cell(x, y, d), (x, y), Grid.next_cell(x, y, Grid.add_directions(d, 3))]
  548. @classmethod
  549. def cache_area(cls, x, y):
  550. for d in range(3):
  551. area = [Grid.next_cell(x, y, d), (x, y), Grid.next_cell(x, y, d + 3)]
  552. Ship.areas[(x, y, d)] = area
  553. Ship.areas[(x, y, d + 3)] = list(reversed(area))
  554. @classmethod
  555. def get_area(cls, x, y, d):
  556. try:
  557. return list(Ship.areas[(x, y, d)])
  558. except KeyError:
  559. return cls.abs_area(x, y, d)
  560. def update(self, x, y, *args):
  561. previous_state = self.state()
  562. previous_traject = self.traject()
  563. super().update(x, y)
  564. self.orientation, self.speed, self.stock, self.owned = map(int, args)
  565. self.objectives = ObjectivesQueue()
  566. self.ennemies = ObjectivesQueue()
  567. self.objective = None
  568. self.objectives_next = []
  569. self.target_ennemy = None
  570. self.goto = None
  571. self.path = []
  572. self.area = Ship.get_area(self.x, self.y, self.orientation)
  573. self.prow, _, self.stern = self.area
  574. self.next_cell = self.get_next_cell()
  575. self.next_pos = self.get_next_pos()
  576. self.next_move = None
  577. self.next_area = Ship.get_area(*self.next_pos, self.orientation)
  578. self.front = Grid.next_cell(*self.prow, self.orientation)
  579. self.front_left = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, 1))
  580. self.left = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, 2))
  581. self.front_right = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, -1))
  582. self.right = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, -2))
  583. self.back_left = Grid.next_cell(*self.stern, Grid.add_directions(self.orientation, 1))
  584. self.back_right = Grid.next_cell(*self.stern, Grid.add_directions(self.orientation, -1))
  585. self._can_move = {}
  586. if self.traject() != previous_traject:
  587. self.same_traject_since += 1
  588. else:
  589. self.same_traject_since = 0
  590. if self.state() == previous_state:
  591. self.blocked_since += 1
  592. else:
  593. self.blocked_since = 0
  594. def traject(self):
  595. return (self.orientation, self.speed)
  596. def state(self):
  597. return (self.x, self.y, self.orientation, self.speed)
  598. @classmethod
  599. def get_pos_in(cls, current, speed, orientation, in_=1):
  600. return Grid.next_cell(*current, orientation, repeat=speed * in_)
  601. def get_next_pos(self, in_=1):
  602. return self.get_pos_in(self.pos, self.speed, self.orientation, in_)
  603. def next_pos_proba(self, in_=1):
  604. # guess next positions
  605. positions = {0: [Position(self.pos, self.orientation, self.speed)]}
  606. for i in range(in_):
  607. positions[i + 1] = []
  608. for p in positions[i]:
  609. pos, d, speed = p.pos, p.d, p.speed
  610. # next pos with inertia
  611. inertia = Grid.next_cell(*pos, d, repeat=speed)
  612. # wait, fire or mine
  613. p = Position(inertia, d, speed, 30)
  614. if self.moving_cost(*p.pos) >= 1000:
  615. p.weight = 10
  616. # turn left
  617. p = Position(inertia, Grid.add_directions(d, 1), speed)
  618. if not self.moving_cost(*p.pos) >= 1000:
  619. positions[i + 1].append(p)
  620. # turn right
  621. p = Position(inertia, Grid.add_directions(d, -1), speed)
  622. if not self.moving_cost(*p.pos) >= 1000:
  623. positions[i + 1].append(p)
  624. # speed up
  625. if speed < self.MAX_SPEED:
  626. p = Position(Grid.next_cell(*pos, d, repeat=speed + 1), d, speed + 1)
  627. if not self.moving_cost(*p.pos) >= 1000:
  628. positions[i + 1].append(p)
  629. # slow down
  630. if speed > 1:
  631. p = Position(Grid.next_cell(*pos, d, repeat=speed - 1), d, speed - 1)
  632. if not self.moving_cost(*p.pos) >= 1000:
  633. positions[i + 1].append(p)
  634. # we voluntary ignore the case where a ship at speed 1 would slow down,
  635. # as it is not expected to be a standard behaviour for a ship
  636. # agregate
  637. proba = {}
  638. for i, plst in positions.items():
  639. proba[i] = {}
  640. weights = {}
  641. total_weight = sum([p.weight for p in plst])
  642. for p in plst:
  643. for c in p.area:
  644. weights[c] = weights.get(c, 0) + p.weight
  645. for c in weights:
  646. proba[i][c] = 100 * weights[c] // total_weight
  647. return proba
  648. def guess_next_positions(self, in_=1):
  649. proba = self.next_pos_proba(in_)
  650. best = {}
  651. for i in proba:
  652. best[i] = max(proba[i].items(), key=lambda x: x[1])[0]
  653. return best
  654. def get_next_cell(self, in_=1):
  655. return Grid.next_cell(self.x, self.y, self.orientation, repeat=in_)
  656. def in_current_direction(self, x, y):
  657. return self.orientation == Grid.direction_to(*self.pos, x, y)
  658. def moving_cost(self, x, y):
  659. return self._moving_costs.get((x, y), 1000)
  660. def can_turn_left(self):
  661. return (self._can_move[self.left] or grid.is_border(*self.left)) \
  662. and (self._can_move[self.right] or grid.is_border(*self.right)) \
  663. and (self._can_move[self.back_right] or grid.is_border(*self.back_right))
  664. def can_turn_right(self):
  665. return (self._can_move[self.right] or grid.is_border(*self.right)) \
  666. and (self._can_move[self.left] or grid.is_border(*self.left)) \
  667. and (self._can_move[self.back_left] or grid.is_border(*self.back_left))
  668. def can_move_fwd(self):
  669. return self._can_move[self.front] and not Grid.is_border(*self.prow)
  670. def can_move(self):
  671. return self.can_move_fwd() or self.can_turn_left() or self.can_turn_left()
  672. def area_after_moving(self, move):
  673. new_speed = self.speed
  674. new_orientation = self.orientation
  675. if move == Ship.SPEED_UP:
  676. new_speed += 1
  677. elif move == Ship.SLOW_DOWN:
  678. new_speed -= 1
  679. elif move == Ship.TURN_LEFT:
  680. new_orientation = Grid.add_directions(self.orientation, 1)
  681. elif move == Ship.TURN_RIGHT:
  682. new_orientation = Grid.add_directions(self.orientation, -1)
  683. new_pos = self.get_next_cell(new_speed)
  684. return self.get_area(*new_pos, new_orientation)
  685. def plan_next_move(self):
  686. blocked = False
  687. if self.speed:
  688. if any(self.front in (s.area if not s.speed else [s.area[1], s.area[0], s.prow]) for s in grid.ships if s is not self):
  689. log("Blocked: speed 0")
  690. blocked = True
  691. self.speed = 0
  692. if self.path:
  693. planned = self._follow_path(self.path)
  694. if self.path is None:
  695. if self.can_move():
  696. available = {}
  697. if self.can_move_fwd():
  698. if self.speed:
  699. available[None] = 0
  700. else:
  701. available[Ship.SPEED_UP] = 0
  702. if self.can_turn_left():
  703. available[Ship.TURN_LEFT] = 0
  704. if self.can_turn_right():
  705. available[Ship.TURN_RIGHT] = 0
  706. for m in available:
  707. new_area = self.area_after_moving(m)
  708. available[m] = abs(Grid.diff_directions(self.orientation, Grid.direction_to(*new_area[1], *self.goto))) + \
  709. (2 if self.moving_cost(*new_area[1]) > 10 else 0)
  710. planned = min(available.items(), key=lambda x: x[1])[0]
  711. log(f"(!) broken: automove ({Ship.COMMANDS[planned]})")
  712. else:
  713. log(f"(!) broken: can not move")
  714. planned = None
  715. elif not self.path:
  716. return False
  717. next_move = None
  718. available_moves = [planned] + [m for m in Ship.MOVES if m != planned]
  719. risk = Queue()
  720. for move in available_moves:
  721. new_area = self.area_after_moving(move)
  722. r = 0
  723. for i, c in enumerate(new_area):
  724. mc = self.moving_cost(*c)
  725. if mc >= 1000 and (c in grid or i == 1): # special: extra-grid cells are not consider as collisions since a part of the ship can go there
  726. countdown = grid.threat.get(c, 0)
  727. if countdown > 1 and mc < 2000:
  728. r += 100
  729. else:
  730. if blocked and move in (Ship.SLOW_DOWN, None, Ship.SPEED_UP):
  731. r = 1000
  732. if i == 1:
  733. # the center of the ship is threaten
  734. r += 500
  735. else:
  736. r += 250
  737. if r:
  738. if self.speed and move == Ship.SPEED_UP or self.speed == self.MAX_SPEED and move != Ship.SLOW_DOWN:
  739. # danger: better slow down
  740. r += 20
  741. if not r:
  742. if move == planned:
  743. r = -1
  744. elif self.speed <= 1 and move == Ship.SLOW_DOWN:
  745. r = 50 # we don't want to slow down except there is a danger
  746. else:
  747. # distance from the prow to the current objective
  748. r = abs(Grid.diff_directions(self.orientation, Grid.direction_to(*new_area[1], *self.goto)))
  749. r += (2 if self.moving_cost(*new_area[1]) > 10 else 0)
  750. risk.fput(move, r)
  751. if r >= 100:
  752. log(f"/!\ Danger: planned move <{Ship.COMMANDS[move]}> could lead to collision (risk={r}, area={new_area})")
  753. elif r < 0:
  754. next_move = move
  755. log(f"Safe move: {Ship.COMMANDS[move]}")
  756. break
  757. else:
  758. log(f"Available move <{Ship.COMMANDS[move]}> (risk={r}, area={new_area})")
  759. else:
  760. try:
  761. next_move = risk.get()
  762. log(f"* Go to the less risky: {Ship.COMMANDS[next_move]}")
  763. except IndexError:
  764. next_move = planned
  765. log(f"* No collision-free move was found, go to the initial one: {Ship.COMMANDS[next_move]}")
  766. self.next_move = next_move
  767. self.next_area = new_area
  768. return True
  769. def _follow_path(self, path):
  770. # flags represent direction changes or end of the path
  771. last_flag = len(path) - 1
  772. next_flag = next((i for i, n in enumerate(path) if n.orientation != self.orientation), last_flag)
  773. afternext_flag = next((i for i, n in enumerate(path[next_flag:]) if n.orientation != path[next_flag].orientation), last_flag)
  774. if not self.speed:
  775. diff = Grid.diff_directions(self.orientation, path[0].orientation)
  776. if diff > 0 and self.last_action == "STARBOARD" or diff < 0 and self.last_action == "PORT":
  777. # special: avoid the starting hesitation
  778. return Ship.SPEED_UP
  779. if diff and next_flag == 0:
  780. # start, with a direction change
  781. if diff > 0:
  782. return Ship.TURN_LEFT
  783. elif diff < 0:
  784. return Ship.TURN_RIGHT
  785. # start straight
  786. else:
  787. return Ship.SPEED_UP
  788. elif self.speed == self.MAX_SPEED:
  789. if next_flag <= self.speed:
  790. if afternext_flag >= (next_flag + 2): # there is at least one straight cell after this drift
  791. # drift
  792. diff = Grid.diff_directions(self.orientation, path[next_flag].orientation)
  793. if diff > 0:
  794. return Ship.TURN_LEFT
  795. elif diff < 0:
  796. return Ship.TURN_RIGHT
  797. else:
  798. return Ship.SLOW_DOWN
  799. if next_flag <= self.speed + 1:
  800. # next direction change or target will be passed at current speed
  801. return Ship.SLOW_DOWN
  802. elif self.speed == 1:
  803. if next_flag <= 1:
  804. diff = Grid.diff_directions(self.orientation, path[next_flag].orientation)
  805. if diff > 0:
  806. return Ship.TURN_LEFT
  807. elif diff < 0:
  808. return Ship.TURN_RIGHT
  809. elif next_flag >= 4:
  810. return Ship.SPEED_UP
  811. return None
  812. def move(self):
  813. if self.next_move == Ship.SPEED_UP:
  814. self.speed_up()
  815. elif self.next_move == Ship.SLOW_DOWN:
  816. self.slow_down()
  817. elif self.next_move == Ship.TURN_LEFT:
  818. self.turn_left()
  819. elif self.next_move == Ship.TURN_RIGHT:
  820. self.turn_right()
  821. else:
  822. return False
  823. return True
  824. def fire_at_will(self, *args, **kwargs):
  825. return self._fire_at_will(*args, **kwargs)
  826. def _fire_at_will(self):
  827. if not self.can_fire():
  828. return False
  829. avoid = []
  830. for ship in grid.owned_ships:
  831. avoid += ship.next_area
  832. barrels = [b.pos for b in grid.barrels]
  833. for bpos in barrels:
  834. if any(Grid.manhattan(ship.pos, bpos) <= Grid.manhattan(e.pos, bpos) for ship in grid.owned_ships for e in grid.ennemy_ships):
  835. avoid.append(bpos)
  836. for m in grid.mines:
  837. if any((Grid.manhattan(s.next_pos, m.pos) <= 2 or \
  838. abs(Grid.diff_directions(self.orientation, Grid.direction_to(*s.next_pos, *m.pos))) <= 1)\
  839. for s in grid.owned_ships):
  840. avoid.append(m.pos)
  841. all_shots = {}
  842. for target in grid.ennemy_ships:
  843. next_positions = target.next_pos_proba(4)
  844. # include avoid, mines, barrels, and other ennemies
  845. for t in next_positions:
  846. probas = next_positions[t]
  847. mines_next = {}
  848. for c, proba in probas.items():
  849. if c in grid.next_to_mine:
  850. mpos = grid.next_to_mine[c].pos
  851. mines_next[mpos] = mines_next.get(mpos, 1) + proba
  852. probas.update(mines_next)
  853. for c in probas:
  854. if c in barrels:
  855. probas[c] *= 2
  856. for t, probas in next_positions.items():
  857. shots = sorted(probas.items(), key=lambda x: x[1], reverse=True)
  858. for c, proba in shots:
  859. if c in avoid:
  860. continue
  861. if proba < 20:
  862. continue
  863. dist = Grid.manhattan(self.prow, c)
  864. if dist > self.SCOPE:
  865. continue
  866. # time for the cannonball to reach this pos (including fire turn)
  867. delay = 1 + round(dist / 3)
  868. if delay != t:
  869. continue
  870. if not c in all_shots:
  871. all_shots[c] = (proba - t)
  872. else:
  873. all_shots[c] += (proba - t)
  874. if all_shots:
  875. best_shot = max(all_shots.items(), key=lambda x: x[1])[0]
  876. log(f"[x] precise shoot: pos={best_shot}")
  877. ship.fire(*best_shot)
  878. return True
  879. return False
  880. def can_mine(self):
  881. return self.last_mining is None or (current_turn - self.last_mining) >= 4
  882. def can_fire(self):
  883. return self.last_fire is None or (current_turn - self.last_fire) >= 1
  884. def mine_maybe(self):
  885. if self.can_mine():
  886. if not any(Grid.manhattan(self.prow, ally.next_pos) <= 5 for ally in self.allies):
  887. self.mine()
  888. return True
  889. return False
  890. # --- Basic commands
  891. def _act(self, cmd, *args):
  892. self.last_action = cmd
  893. output = " ".join([cmd] + [str(a) for a in args])
  894. log(f"ship {self.id}: {output}")
  895. print(output)
  896. def auto_move(self, x, y):
  897. self._act("MOVE", x, y)
  898. def speed_up(self):
  899. self._act("FASTER")
  900. def slow_down(self):
  901. self._act("SLOWER")
  902. def turn_right(self):
  903. self._act("STARBOARD")
  904. def turn_left(self):
  905. self._act("PORT")
  906. def wait(self):
  907. self._act("WAIT")
  908. def mine(self):
  909. self.last_mining = current_turn
  910. self._act("MINE")
  911. def fire(self, x, y):
  912. self.last_fire = current_turn
  913. self._act("FIRE", x, y)
  914. class Barrel(Entity):
  915. def __init__(self, *args, **kwargs):
  916. super().__init__(*args, **kwargs)
  917. self.amount = 0
  918. self.dispersal = 0
  919. self.mine_threat = False
  920. self.ennemy_near = False
  921. def __repr__(self):
  922. return f"<Barrel {self.id}: pos=({self.x}, {self.y}), amount={self.amount}>"
  923. def update(self, x, y, *args):
  924. super().update(x, y)
  925. self.amount = int(args[0])
  926. class Mine(Entity):
  927. def __init__(self, *args, **kwargs):
  928. super().__init__(*args, **kwargs)
  929. self.ghost = False
  930. def __repr__(self):
  931. return f"<Mine {self.id}: pos=({self.x}, {self.y}), ghost={self.ghost}>"
  932. class Cannonball(Entity):
  933. def update(self, x, y, *args):
  934. super().update(x, y)
  935. self.sender, self.countdown = int(args[0]), int(args[1])
  936. entities = {}
  937. map_entity = {"SHIP": Ship,
  938. "BARREL": Barrel,
  939. "MINE": Mine,
  940. "CANNONBALL": Cannonball}
  941. Grid.preload()
  942. grid = Grid()
  943. ### *** Main Loop ***
  944. while True:
  945. seen = []
  946. current_turn += 1
  947. # <--- get input
  948. my_ship_count, entity_count = int(input()), int(input())
  949. ent_input = [input().split() for _ in range(entity_count)]
  950. # --->
  951. log(f"### TURN {current_turn}")
  952. log(">> Load input")
  953. # <--- load input
  954. previous_ent, entities = grid.entities, {}
  955. for e in ent_input:
  956. ent_id, ent_type, *data = e
  957. ent_id = int(ent_id)
  958. entities[ent_id] = grid.entities.get(ent_id, map_entity[ent_type](ent_id))
  959. entities[ent_id].update(*data)
  960. grid.load_entities(entities)
  961. # --->
  962. # log(f"Owned Ships: {grid.owned_ships}")
  963. log(f"Ennemy Ships: {grid.ennemy_ships}")
  964. log(f"Barrels: {grid.barrels}")
  965. # log(f"Mines: {grid.mines}")
  966. log(f"Cannonballs: {grid.cannonballs}")
  967. max_it = 9000 // len(grid.owned_ships)
  968. ### Acquire
  969. log("# Acquiring")
  970. # main objective
  971. while not all(s.objective for s in grid.owned_ships):
  972. try:
  973. acquired = sorted([(s, s.objectives.get()) for s in grid.owned_ships if not s.objective], key= lambda x: x[1].interest)
  974. for s, o in acquired:
  975. if not s.objective and not any(al.objective.target is o.target for al in s.allies if al.objective):
  976. s.objective = o
  977. except IndexError:
  978. break
  979. # targetted ennemy
  980. for s in grid.owned_ships:
  981. s.target_ennemy = s.ennemies.get()
  982. ### Plan
  983. log("# Planning")
  984. for ship in grid.owned_ships:
  985. log(f"---- ship {ship.id} ---")
  986. log(f"ship: {ship}")
  987. it_consumed = 0
  988. if ship.objective:
  989. ship.goto = ship.objective.target.pos
  990. elif ship.target_ennemy:
  991. if all(s.stock < ship.stock for s in grid.ships if not s is ship):
  992. log("Best stock: runaway!")
  993. ship.goto = grid.runaway_spot(ship)
  994. else:
  995. ship.goto = grid.shooting_spot(ship, ship.target_ennemy.target, current=ship.goto)
  996. else:
  997. log("ERROR: No target")
  998. continue
  999. log(f"goto: {ship.goto}")
  1000. ship.path, its = grid.path(ship.pos,
  1001. ship.orientation,
  1002. ship.goto,
  1003. moving_costs=ship._moving_costs,
  1004. inertia=ship.speed,
  1005. limit=(max_it - it_consumed))
  1006. it_consumed += its
  1007. log(ship.path)
  1008. if ship.objective and ship.path and ship.path[-1] == ship.goto:
  1009. while ship.objectives and len(ship.path) < 15:
  1010. pos, d = ship.path[-1], ship.path[-1].orientation
  1011. ship.objectives = ObjectivesQueue.re_eval(ship.objectives, pos, d)
  1012. current_obj = ship.objectives.get()
  1013. ship.objectives_next.append(current_obj)
  1014. new_path, its = grid.path(pos, d,
  1015. current_obj.target.pos,
  1016. moving_costs=ship._moving_costs,
  1017. inertia=None,
  1018. limit=(max_it - it_consumed))
  1019. it_consumed += its
  1020. if new_path and new_path[-1] == current_obj.target.pos:
  1021. log(new_path)
  1022. ship.path += new_path
  1023. else:
  1024. break
  1025. ship.plan_next_move()
  1026. log(f"obj: {ship.objective}; next: {ship.objectives_next}")
  1027. log(f"target: {ship.target_ennemy}")
  1028. log(f"path: {ship.path}")
  1029. log(f"next_move: {Ship.COMMANDS[ship.next_move]}")
  1030. ### Process
  1031. log("# Processing")
  1032. for ship in grid.owned_ships:
  1033. log(f"---- ship {ship.id} ---")
  1034. if not ship.objective and not ship.target_ennemy:
  1035. log("No target: wait")
  1036. ship.wait()
  1037. if ship.move():
  1038. continue
  1039. # no movement was required, can fire
  1040. if ship.fire_at_will():
  1041. continue
  1042. # or mine
  1043. if ship.mine_maybe():
  1044. continue
  1045. log("ERROR: Did not act, wait")
  1046. ship.wait()
  1047. # Changelog:
  1048. # 2019-04-17
  1049. # * if no available move, takes the less risky
  1050. # * add the ennemy_near evaluation to the pre_eval method of GetBarrel and update it
  1051. # * ignore probas < 20 in the moving cost calc (about ennemy next positions)
  1052. # * get_shooting_spots: discurage direction changes
  1053. # * increase shooting_spots distance from 5 to 7
  1054. # * fire on mines, do not shoot mines that are in front of the ship
  1055. # * increase the weight of a dead angle in GetBarrel.eval() from 18 to 36 <=> the weight of a distance of 6 needed to turn
  1056. # * mines: increase moving_cost of neighbors if a cannon ball is going to hit the mine
  1057. # * Improve the _follow_path algo
  1058. # * anticipate the speed at 0 when blocked
  1059. # * coeff 20 instead of 10 for the presence probability, making it impassable from 50% instead of 100%
  1060. # *(disactivated) moving cost takes now in account the order of play of the ships
  1061. # * increase the max length of the path from 10 to 15 when seeking for next objectives
  1062. # * minor improvement to automove
  1063. # * Avoid shooting barrels unless ennemy is nearest
  1064. # * include distance to ennemy in the eval of the shooting spot
  1065. # * (disactivated because of below) avoid consecutives direction changes
  1066. # * path: direction change moving cost changed from 10 to 20 because of the slowing effect
  1067. # 2019-04-18
  1068. # * take in account the inertial_area in path computing when direction change
  1069. # * improve the esquive algo by priorizing moves in direction of the target
  1070. # * remove cache on 'next_pos_proba'
  1071. # * improve the fire_at_will algo
  1072. # * takes all ennemies in account to find the best shot
  1073. # * add the runaway behaviour
  1074. # * fix the can_go_fwd method
  1075. # * better path computing for the next objectives (with inertia which can be None)