script.py 35 KB

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