script.py 38 KB

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