script.py 39 KB

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