script.py 38 KB

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