script.py 38 KB

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