script.py 35 KB

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