script.py 47 KB

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