script.py 32 KB

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