script.py 38 KB

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