script.py 28 KB

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