Advertisement
Guest User

phil arrêtes de coder

a guest
May 23rd, 2022
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 23.55 KB | None | 0 0
  1. import math
  2. import random
  3. import sys
  4. from dataclasses import dataclass, field
  5. from enum import Enum
  6. from tkinter import Tk, Canvas, YES, BOTH
  7. from tkinter.ttk import Label
  8. from typing import Any, List, Tuple
  9.  
  10. from numpy import array, cos, sin, dot
  11. from scipy.linalg import norm
  12.  
  13.  
  14. def idebug(*args):
  15.     return
  16.     print(*args, file=sys.stderr, flush=True)
  17.  
  18.  
  19. def debug(*args):
  20.     # return
  21.     print(*args, file=sys.stderr, flush=True)
  22.  
  23.  
  24. class EntityType(Enum):
  25.     SPIDER = 0
  26.     PLAYER = 1
  27.     OPPONENT = 2
  28.     PLAYER_BASE = 3
  29.     ENEMY_BASE = 4
  30.  
  31.  
  32. @dataclass
  33. class Action:
  34.     type: str
  35.     target: array = None
  36.     entity_id: int = None
  37.     message: str = None
  38.  
  39.     def __repr__(self):
  40.         if self.type == 'MOVE':
  41.             x, y = self.target
  42.             msg: str = f' {self.message}' if self.message else ''
  43.             return f'MOVE {round(x)} {round(y)}{msg}'
  44.         elif self.type == 'SPELL WIND':
  45.             x, y = self.target
  46.             return f'{self.type} {round(x)} {round(y)}'
  47.         elif self.type == 'SPELL SHIELD':
  48.             return f'{self.type} {self.entity_id}'
  49.         elif self.type == 'SPELL CONTROL':
  50.             x, y = self.target
  51.             return f'{self.type} {self.entity_id} {round(x)} {round(y)}'
  52.  
  53.  
  54. @dataclass
  55. class Entity:
  56.     id: int
  57.     x: int
  58.     y: int
  59.     vx: int
  60.     vy: int
  61.     radius: int
  62.     speed: int
  63.     type: EntityType
  64.     health: int
  65.     visible: bool = False
  66.     action: Action = None
  67.     threat_for: EntityType = field(init=False)
  68.     velocity: array = field(init=False)  # calculated value after instance creation
  69.     label: Any = field(init=False)
  70.     circle: Any = field(init=False)
  71.  
  72.     def __post_init__(self):
  73.         self.location = array([self.x, self.y], dtype=float)
  74.         self.velocity = array([self.vx, self.vy], dtype=float)
  75.         self.threat_for = self.type
  76.         self.label = None
  77.         self.circle = None
  78.  
  79.     def __copy__(self):
  80.         return Entity(id=self.id, x=self.x, y=self.y, vx=self.vx, vy=self.vy, radius=self.radius, speed=self.speed, type=self.type, health=self.health, visible=self.visible, action=self.action)
  81.  
  82.     def threat_level(self, base) -> int:
  83.         score = 0
  84.         if self.threat_for == base.type:
  85.             if self.dist(base) <= 5000:
  86.                 score = 1000
  87.             else:
  88.                 score = 500
  89.         score += 500 / (1 + self.dist(base))
  90.         return score
  91.  
  92.     def dist(self, other):
  93.         return norm(self.location - other.location) if isinstance(other, Entity) else norm(self.location - other)
  94.  
  95.     def delete_from(self, canvas: Canvas):
  96.         canvas.delete(self.circle)
  97.         self.label.destroy()
  98.  
  99.     def move(self, canvas: Canvas = None, target: array = None):
  100.         new_location = self.get_new_location(target=target)
  101.         if canvas is not None:
  102.             dx, dy = reduce(new_location - self.location)
  103.             canvas.move(self.circle, dx, dy)
  104.         self.location = new_location
  105.         self.update_label()
  106.  
  107.     def create_circle(self, canvas: Canvas, color: str):
  108.         # changed this to return the ID
  109.         x, y = self.location
  110.         oval = x - self.radius, y - self.radius, x + self.radius, y + self.radius
  111.         x0, y0, x1, y1 = reduce(oval)
  112.         self.circle = canvas.create_oval(x0, y0, x1, y1, width=1, outline=color)
  113.  
  114.     def update_label(self):
  115.         x, y = reduce(self.location)
  116.         self.label.place(x=x, y=y)
  117.         if self.type == EntityType.SPIDER:
  118.             self.label['text'] = f'P{self.id}' if self.threat_for == EntityType.PLAYER_BASE else f'E{self.id}' if self.threat_for == EntityType.ENEMY_BASE else self.health
  119.         else:
  120.             if self.visible:
  121.                 self.label['text'] = f"{self.health}" if self.type in [EntityType.SPIDER, EntityType.PLAYER_BASE, EntityType.ENEMY_BASE] else f"{self.id}"
  122.             else:
  123.                 self.label['text'] = 'Fog'
  124.  
  125.     def get_new_location(self, target=None):
  126.         if target is not None:
  127.             if isinstance(target, Entity):
  128.                 u: array = target.location - self.location
  129.             else:
  130.                 u: array = target - self.location
  131.             v: array = u / norm(u) if norm(u) > 0 else 0
  132.             speed: float = min(self.speed, self.dist(target))
  133.             new_location = self.location + speed * v
  134.         else:
  135.             new_location = self.location + self.velocity
  136.         return new_location
  137.  
  138.  
  139. def inside_map(location: array) -> bool:
  140.     x, y = location
  141.     return 0 <= x <= MAP_WIDTH and 0 <= y <= MAP_HEIGHT
  142.  
  143.  
  144. def spawn_spiders(entity_counter: int, spiders_max_level: int) -> Tuple[Entity, Entity]:
  145.     hp_list = [(i + 1) * 10 for i in range(spiders_max_level)]
  146.     hp_spider: int = random.choice(hp_list)
  147.     top_left, top_right = 5000, MAP_WIDTH
  148.     random_x: int = random.randint(top_left, top_right)
  149.     dir: int = random.randint(1, 5)
  150.     theta = dir * math.pi / 6
  151.     # theta = radians(angle)
  152.     c, s = cos(theta), sin(theta)
  153.     R = array(((c, -s), (s, c)))
  154.     u_x: array = array([1, 0])
  155.     vx, vy = 400 * dot(R, u_x)
  156.     spider: Entity = Entity(id=entity_counter, health=hp_spider, type=EntityType.SPIDER, x=random_x, y=0, vx=vx, vy=vy, radius=400, speed=400)
  157.     x, y = array([MAP_WIDTH, MAP_HEIGHT]) - spider.location
  158.     vx, vy = -spider.velocity
  159.     symmetric_spider: Entity = Entity(id=entity_counter + 1, health=hp_spider, type=EntityType.SPIDER, x=x, y=y, vx=vx, vy=vy, radius=400, speed=400)
  160.     return spider, symmetric_spider
  161.  
  162.  
  163. @dataclass
  164. class Game:
  165.     max_turns: int
  166.     respawn_value: int
  167.     spiders_max_level: int
  168.     root: Tk = Tk()
  169.     canvas: Canvas = None
  170.     console: Label = None
  171.     my_base: array = None
  172.     my_base_detect_radius: array = None
  173.     enemy_base: array = None
  174.     enemy_base_detect_radius: array = None
  175.     turns = 1
  176.     entity_counter = 0
  177.     spawn_cooldown: int = 0
  178.     my_mana: int = 0
  179.     enemy_mana: int = 0
  180.     my_wild_mana: int = 0
  181.     enemy_wild_mana: int = 0
  182.     heroes: List[Entity] = field(default_factory=list)
  183.     enemies: List[Entity] = field(default_factory=list)
  184.     spiders: List[Entity] = field(default_factory=list)
  185.  
  186.     def get_default_positions(self, player: EntityType) -> List[array]:
  187.         # Some constants used to affect game's zones for my heroes
  188.         base: Entity = self.my_base if player == EntityType.PLAYER else self.enemy_base
  189.         base_is_top_left = (base.x, base.y) == (0, 0)
  190.         map_size: array = array([MAP_WIDTH, MAP_HEIGHT])
  191.         pos_0_topleft, pos_1_topleft, pos_2_topleft = array([15199, 6225]), array([4706, 2033]), array([2033, 4706])
  192.         pos_0_bottom_right, pos_1_bottom_right, pos_2_bottom_right = map_size - pos_0_topleft, map_size - pos_1_topleft, map_size - pos_2_topleft
  193.         return [pos_0_topleft, pos_1_topleft, pos_2_topleft] if base_is_top_left else [pos_0_bottom_right, pos_1_bottom_right, pos_2_bottom_right]
  194.  
  195.     def threat_for(self, spider: Entity) -> EntityType:
  196.         base_candidates: List[Entity] = []
  197.         for base in [self.my_base, self.enemy_base]:
  198.             x0, y0 = base.location
  199.             x1, y1 = spider.location
  200.             a, b = spider.velocity
  201.             r = 5000
  202.             # Equation droite
  203.             # x = x1 + a * t
  204.             # y = y1 + b * t
  205.             # Equation cercle
  206.             # (x - x0) ** 2 + (y - y0) ** 2 = r * r
  207.             A = a * a + b * b
  208.             B = 2 * (a * x1 - a * x0 + b * y1 - b * y0)
  209.             C = (x1 - x0) ** 2 + (y1 - y0) ** 2 - r * r
  210.             # Intersection cercle/droite:
  211.             # A * t^2 + B * t + C = 0
  212.             det: float = B * B - 4 * A * C
  213.             if det >= 0:
  214.                 t0 = (-B + math.sqrt(det)) / (2 * A)
  215.                 X0, Y0 = x1 + a * t0, y1 + b * t0
  216.                 t1 = (-B - math.sqrt(det)) / (2 * A)
  217.                 X1, Y1 = x1 + a * t1, y1 + b * t1
  218.                 if inside_map((X0, Y0)) or inside_map((X1, Y1)):
  219.                     base_candidates.append(base)
  220.         if len(base_candidates) == 2:
  221.             new_spider_location = spider.location + spider.velocity
  222.             for base in base_candidates:
  223.                 if norm(new_spider_location - base.location) < spider.dist(base):
  224.                     return base.type
  225.         else:
  226.             return base_candidates[0].type if base_candidates else EntityType.SPIDER
  227.  
  228.     def init(self):
  229.         """
  230.            Initialise les entités de départ dans le jeu
  231.        :return:
  232.        """
  233.         self.my_base = Entity(id=None, health=3, type=EntityType.PLAYER_BASE, x=0, y=0, vx=0, vy=0, radius=300, speed=0, visible=True)
  234.         self.my_base_detect_radius = Entity(id=None, health=math.inf, type=EntityType.PLAYER_BASE, x=0, y=0, vx=0, vy=0, radius=5000, speed=0)
  235.         self.enemy_base = Entity(id=None, health=3, type=EntityType.ENEMY_BASE, x=MAP_WIDTH, y=MAP_HEIGHT, vx=0, vy=0, radius=300, speed=0, visible=True)
  236.         self.enemy_base_detect_radius = Entity(id=None, health=math.inf, type=EntityType.ENEMY_BASE, x=MAP_WIDTH, y=MAP_HEIGHT, vx=0, vy=0, radius=5000, speed=0)
  237.         hero_1 = Entity(id=0, health=math.inf, type=EntityType.PLAYER, x=1414, y=849, vx=0, vy=0, radius=800, speed=800, visible=True)
  238.         hero_2 = Entity(id=1, health=math.inf, type=EntityType.PLAYER, x=1131, y=1131, vx=0, vy=0, radius=800, speed=800, visible=True)
  239.         hero_3 = Entity(id=2, health=math.inf, type=EntityType.PLAYER, x=849, y=1414, vx=0, vy=0, radius=800, speed=800, visible=True)
  240.         self.heroes.append(hero_1)
  241.         self.heroes.append(hero_2)
  242.         self.heroes.append(hero_3)
  243.         hero_1 = Entity(id=3, health=math.inf, type=EntityType.OPPONENT, x=MAP_WIDTH - 1414, y=MAP_HEIGHT - 849, vx=0, vy=0, radius=800, speed=800)
  244.         hero_2 = Entity(id=4, health=math.inf, type=EntityType.OPPONENT, x=MAP_WIDTH - 1131, y=MAP_HEIGHT - 1131, vx=0, vy=0, radius=800, speed=800)
  245.         hero_3 = Entity(id=5, health=math.inf, type=EntityType.OPPONENT, x=MAP_WIDTH - 849, y=MAP_HEIGHT - 1414, vx=0, vy=0, radius=800, speed=800)
  246.         self.heroes.append(hero_1)
  247.         self.heroes.append(hero_2)
  248.         self.heroes.append(hero_3)
  249.         self.entity_counter = len(self.heroes)
  250.         spider, symmetric_spider = spawn_spiders(entity_counter=self.entity_counter, spiders_max_level=self.spiders_max_level)
  251.         spider.threat_for = self.threat_for(spider)
  252.         symmetric_spider.threat_for = self.threat_for(symmetric_spider)
  253.         self.entity_counter += 2
  254.         self.spiders.append(spider)
  255.         self.spiders.append(symmetric_spider)
  256.  
  257.     def init_tk(self):
  258.         """
  259.            Initialisation de la partie graphique de l'application et entités de jeu
  260.        :return:
  261.        """
  262.         self.canvas = Canvas(width=MAP_WIDTH * ZOOM, height=MAP_HEIGHT * ZOOM, bg='white')
  263.         self.canvas.pack(expand=YES, fill=BOTH)
  264.  
  265.         self.console = Label(self.root, text="Hello World!")
  266.         self.console.pack(pady=20)
  267.  
  268.         # Entities
  269.         self.my_base.create_circle(canvas=self.canvas, color='green')
  270.         self.my_base.label = Label(self.root)
  271.         self.my_base.update_label()
  272.         self.my_base_detect_radius.create_circle(canvas=self.canvas, color='orange')
  273.         self.enemy_base.create_circle(canvas=self.canvas, color='green')
  274.         self.enemy_base.label = Label(self.root)
  275.         self.enemy_base.update_label()
  276.         self.enemy_base_detect_radius.create_circle(canvas=self.canvas, color='orange')
  277.  
  278.         for e in self.heroes + self.spiders:
  279.             e.label = Label(self.root)
  280.             e.update_label()
  281.             # e.label.pack(pady=20)
  282.             color = 'red' if e.type == EntityType.SPIDER else 'blue' if e.type == EntityType.PLAYER else 'green'
  283.             e.create_circle(canvas=self.canvas, color=color)
  284.  
  285.         self.canvas.bind_all("<space>", self.callback)
  286.         self.root.mainloop()
  287.  
  288.     # All of this would do better as a subclass of Canvas with specialize methods
  289.  
  290.     def update_fog(self, player: EntityType):
  291.         player_base: Entity = self.enemy_base if player == EntityType.OPPONENT else self.my_base
  292.         player_heroes: List[Entity] = [h for h in self.heroes if h.type == player]
  293.         enemy_heroes: List[Entity] = [h for h in self.heroes if h.type != player]  # only handle visible enemy heroes
  294.         for spider in self.spiders:
  295.             if spider.dist(player_base) <= 6000 or any([h for h in player_heroes if h.type == player and spider.dist(h) <= 800]):
  296.                 spider.visible = True
  297.             else:
  298.                 spider.visible = False
  299.         for enemy in enemy_heroes:
  300.             if enemy.dist(player_base) <= 6000 or any([h for h in player_heroes if h.type == player and enemy.dist(h) <= 800]):
  301.                 enemy.visible = True
  302.             else:
  303.                 enemy.visible = False
  304.  
  305.     def update_entities_after_wind(self, hero: Entity, target: array):
  306.         u: array = target - hero.location
  307.         v: array = u / norm(u)
  308.         for entity in self.heroes + self.spiders:
  309.             if entity.dist(hero) <= 1280 and entity != hero:
  310.                 new_location = entity.location + 2200 * v
  311.                 entity.move(canvas=self.canvas, target=new_location)
  312.  
  313.     """ Referee SC2022:
  314.        https://github1s.com/CodinGame/SpringChallenge2022/blob/main/src/main/java/com/codingame/game/Referee.java#L1009
  315.        private void performGameUpdate(int turn) {
  316.            doControl();
  317.            doShield();
  318.            moveHeroes();
  319.            Map<Player, Integer[]> manaGain = performCombat();
  320.            doPush();
  321.            moveMobs();
  322.            shieldDecay();
  323.            spawnNewMobs(turn);
  324.    
  325.            manaGain.forEach((player, amount) -> {
  326.                player.gainMana(amount);
  327.            });
  328.        }
  329.    """
  330.  
  331.     def game_update(self):
  332.         """
  333.            Mise à jour des entités à chaque tour à partir des actions des héros générées par la fonction callback (IA du jeu)
  334.        :return:
  335.        """
  336.         # update game counters
  337.         self.turns += 1
  338.         self.spawn_cooldown -= 1 if self.spawn_cooldown else 0
  339.  
  340.         # perform heroes actions and display of heroes
  341.         for hero in self.heroes:
  342.             if hero.action.type == 'MOVE':
  343.                 hero.move(canvas=self.canvas, target=hero.action.target)
  344.             elif hero.action.type == 'WIND':
  345.                 self.update_entities_after_wind(hero=hero, target=hero.action.target)
  346.                 hero.label['text'] = 'WIND'
  347.                 if hero.type == EntityType.PLAYER:
  348.                     self.my_mana -= 10
  349.                 else:
  350.                     self.enemy_mana -= 10
  351.  
  352.         # Update mana, wild mana and spiders health
  353.         for hero in self.heroes:
  354.             for spider in self.spiders:
  355.                 if hero.dist(spider) <= hero.radius:
  356.                     if hero.type == EntityType.OPPONENT:
  357.                         self.enemy_mana += 2
  358.                     else:
  359.                         self.my_mana += 2
  360.                     spider.health -= 2
  361.                     if spider.health <= 0 and spider.dist(hero) <= 800:
  362.                         if hero.type == EntityType.PLAYER and hero.dist(self.my_base) > 5000:
  363.                             self.my_wild_mana += 1
  364.                         elif hero.type == EntityType.OPPONENT and hero.dist(self.enemy_base) > 5000:
  365.                             self.enemy_wild_mana += 1
  366.  
  367.         # Update display of spiders
  368.         for spider in self.spiders:
  369.             if spider.health > 0:
  370.                 if spider.dist(self.my_base) <= 300:
  371.                     self.my_base.health -= 1
  372.                     self.my_base.update_label()
  373.                     self.canvas.delete(spider.circle)
  374.                     spider.label.destroy()
  375.                     self.spiders.remove(spider)
  376.                 elif spider.dist(self.enemy_base) <= 300:
  377.                     self.enemy_base.health -= 1
  378.                     self.enemy_base.update_label()
  379.                     spider.delete_from(canvas=self.canvas)
  380.                     self.spiders.remove(spider)
  381.                 elif spider.dist(self.my_base) <= 5000:
  382.                     spider.move(canvas=self.canvas, target=self.my_base)
  383.                 elif spider.dist(self.enemy_base) <= 5000:
  384.                     spider.move(canvas=self.canvas, target=self.enemy_base)
  385.                 elif not inside_map(spider.location):
  386.                     spider.delete_from(canvas=self.canvas)
  387.                     self.spiders.remove(spider)
  388.                 else:
  389.                     spider.move(canvas=self.canvas)
  390.             else:
  391.                 spider.delete_from(canvas=self.canvas)
  392.                 self.spiders.remove(spider)
  393.  
  394.         if self.my_base.health <= 0:
  395.             self.console['text'] = f'OPPONENT WINS after {self.turns} turns!'
  396.             self.canvas.unbind_all("<space>")
  397.         elif self.enemy_base.health <= 0:
  398.             self.console['text'] = f'PLAYER WINS after {self.turns} turns!'
  399.             self.canvas.unbind_all("<space>")
  400.         elif self.turns == self.max_turns:
  401.             if self.enemy_base.health > self.my_base.health:
  402.                 self.console['text'] = f'OPPONENT WINS!'
  403.             elif self.enemy_base.health < self.my_base.health:
  404.                 self.console['text'] = f'PLAYER WINS!'
  405.             else:
  406.                 if self.my_wild_mana == self.enemy_wild_mana:
  407.                     self.console['text'] = f'THIS IS A DRAW!'
  408.                 else:
  409.                     if self.my_wild_mana < self.enemy_wild_mana:
  410.                         self.console['text'] = f'OPPONENT WINS!'
  411.                     elif self.my_wild_mana > self.enemy_wild_mana:
  412.                         self.console['text'] = f'PLAYER WINS!'
  413.                 self.console['text'] += f'\nWILD MANA | Player = {self.my_wild_mana} - Opponent = {self.enemy_wild_mana}'
  414.             self.canvas.unbind_all("<space>")
  415.         else:
  416.             if not self.spawn_cooldown:
  417.                 self.spawn_cooldown = self.respawn_value
  418.                 spider, symmetric_spider = spawn_spiders(entity_counter=self.entity_counter, spiders_max_level=self.spiders_max_level)
  419.                 spider.threat_for = self.threat_for(spider)
  420.                 symmetric_spider.threat_for = self.threat_for(symmetric_spider)
  421.                 self.entity_counter += 2
  422.                 self.spiders.append(spider)
  423.                 self.spiders.append(symmetric_spider)
  424.                 for s in [spider, symmetric_spider]:
  425.                     s.label = Label(self.root)
  426.                     s.update_label()
  427.                     s.create_circle(canvas=self.canvas, color='red')
  428.             self.console['text'] = f'BASE HEALTH | Player = {self.my_base.health} - Opponent = {self.my_base.health}'
  429.             self.console['text'] += f'\nMANA | Player = {self.my_mana} - Opponent = {self.enemy_mana}'
  430.  
  431.         for hero in self.heroes:
  432.             hero.action = None
  433.  
  434.     def wood_2_ia(self, player: EntityType):
  435.         base: Entity = self.enemy_base if player == EntityType.OPPONENT else self.my_base
  436.  
  437.         player_heroes: List[Entity] = [h for h in self.heroes if h.type == player]
  438.  
  439.         visible_spiders: List[Entity] = [s for s in self.spiders if s.visible]
  440.  
  441.         if visible_spiders:
  442.             spiders = sorted(self.spiders, key=lambda s: s.dist(base))
  443.             while player_heroes and spiders:
  444.                 spider: Entity = spiders.pop(0)
  445.                 hero: Entity = min(player_heroes, key=lambda h: h.dist(spider))
  446.                 player_heroes.remove(hero)
  447.                 hero.action = Action(type='MOVE', target=spider.location)
  448.  
  449.         for hero in player_heroes:
  450.             if not hero.action:
  451.                 hero.action = Action(type='WAIT')
  452.  
  453.         for hero in player_heroes:
  454.             for h in self.heroes:
  455.                 if h.id == hero.id:
  456.                     # debug('prout wood 2')
  457.                     h.action = hero.action
  458.  
  459.     def wood_1_ia(self, player: EntityType):
  460.         # ia_bronze_defense
  461.         # spring-challenge-2022-Silver_570_defense_only
  462.  
  463.         my_health, enemy_health = (self.my_base.health, self.enemy_base.health) if player == EntityType.PLAYER else (self.enemy_base.health, self.my_base.health)
  464.         my_mana, enemy_mana = (self.my_mana, self.enemy_mana) if player == EntityType.PLAYER else (self.enemy_mana, self.my_mana)
  465.         my_base, enemy_base = (self.my_base, self.enemy_base) if player == EntityType.PLAYER else (self.enemy_base, self.my_base)
  466.  
  467.         player_heroes: List[Entity] = [h for h in self.heroes if h.type == player]
  468.  
  469.         spiders: List[Entity] = [s for s in self.spiders if s.visible]
  470.  
  471.         """ DEFENSE ONLY """
  472.         defenders: List[Entity] = player_heroes
  473.  
  474.         if spiders:
  475.             ranked_spiders: List[Entity] = sorted(spiders, key=lambda s: s.threat_level(base=my_base), reverse=True)
  476.             while ranked_spiders and defenders:
  477.                 wind_heroes: List[Entity] = [(h, len([s for s in ranked_spiders if s.dist(my_base) <= 5000 and h.dist(s) <= 1280])) for h in defenders]
  478.                 if my_mana >= 20 and wind_heroes:
  479.                     hero = max(wind_heroes, key=lambda x: x[1])[0]
  480.                     hero.action = Action(type='SPELL WIND', target=enemy_base.location)
  481.                     my_mana -= 10
  482.                 else:
  483.                     spider: Entity = ranked_spiders.pop(0)
  484.                     hero: Entity = min(defenders, key=lambda h: h.dist(spider))
  485.                     hero.action = Action(type='MOVE', target=spider.location + spider.velocity)
  486.                 defenders.remove(hero)
  487.                 ranked_spiders: List[Entity] = sorted([s for s in ranked_spiders if s.health > 0], key=lambda s: s.threat_level(base=my_base), reverse=True)
  488.         else:
  489.             default_positions: List[array] = self.get_default_positions(player=player)
  490.             for hero in defenders:
  491.                 hero.action = Action(type='MOVE', target=default_positions[player_heroes.index(hero)])
  492.  
  493.         for hero in player_heroes:
  494.             if not hero.action:
  495.                 hero.action = Action(type='WAIT')
  496.  
  497.         for hero in player_heroes:
  498.             for h in self.heroes:
  499.                 if h.id == hero.id:
  500.                     h.action = hero.action
  501.  
  502.     def callback(self, event):
  503.         """
  504.            IA for Dummies (fonction tour par tour de Codingame)
  505.        :param event:
  506.        :return:
  507.        """
  508.         self.update_fog(player=EntityType.OPPONENT)
  509.         self.wood_2_ia(player=EntityType.OPPONENT)
  510.         # self.wood_1_ia(player=EntityType.OPPONENT) # BUGGY :-(
  511.  
  512.         self.update_fog(player=EntityType.PLAYER)
  513.         self.wood_2_ia(player=EntityType.PLAYER)
  514.  
  515.         self.game_update()
  516.  
  517.  
  518. def read_int_value(message: str, max_value: int) -> int:
  519.     while True:
  520.         try:
  521.             print(f'{message} [1-{max_value}] ')
  522.             value = int(input())
  523.             if not value or not 1 <= int(value) <= max_value:
  524.                 raise ValueError
  525.         except ValueError:
  526.             continue
  527.         except UnboundLocalError:
  528.             continue
  529.         finally:
  530.             return int(value)
  531.  
  532.  
  533. if __name__ == "__main__":
  534.     MAP_WIDTH, MAP_HEIGHT = 17630, 9000
  535.     mac_display_resolution = 1920, 1080
  536.     ZOOM = 0.1
  537.     SPAWN_COOLDOWN = 2
  538.     reduce = lambda x_list: map(lambda x: x * ZOOM, x_list)
  539.  
  540.     max_turns = read_int_value(message="Enter max number of rounds:", max_value=300)
  541.     respawn_value = read_int_value(message="Frequency of respawn spiders:", max_value=10)
  542.     spiders_max_level = read_int_value(message="Maximum level of spiders:", max_value=10)
  543.     game: Game = Game(max_turns=int(max_turns), respawn_value=respawn_value, spiders_max_level=spiders_max_level)
  544.     game.init()
  545.     game.init_tk()
  546.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement