script.py 34 KB

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