script.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. '''
  2. @author: olivier.massot, 2019
  3. '''
  4. import heapq
  5. import sys
  6. # TODO:
  7. # * add an esquive manoeuvre / try to avoid cannonballs
  8. # * consider firing at rum barrels if an ennemy is nearer
  9. # * compute first and second target instead of only one to anticipate the next move
  10. # * if an enemy is near a mine, shoot the mine instead of the ship
  11. # * compute the probabilities of presence of an ennemy on different coords at next turn
  12. # * find a way to change direction without slowing down if possible
  13. # * avoid getting blocked by a side-by-side with an ennemy
  14. debug = True
  15. def log(*msg):
  16. if debug:
  17. print(*msg, file=sys.stderr)
  18. current_turn = 0
  19. class DidNotAct(Exception):
  20. pass
  21. class Queue():
  22. def __init__(self):
  23. self.items = []
  24. def __bool__(self):
  25. return bool(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. pass
  50. class Base():
  51. def __repr__(self):
  52. return f"<{self.__class__.__name__}: {self.__dict__}>"
  53. class BaseObjective(Base):
  54. def __init__(self, target):
  55. self.target = target
  56. self.interest = 0
  57. def __lt__(self, other):
  58. return self.interest < other.interest
  59. def __repr__(self):
  60. return f"<{self.__class__.__name__}({self.target.id})>"
  61. def eval(self, pos = None, d = None):
  62. self.distance = Grid.manhattan(pos, self.target.pos) if pos is not None else 0
  63. self.alignment = abs(Grid.diff_directions(Grid.direction_to(*pos, *self.target.pos), d)) if d is not None else 0
  64. self._compute_interest()
  65. def _compute_interest(self):
  66. self.interest = 7 * self.distance + 3 * self.alignment
  67. class GetBarrel(BaseObjective):
  68. def _compute_interest(self):
  69. self.interest = 6 * self.distance + 9 * self.alignment + 3 * self.target.dispersal + self.target.mine_threat ** 2 - 36 * self.target.ennemy_near
  70. class Attack(BaseObjective):
  71. def _compute_interest(self):
  72. self.interest = 7 * self.distance + 3 * self.alignment + self.target.stock // 4 - 20 * self.target.blocked_since
  73. class PathNode(tuple):
  74. def __new__(self, x, y, parent=None):
  75. n = tuple.__new__(self, (x, y))
  76. n.parent = parent
  77. n.cost = 0
  78. n.orientation = 0
  79. return n
  80. def __repr__(self):
  81. return f"<{self[0]}, {self[1]}, c:{self.cost}, o:{self.orientation}>"
  82. class Grid(Base):
  83. def __init__(self):
  84. self.w = 23
  85. self.h = 21
  86. self._neighbors = {}
  87. for x in range(-1, self.w + 1):
  88. for y in range(-1, self.h + 1):
  89. self.cache_neighbors(x, y)
  90. self.load_entities({})
  91. def __contains__(self, key):
  92. return 0 <= key[0] < self.w and 0 <= key[1] < self.h
  93. def __iter__(self):
  94. for item in ((x, y) for x in range(self.w) for y in range(self.h)):
  95. yield item
  96. # data
  97. def load_entities(self, entities):
  98. # special: mines too far from ships are not recorded but still exist
  99. ghost_mines = []
  100. if hasattr(self, "mines"):
  101. for m in self.mines:
  102. if not m.pos in [e.pos for e in entities.values() if type(e) is Mine]:
  103. if all((self.manhattan(m.pos, ship.pos) > 5) for ship in self.owned_ships):
  104. m.ghost = True
  105. ghost_mines.append(m)
  106. self.entities = entities
  107. self.index = {}
  108. self.ships = []
  109. self.owned_ships = []
  110. self.ennemy_ships = []
  111. self.ships = []
  112. self.barrels = []
  113. self.mines = []
  114. self.cannonballs = []
  115. for e in list(entities.values()) + ghost_mines:
  116. self.index[e.pos] = e
  117. type_ = type(e)
  118. if type_ is Ship:
  119. self.ships.append(e)
  120. if e.owned:
  121. self.owned_ships.append(e)
  122. else:
  123. self.ennemy_ships.append(e)
  124. elif type_ is Barrel:
  125. self.barrels.append(e)
  126. elif type_ is Mine:
  127. self.mines.append(e)
  128. elif type_ is Cannonball:
  129. self.cannonballs.append(e)
  130. for s in self.owned_ships:
  131. s.allies = [other for other in self.owned_ships if other is not s]
  132. grav_center = self.barrels_gravity_center()
  133. for b in self.barrels:
  134. b.dispersal = Grid.manhattan(grav_center, b.pos) if grav_center != None else 0
  135. b.mine_threat = any(type(self.at(*c)) is Mine for c in self.neighbors(*b.pos))
  136. b.ennemy_near = any(b.pos in e.next_area for e in self.ennemy_ships)
  137. for s in self.owned_ships:
  138. for b in self.barrels:
  139. obj = GetBarrel(b)
  140. obj.eval(s.next_pos if s.speed else s.prow, s.orientation)
  141. s.objectives.put(obj)
  142. for e in self.ennemy_ships:
  143. obj = Attack(e)
  144. obj.eval(s.next_pos, s.orientation)
  145. s.ennemies.put(obj)
  146. self.update_moving_costs()
  147. def at(self, x, y):
  148. try:
  149. return self.index[(x, y)]
  150. except KeyError:
  151. return None
  152. def collision_at(self, x, y):
  153. e = self.at(x, y)
  154. return type(e) in [Mine, Ship, Cannonball] or not (x, y) in self.__iter__()
  155. def barrels_gravity_center(self):
  156. wx, wy, wtotal = 0,0,0
  157. for b in self.barrels:
  158. wx += (b.x * b.amount)
  159. wy += (b.y * b.amount)
  160. wtotal += b.amount
  161. return (wx // wtotal, wy // wtotal) if wtotal else None
  162. def update_moving_costs(self):
  163. base_costs = {}
  164. for x in range(-1, self.w + 1):
  165. for y in range(-1, self.h + 1):
  166. base_costs[(x, y)] = 10 # base moving cost
  167. for x, y in base_costs:
  168. if x in (-1, self.w + 1) or y in (-1, self.h):
  169. base_costs[(x, y)] = 1000 # out of the map
  170. elif x in (0, self.w - 1) or y in (0, self.h - 1):
  171. base_costs[(x, y)] = 15 # borders are a little more expensive
  172. for m in self.mines:
  173. for n in self.neighbors(*m.pos):
  174. base_costs[n] += 30
  175. for m in self.mines:
  176. base_costs[m.pos] += 1000
  177. for c in self.cannonballs:
  178. base_costs[c.pos] += (100 + (5 - c.countdown) * 200)
  179. for ship in self.ships:
  180. ship._moving_costs = {}
  181. ship._moving_costs.update(base_costs)
  182. for other in self.ships:
  183. if other is ship:
  184. continue
  185. dist = self.manhattan(ship.pos, other.pos)
  186. if dist > 8:
  187. continue
  188. for c in self.neighbors(*other.pos):
  189. ship._moving_costs[c] += 100 * abs(3 - other.speed)
  190. for c in self.zone(other.next_pos, 4):
  191. ship._moving_costs[c] += 20
  192. def shooting_spot(self, ship, target):
  193. shooting_spots = Queue()
  194. target_pos = target.next_pos if type(target) is Ship else target.pos
  195. for x, y in self.zone(target_pos, 10):
  196. if ship.moving_cost(x, y) > 100:
  197. continue
  198. if self.manhattan((x, y), target_pos) <= 1:
  199. continue
  200. interest = 0 # the lower the better
  201. interest += ship.moving_cost(x, y)
  202. # avoid cells too close from borders
  203. if not (3 <= x <= (self.w - 3) and 3 <= y < (self.h - 3)):
  204. interest += 10
  205. # priorize spots at distance 5 from active ship
  206. interest -= 20 * abs(5 - self.manhattan((x, y), ship.pos))
  207. shooting_spots.put((x, y), interest)
  208. return shooting_spots.get()
  209. # geometrical algorithms
  210. @staticmethod
  211. def from_cubic(xu, yu, zu):
  212. return (zu, int(xu + (zu - (zu & 1)) / 2))
  213. @staticmethod
  214. def to_cubic(x, y):
  215. zu = x
  216. xu = int(y - (x - (x & 1)) / 2)
  217. yu = int(-xu - zu)
  218. return (xu, yu, zu)
  219. @staticmethod
  220. def manhattan(from_, to_):
  221. xa, ya = from_
  222. xb, yb = to_
  223. return abs(xa - xb) + abs(ya - yb)
  224. def zone(self, center, radius):
  225. buffer = frozenset([center])
  226. for _ in range(0, radius):
  227. current = buffer
  228. for x, y in current:
  229. buffer |= frozenset(self.abs_neighbors(x, y))
  230. return [c for c in buffer if 0 <= c[0] < self.w and 0 <= c[1] < self.h]
  231. @staticmethod
  232. def closest(from_, in_):
  233. return min(in_, key=lambda x: Grid.manhattan(from_, x.pos))
  234. @staticmethod
  235. def directions(y):
  236. if y % 2 == 0:
  237. return [(1, 0), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1)]
  238. else:
  239. return [(1, 0), (1,-1), (0,-1), (-1, 0), (0, 1), (1, 1)]
  240. @staticmethod
  241. def direction_to(x0, y0, x, y):
  242. dx, dy = (x - x0), (y - y0)
  243. if dx > 0:
  244. if dy == 0:
  245. return 0
  246. elif dy > 0:
  247. return 5
  248. else:
  249. return 1
  250. elif dx < 0:
  251. if dy == 0:
  252. return 3
  253. elif dy > 0:
  254. return 4
  255. else:
  256. return 2
  257. else:
  258. if dy > 0:
  259. return 5 if y0 % 2 == 0 else 4
  260. else:
  261. return 1 if y0 % 2 == 0 else 2
  262. @staticmethod
  263. def add_directions(d1, d2):
  264. d = d2 + d1
  265. if d <= -3:
  266. d += 6
  267. elif d > 3:
  268. d -= 6
  269. return d
  270. @staticmethod
  271. def diff_directions(d1, d2):
  272. d = d2 - d1
  273. if d <= -3:
  274. d += 6
  275. elif d > 3:
  276. d -= 6
  277. return d
  278. @staticmethod
  279. def next_cell(x, y, d, repeat=1):
  280. for _ in range(repeat):
  281. dx, dy = Grid.directions(y)[d]
  282. x, y = x + dx, y + dy
  283. return x, y
  284. @staticmethod
  285. def symetry(d):
  286. return d + 3 if d < 3 else d - 3
  287. @staticmethod
  288. def abs_neighbors(x, y):
  289. return ((x + dx, y + dy) for dx, dy in Grid.directions(y))
  290. def cache_neighbors(self, xc, yc):
  291. self._neighbors[(xc, yc)] = [(x, y) for x, y in Grid.abs_neighbors(xc, yc) if 0 <= x < self.w and 0 <= y < self.h]
  292. def neighbors(self, x, y):
  293. try:
  294. return self._neighbors[(x, y)]
  295. except KeyError:
  296. self.cache_neighbors(x, y)
  297. return self._neighbors[(x, y)]
  298. def rotate(self, center, coordinates, rotations):
  299. if coordinates == [center] or rotations % 6 == 0:
  300. return coordinates
  301. x0, y0 = center
  302. xu0, yu0, zu0 = self.to_cubic(x0, y0)
  303. result = []
  304. for x, y in coordinates:
  305. xu, yu, zu = self.to_cubic(x, y)
  306. dxu, dyu, dzu = xu - xu0, yu - yu0, zu - zu0
  307. for _ in range(rotations):
  308. dxu, dyu, dzu = -dzu, -dxu, -dyu
  309. xru, yru, zru = dxu + xu0, dyu + yu0, dzu + zu0
  310. xr, yr = self.from_cubic(xru, yru, zru)
  311. result.append((xr, yr))
  312. return result
  313. # pathfinding
  314. def path(self, origin, orientat0, target, moving_costs={}, incl_start=False, limit=10000):
  315. nodes = Queue()
  316. break_on, iteration = limit, 0
  317. origin = PathNode(*origin)
  318. origin.orientation = orientat0
  319. nodes.put(origin, 0)
  320. neighbors = []
  321. while nodes:
  322. current = nodes.get()
  323. if current == target:
  324. path = []
  325. previous = current
  326. while previous:
  327. if previous != origin or incl_start:
  328. path.insert(0, previous)
  329. previous = previous.parent
  330. return path
  331. neighbors = self.neighbors(*current)
  332. for x, y in neighbors:
  333. if (x, y) == current.parent:
  334. continue
  335. iteration += 1
  336. if break_on > 0 and iteration >= break_on:
  337. return None
  338. moving_cost = moving_costs.get((x, y), 1000)
  339. if moving_cost >= 1000:
  340. continue
  341. d = Grid.direction_to(*current, x, y)
  342. diff = abs(Grid.diff_directions(current.orientation, d))
  343. if diff > 1:
  344. # change direction one degree at a time
  345. continue
  346. if any(moving_costs.get(c, 1000) >= 1000 for c in Ship.get_area(x, y, d)):
  347. continue
  348. cost = current.cost + moving_cost + diff * 10
  349. # if diff != 0 and any(moving_costs.get(c, 1000) >= 1000 for c in neighbors):
  350. # # a direction change here is dangerous
  351. # cost += 100
  352. priority = cost + 10 * Grid.manhattan((x, y), target)
  353. node = PathNode(x, y, current)
  354. node.cost = cost
  355. node.orientation = d
  356. nodes.put(node, priority)
  357. else:
  358. return None
  359. class Entity(Base):
  360. def __init__(self, ent_id):
  361. self.id = int(ent_id)
  362. self.x, self.y = 0, 0
  363. self.args = [0,0,0,0]
  364. def update(self, x, y, *args):
  365. self.x, self.y = int(x), int(y)
  366. @property
  367. def pos(self):
  368. return (self.x, self.y)
  369. def __lt__(self, other):
  370. # default comparison, used to avoid errors when used with queues and priorities are equals
  371. return self.id < other.id
  372. class Ship(Entity):
  373. MAX_SPEED = 2
  374. SCOPE = 10
  375. def __init__(self, *args, **kwargs):
  376. super().__init__(*args, **kwargs)
  377. self.x, self.y = 0, 0
  378. self.orientation = 0
  379. self.speed = 0
  380. self.stock = 0
  381. self.owned = 0
  382. self.next_cell = None
  383. self.next_pos = None
  384. self.last_fire = None
  385. self.last_mining = None
  386. self.blocked_since = 0
  387. self.same_traject_since = 0
  388. self.last_action = ""
  389. self.allies = []
  390. self._moving_costs = {}
  391. self.objectives = ObjectivesQueue()
  392. self.ennemies = ObjectivesQueue()
  393. self.objective = None
  394. self.objective_next = None
  395. self.target_ennemy = None
  396. self.path = []
  397. self.distance = 0
  398. self.alignment = 0
  399. def __repr__(self):
  400. 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}>"
  401. def update(self, x, y, *args):
  402. previous_state = self.state()
  403. previous_traject = self.traject()
  404. super().update(x, y)
  405. self.orientation, self.speed, self.stock, self.owned = map(int, args)
  406. self.objectives = ObjectivesQueue()
  407. self.ennemies = ObjectivesQueue()
  408. self.objective = None
  409. self.objective_next = None
  410. self.target_ennemy = None
  411. self.goto = None
  412. self.path = []
  413. self.area = Ship.get_area(self.x, self.y, self.orientation)
  414. self.prow, _, self.stern = self.area
  415. self.next_cell = self.get_next_cell()
  416. self.next_pos = self.get_next_pos()
  417. self.next_area = Ship.get_area(*self.next_pos, self.orientation)
  418. self.mobility_zone = list(set(self.area + self.next_area))
  419. if self.traject() != previous_traject:
  420. self.same_traject_since += 1
  421. else:
  422. self.same_traject_since = 0
  423. if self.state() == previous_state:
  424. self.blocked_since += 1
  425. else:
  426. self.blocked_since = 0
  427. def traject(self):
  428. return (self.orientation, self.speed)
  429. def state(self):
  430. return (self.x, self.y, self.orientation, self.speed)
  431. @classmethod
  432. def get_pos_in(cls, current, speed, orientation, in_=1):
  433. x, y = current
  434. for _ in range(in_):
  435. for _ in range(speed):
  436. dx, dy = Grid.directions(y)[orientation]
  437. x, y = x + dx, y + dy
  438. return x, y
  439. @classmethod
  440. def get_area(cls, x, y, orientation):
  441. dx, dy = Grid.directions(y)[Grid.add_directions(orientation, 3)]
  442. stern = (x + dx, y + dy)
  443. dx, dy = Grid.directions(y)[orientation]
  444. prow = (x + dx, y + dy)
  445. return [prow, (x, y), stern]
  446. def get_next_pos(self, in_=1):
  447. return self.get_pos_in(self.pos, self.speed, self.orientation, in_)
  448. def guess_next_pos(self):
  449. proba = {}
  450. # wait (or fire or mine)
  451. for c in self.next_area:
  452. proba[c] = proba.get(c, 10)
  453. # turn left
  454. area = self.get_area(*self.pos, Grid.add_directions(self.orientation, 1))
  455. for c in area:
  456. proba[c] = proba.get(c, 0) + 10
  457. # turn right
  458. area = self.get_area(*self.pos, Grid.add_directions(self.orientation, -1))
  459. for c in area:
  460. proba[c] = proba.get(c, 0) + 10
  461. # speed up
  462. if self.speed < self.MAX_SPEED:
  463. area = self.get_area(*self.get_pos_in(self.pos, self.speed + 1, self.orientation), self.orientation)
  464. for c in area:
  465. proba[c] = proba.get(c, 0) + 10
  466. # slow down
  467. if self.speed > 0:
  468. area = self.get_area(*self.get_pos_in(self.pos, self.speed - 1, self.orientation), self.orientation)
  469. for c in area:
  470. proba[c] = proba.get(c, 0) + 10
  471. for c in proba:
  472. proba[c] -= self.moving_cost(*c)
  473. for c in self.area:
  474. proba[c] = proba.get(c, 0) + 50 * self.blocked_since
  475. best = max(proba.items(), key=lambda x: x[1])
  476. return best[0]
  477. def get_next_cell(self, in_=1):
  478. return Grid.next_cell(self.x, self.y, self.orientation, repeat=in_)
  479. def in_current_direction(self, x, y):
  480. return self.orientation == Grid.direction_to(*self.pos, x, y)
  481. def moving_cost(self, x, y):
  482. return self._moving_costs.get((x, y), 1000)
  483. def cant_move(self):
  484. front = Grid.next_cell(*self.prow, self.orientation)
  485. front_left = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, 1))
  486. left = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, 2))
  487. front_right = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, -1))
  488. right = Grid.next_cell(*self.prow, Grid.add_directions(self.orientation, -2))
  489. back_left = Grid.next_cell(*self.stern, Grid.add_directions(self.orientation, 2))
  490. back_right = Grid.next_cell(*self.stern, Grid.add_directions(self.orientation, -2))
  491. blocked = {c: (self.moving_cost(*c) >= 1000) for c in [front, front_left, left,
  492. front_right, right,
  493. back_left, back_right]}
  494. if all(blocked[i] for i in [front, front_left, front_right, left, right]):
  495. # surrounded
  496. return True
  497. elif (blocked[front_left] and blocked[left]) or (blocked[front_right] and blocked[right]):
  498. # side by side
  499. return True
  500. elif blocked[front] and ((blocked[front_left] and blocked[back_right]) or (blocked[front_right] and blocked[back_left])):
  501. # cannot go front or turn
  502. return True
  503. return False
  504. def move(self, *args, **kwargs):
  505. try:
  506. self._move(*args, **kwargs)
  507. return True
  508. except DidNotAct:
  509. return False
  510. def _move(self, path, danger=[]):
  511. if path is None:
  512. log(f"(!) broken: automove to {self.goto}")
  513. self.auto_move(*self.goto)
  514. return
  515. elif not path:
  516. raise DidNotAct()
  517. # speed shall be at 1 when arriving on the "flag"
  518. next_flag = next((i for i, n in enumerate(path) if n.orientation != self.orientation), None)
  519. if next_flag is None:
  520. next_flag = len(path)
  521. diff = Grid.diff_directions(self.orientation, path[0].orientation)
  522. if not self.speed:
  523. if diff and next_flag == 0:
  524. # start, with a direction change
  525. if diff > 0:
  526. self.turn_left()
  527. return
  528. elif diff < 0:
  529. self.turn_right()
  530. return
  531. else:
  532. # start, todo recto
  533. self.speed_up()
  534. return
  535. elif self.speed > 1 and next_flag <= (self.speed + 1):
  536. # the end of the path or a direction change is coming
  537. self.slow_down()
  538. return
  539. elif next_flag > self.MAX_SPEED + 1 and self.speed < self.MAX_SPEED:
  540. # long path and no direction change coming: speed up
  541. self.speed_up()
  542. return
  543. elif diff:
  544. if diff > 0:
  545. self.turn_left()
  546. return
  547. elif diff < 0:
  548. self.turn_right()
  549. return
  550. raise DidNotAct()
  551. def fire_at_will(self, *args, **kwargs):
  552. try:
  553. self._fire_at_will(*args, **kwargs)
  554. return True
  555. except DidNotAct:
  556. return False
  557. def _fire_at_will(self, target, allies = []):
  558. if not self.can_fire():
  559. raise DidNotAct()
  560. avoid = []
  561. if not self in allies:
  562. allies.append(self)
  563. for ally in allies:
  564. avoid += ally.mobility_zone
  565. dist = Grid.manhattan(self.prow, target.next_pos)
  566. if dist <= 4:
  567. # precise algo
  568. shoot_at = target.guess_next_pos()
  569. log(f"most probable position: {shoot_at}")
  570. ship.fire(*shoot_at)
  571. elif dist <= self.SCOPE:
  572. # anticipate
  573. next_positions = [target.get_next_pos(i) for i in range(1, 3)]
  574. for i, p in enumerate(next_positions):
  575. turn = i + 1
  576. if p in avoid:
  577. continue
  578. dist_p = Grid.manhattan(self.prow, p)
  579. if dist_p > self.SCOPE:
  580. continue
  581. if (1 + round(dist_p / 3)) == turn:
  582. log(f"Precision: {p}, {dist_p}, {turn}")
  583. ship.fire(*p)
  584. return
  585. # give a try
  586. next_pos = next_positions[0]
  587. dist_p = Grid.manhattan(self.prow, next_pos)
  588. if dist_p <= self.SCOPE:
  589. ship.fire(*p)
  590. else:
  591. raise DidNotAct()
  592. def can_mine(self):
  593. return self.last_mining is None or (current_turn - self.last_mining) >= 4
  594. def can_fire(self):
  595. return self.last_fire is None or (current_turn - self.last_fire) >= 1
  596. # --- Basic commands
  597. def _act(self, cmd, *args):
  598. self.last_action = cmd
  599. output = " ".join([cmd] + [str(a) for a in args])
  600. log(f"ship {self.id}: {output}")
  601. print(output)
  602. def auto_move(self, x, y):
  603. self._act("MOVE", x, y)
  604. def speed_up(self):
  605. self._act("FASTER")
  606. def slow_down(self):
  607. self._act("SLOWER")
  608. def turn_right(self):
  609. self._act("STARBOARD")
  610. def turn_left(self):
  611. self._act("PORT")
  612. def wait(self):
  613. self._act("WAIT")
  614. def mine(self):
  615. self.last_mining = current_turn
  616. self._act("MINE")
  617. def fire(self, x, y):
  618. self.last_fire = current_turn
  619. self._act("FIRE", x, y)
  620. class Barrel(Entity):
  621. def __init__(self, *args, **kwargs):
  622. super().__init__(*args, **kwargs)
  623. self.amount = 0
  624. self.dispersal = 0
  625. self.mine_threat = False
  626. self.ennemy_near = False
  627. def __repr__(self):
  628. return f"<Barrel {self.id}: pos=({self.x}, {self.y}), amount={self.amount}>"
  629. def update(self, x, y, *args):
  630. super().update(x, y)
  631. self.amount = int(args[0])
  632. class Mine(Entity):
  633. def __init__(self, *args, **kwargs):
  634. super().__init__(*args, **kwargs)
  635. self.ghost = False
  636. def __repr__(self):
  637. return f"<Mine {self.id}: pos=({self.x}, {self.y}), ghost={self.ghost}>"
  638. class Cannonball(Entity):
  639. def update(self, x, y, *args):
  640. super().update(x, y)
  641. self.sender, self.countdown = int(args[0]), int(args[1])
  642. entities = {}
  643. map_entity = {"SHIP": Ship,
  644. "BARREL": Barrel,
  645. "MINE": Mine,
  646. "CANNONBALL": Cannonball}
  647. grid = Grid()
  648. ### *** Main Loop ***
  649. while True:
  650. seen = []
  651. current_turn += 1
  652. # <--- get input
  653. my_ship_count, entity_count = int(input()), int(input())
  654. previous_ent, entities = grid.entities, {}
  655. for _ in range(entity_count):
  656. ent_id, ent_type, *data = input().split()
  657. ent_id = int(ent_id)
  658. entities[ent_id] = grid.entities.get(ent_id, map_entity[ent_type](ent_id))
  659. entities[ent_id].update(*data)
  660. # --->
  661. grid.load_entities(entities)
  662. log(f"### TURN {current_turn}")
  663. # log(f"Owned Ships: {grid.owned_ships}")
  664. log(f"Ennemy Ships: {grid.ennemy_ships}")
  665. # log(f"Barrels: {grid.barrels}")
  666. # log(f"Mines: {grid.mines}")
  667. log(f"Cannonballs: {grid.cannonballs}")
  668. ### Acquire
  669. log("# Acquiring")
  670. # main objective
  671. while not all(s.objective for s in grid.owned_ships):
  672. try:
  673. acquired = sorted([(s, s.objectives.get()) for s in grid.owned_ships if not s.objective], key= lambda x: x[1].interest)
  674. for s, o in acquired:
  675. if not s.objective and not any(al.objective.target is o.target for al in s.allies if al.objective):
  676. s.objective = o
  677. except IndexError:
  678. break
  679. # after_that objective
  680. for s in grid.owned_ships:
  681. if not s.objective:
  682. continue
  683. if grid.manhattan(s.pos, s.objective.target.pos) > 5:
  684. continue
  685. after_that = ObjectivesQueue()
  686. for b in [o.target for o in s.objectives.items]:
  687. obj = GetBarrel(b)
  688. obj.eval(s.objective.target.pos, s.orientation)
  689. after_that.put(obj)
  690. if after_that:
  691. s.objective_next = after_that.get()
  692. # targetted ennemy
  693. for s in grid.owned_ships:
  694. s.target_ennemy = s.ennemies.get()
  695. for ship in grid.owned_ships:
  696. log(f"Ship {ship.id}: obj: {ship.objective}; next: {ship.objective_next}; target: {ship.target_ennemy}")
  697. ### Plan
  698. log("# Planning")
  699. for ship in grid.owned_ships:
  700. log(f"---- ship {ship.id} ---")
  701. log(f"ship: {ship}")
  702. if ship.objective or (ship.target_ennemy and ship.target_ennemy.interest < 0):
  703. ship.goto = ship.objective.target.pos
  704. elif ship.target_ennemy:
  705. ship.goto = grid.shooting_spot(ship, ship.target_ennemy.target)
  706. else:
  707. log("ERROR: No target")
  708. continue
  709. log(f"goto: {ship.goto}")
  710. ship.path = grid.path(ship.next_pos, ship.orientation, ship.goto, ship._moving_costs, limit=6000 // len(grid.owned_ships))
  711. if ship.objective_next and ship.path:
  712. ship.path += grid.path(ship.goto,
  713. ship.path[-1].orientation,
  714. ship.objective_next.target.pos,
  715. ship._moving_costs,
  716. limit=6000 // len(grid.owned_ships)) or []
  717. log(f"path: {ship.path}")
  718. ### special: avoid cannonballs
  719. danger = [c.pos for c in grid.cannonballs if c.countdown <= 1]
  720. ### Process
  721. log("# Processing")
  722. for ship in grid.owned_ships:
  723. if not ship.objective and not ship.target_ennemy:
  724. log("No target: wait")
  725. ship.wait()
  726. if ship.cant_move():
  727. log("blocked... fire!")
  728. if ship.fire_at_will(ship.target_ennemy.target, allies=grid.owned_ships):
  729. continue
  730. if ship.move(ship.path):
  731. continue
  732. # no movement was required, can fire
  733. if ship.fire_at_will(ship.target_ennemy.target, allies=grid.owned_ships):
  734. continue
  735. log("ERROR: Did not act, wait")
  736. ship.wait()