script.py 39 KB

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