script.py 31 KB

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