script.py 31 KB

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