Ejemplo n.º 1
0
 def halfrotate(i, a, f):
     if i == 1:
         return deque()
     elif i == 0:
         rcenter = Unit(None, f.right + 1,
                        a.bottom + 1)  # minus unit radius
     elif i == 2:
         rcenter = Unit(None, f.left - 1, a.top - 1)  # minus unit radius
     return deque([select_vehicles(a), rotate(pi, rcenter)])
Ejemplo n.º 2
0
def test_group_renew():
    group = Group()

    u1 = Unit(1, 1)
    group.addUnit(u1)
    assert group.unitList == [u1]

    u2 = Unit(2, 2)
    group.renew([u2])
    assert group.unitList == [u2]
Ejemplo n.º 3
0
    def setStrategyAttackGate(self):

        # if the position is good or i am swinging >> let's strike!
        if ((self.me.get_distance_to_unit(
                self.attackCircle) < self.attackCircle.radius
             and abs(self.me.get_angle_to_unit(self.attackCircle)) <
             self.attackAngle) or self.me.state == HockeyistState.SWINGING):
            strikeX = self.opponentPlayer.net_front
            if self.me.y < self.rink_center_y:
                strikeY1 = self.opponentPlayer.net_bottom - self.world.puck.radius
                strikeY2 = self.opponentPlayer.net_bottom - 2.0 * self.world.puck.radius
            else:
                strikeY1 = self.opponentPlayer.net_top + self.world.puck.radius
                strikeY2 = self.opponentPlayer.net_top + 2.0 * self.world.puck.radius

            unit1 = Unit(9910, 0.0, 0.0, strikeX, strikeY1, 0.0, 0.0, 0.0, 0.0)
            unit2 = Unit(9911, 0.0, 0.0, strikeX, strikeY2, 0.0, 0.0, 0.0, 0.0)
            dist1 = min([
                dist2segment(self.me, unit1, opponent)
                for opponent in self.opponentUnits
            ])
            dist2 = min([
                dist2segment(self.me, unit2, opponent)
                for opponent in self.opponentUnits
            ])

            if dist1 < dist2:
                #print "trystrike2 " + str(dist1) + " " + str(dist2)
                self.tryStrike(strikeX, strikeY2)
            else:
                #print "trystrike1 " + str(dist1) + " " + str(dist2)
                self.tryStrike(strikeX, strikeY1)

            return True

        if abs(self.me.x -
               self.opponentPlayer.net_front) > self.game.world_width / 2.0:
            if self.me.y < self.rink_center_y:
                self.trySkate(self.attackCircle.x,
                              0.2 * self.game.world_height)
            else:
                self.trySkate(self.attackCircle.x,
                              0.8 * self.game.world_height)
        else:
            if self.me.y < self.rink_center_y:
                self.trySkate(
                    self.attackCircle.x,
                    self.opponentPlayer.net_bottom - self.world.puck.radius)
            else:
                self.trySkate(
                    self.attackCircle.x,
                    self.opponentPlayer.net_top + self.world.puck.radius)
        return True
Ejemplo n.º 4
0
 def do_shuffle(s: MyStrategy, w: World, g: Game, m: Move):
     vs = s.worldstate.vehicles
     classes = [
         reduce(lambda x, y: y | x, list(map(lambda x: vs.by_type[x], i)))
         for i in types
     ]
     pv = vs.by_player[vs.me]
     allunits = vs.resolve(pv)
     fullarea = get_square(allunits)
     pointofscale = Unit(None, fullarea.left, fullarea.top)
     result = deque()
     for clas in range(len(classes)):
         units = vs.resolve(classes[clas] & pv)
         area = get_square(units)
         pointofscale = Unit(None, area.left, area.top)
         spreadflag = "spread:" + str(clas)
         shiftflag = "shifted:" + str(clas)
         mergeflag = "merged:" + str(clas)
         spread_groups = select_types(types[clas], s.full_area)
         spread_groups += do_and_check(
             scale(pointofscale, len(types[clas])), spreadflag,
             classes[clas])
         shift_groups = deque()
         merge_groups = deque()
         slowpockarea = get_square(vs.resolve(vs.by_type[types[clas][0]]))
         for i in range(1, len(types[clas])):
             shift = 4 * i / len(types[clas])  # 4 - vehicle diameter
             thetype = types[clas][i]
             destination = Unit(None, 0, shift)
             group_of_interest = vs.by_type[thetype] & pv
             goi_area = get_square(vs.resolve(group_of_interest))
             shift_groups += deque(
                 [select_vehicles(s.full_area, vtype=thetype)])
             shift_groups += do_and_check(move(destination), shiftflag,
                                          group_of_interest)
             aligned_destination = Unit(None,
                                        slowpockarea.left - goi_area.left,
                                        0)
             merge_groups += deque(
                 [select_vehicles(s.full_area, vtype=thetype)])
             merge_groups += do_and_check(move(aligned_destination),
                                          mergeflag, group_of_interest)
         tight_groups = select_types(types[clas], s.full_area)
         tight_groups += do_and_check(scale(pointofscale, 0.1), tightflag,
                                      classes[clas])
         result += shift_groups
         result += deque([at_flag(spreadflag, 1, merge_groups)])
         result += deque([at_flag(shiftflag, 1, spread_groups)])
         result += deque([at_flag(mergeflag, 1, tight_groups)])
         result += deque(
             [at_flag(tightflag, 2, deque([fill_flag("shuffled")]))])
     s.current_action = result + s.current_action
Ejemplo n.º 5
0
def test_group_add_units():
    group = Group()

    u1 = Unit(1, 1)
    u2 = Unit(2, 2)
    u3 = Unit(3, 3)

    group.addUnit(u1)
    group.addUnit(u2)
    group.addUnit(u3)

    assert group.unitList == [u1, u2, u3]
    assert group.getX() == 2 # mass X
    assert group.getY() == 2 # mass Y
Ejemplo n.º 6
0
 def do_hunt(s: MyStrategy, w: World, g: Game, m: Move):
     vs = s.worldstate.vehicles
     myv = list(vs.resolve(vs.by_group[gr]))
     mya = get_square(myv)
     density = len(myv) / mya.area()
     #print("Density is: " + str(density))
     #print("Area is: " + str(mya))
     #print("Amount is: " + str(len(myv)))
     if density < criticaldensity:
         if len(vs.by_group[gr] & vs.by_group[gr + 1]) == 0:
             destination = get_center(myv)
             aerials = vs.by_group[gr + 1]
             pos = get_center(list(vs.resolve(aerials)))
             targetv = Unit(None, destination.x - pos.x,
                            destination.y - pos.y)
             s.current_action.append(
                 select_vehicles(s.full_area, group=gr + 1))
             s.current_action.append(move(targetv))
             s.current_action.append(
                 at_move_end(
                     aerials,
                     deque([
                         select_vehicles(s.full_area, group=gr + 1),
                         group(gr),
                     ])))
         s.current_action += deque([hurricane(gr), hunt(gr, game)])
     else:
         huntchain = deque([
             select_vehicles(s.full_area, group=gr),
             move_to_enemies(
                 gr, game.tank_speed * game.swamp_terrain_speed_factor),
             wait(60),
             hunt(gr, game)
         ])
         s.current_action += huntchain
Ejemplo n.º 7
0
def get_center(vehicles: list):
    length = len(vehicles)
    assert (length > 0)
    center = length // 2
    xsort = sorted(vehicles, key=lambda x: x.x)
    ysort = sorted(vehicles, key=lambda x: x.y)
    return Unit(None, xsort[center].x, ysort[center].y)
Ejemplo n.º 8
0
 def get_unit(self, name):
     con = lite.connect(os.path.join(self.database_path, 'easybeer.db'))
     c = con.cursor()
     c.execute("""select * from units where name=:name""", {'name': name})
     u = c.fetchone()
     c.close()
     con.close()
     if u: return Unit(u[0], u[1])
     else: return None
Ejemplo n.º 9
0
    def apply_default_values(self):
        self.model.update_unit(Unit('temperature', 'Celsius'))
        self.model.update_unit(Unit('delta_temperature', 'Celsius'))
        self.model.update_unit(Unit('water_volume', 'Liter'))
        self.model.update_unit(Unit('malt_mass', 'Kilogram'))
        self.model.update_unit(Unit('yeast_mass', 'Gram'))
        self.model.update_unit(Unit('yeast_rate', 'Billion/°P/Liter'))
        self.model.update_unit(Unit('hop_rate', 'Gram per liter'))
        self.model.update_unit(Unit('hop_mass', 'Gram'))

        self.close()
Ejemplo n.º 10
0
def test_unit_creation():
    _x = 1
    _y = 1
    _hp = 5
    _typeId = Terran.SCV
    unit = Unit(x=_x, y=_y, hp=_hp, typeId=_typeId, idn=0)

    assert unit.getX() == _x
    assert unit.getY() == _y
    assert unit.getHp() == _hp
    assert unit.getTypeId() == _typeId
Ejemplo n.º 11
0
    def tryStrike(self, strikeX, strikeY):
        PASS_ACCURACY = pi / 3.0
        STRIKE_ACCURACY = 1.0 * pi / 180.0

        angle = self.me.get_angle_to(strikeX, strikeY)

        self.move_turn = angle
        self.move_speed_up = 1.0

        danger = False
        for opponentUnit in self.opponentUnits:
            if (opponentUnit.get_distance_to_unit(
                    self.me) < 1.1 * self.game.stick_length
                    and abs(opponentUnit.get_angle_to_unit(
                        self.me)) < 0.6 * self.game.stick_sector
                    and opponentUnit.state != HockeyistState.KNOCKED_DOWN):
                danger = True

            if (opponentUnit.get_distance_to_unit(
                    self.world.puck) < 1.1 * self.game.stick_length
                    and abs(opponentUnit.get_angle_to_unit(
                        self.world.puck)) < 0.7 * self.game.stick_sector
                    and opponentUnit.state != HockeyistState.KNOCKED_DOWN):
                danger = True

        if abs(angle) < STRIKE_ACCURACY and self.me.get_distance_to_unit(
                self.attackCircle) > self.attackPassDistance:
            if self.me.swing_ticks < self.game.max_effective_swing_ticks and not danger:
                #print "swing: " + str(self.me.swing_ticks)
                self.move_action = ActionType.SWING

                return True

        if (self.me.state == HockeyistState.SWINGING
                or abs(angle) < STRIKE_ACCURACY):
            #print "strike puck: " + str(self.me.swing_ticks)
            self.move_action = ActionType.STRIKE

            return True

        if (abs(angle) < PASS_ACCURACY
                #and danger
                and self.me.state != HockeyistState.SWINGING and
                self.me.get_distance_to_unit(
                    self.attackCircle) < self.attackPassDistance):
            print "strike pass"
            unit = Unit(9912, 0.0, 0.0, strikeX, strikeY, 0.0, 0.0, 0.0, 0.0)
            self.tryPass('Strike', unit)
            return True

        return False
Ejemplo n.º 12
0
    def create(self, *, round: int) -> Unit:
        attrs = {}
        uniforms = []

        for name, v in self.params.items():
            if isinstance(v, Param):
                x, attrs[name] = v.sample(round=round)
                uniforms.append(x)
            else:
                attrs[name] = v

        price = int((1 + mean(uniforms)) * 100 * round)

        return Unit(**attrs, price=price)
Ejemplo n.º 13
0
 def each(i, a, f):
     step = a.bottom - a.top
     center = f.get_center().y
     distributed_size = parts * (3 * step + 4)
     top_from_bottom = ss.full_area.bottom - distributed_size
     top_from_center = center - distributed_size / 2
     top = (top_from_center < 0 and f.top + 10
            or top_from_bottom < top_from_center and top_from_bottom
            or top_from_center)
     target = Unit(None, 0, i * (2 * step + 4) - top)
     return deque([
         select_vehicles(a),
         move(target),
     ])
Ejemplo n.º 14
0
 def do_kill(s: MyStrategy, w: World, g: Game, m: Move):
     enemy = w.get_opponent_player()
     vs = s.worldstate.vehicles
     epicenter = Unit(None, enemy.next_nuclear_strike_x,
                      enemy.next_nuclear_strike_y)
     radius = g.tactical_nuclear_strike_radius + 10
     enemies = vs.resolve(vs.by_player[vs.opponent])
     clusters = clusterize(enemies)
     navigator = enemy.next_nuclear_strike_vehicle_id
     in_cluster_of_len = 0
     for c in clusters:
         cluset = set()
         for i in c:
             cluset.add(enemies[i].id)
         if navigator in cluset:
             in_cluster_of_len = len(c)
             break
     expl_area = Area(epicenter.x - radius, epicenter.x + radius,
                      epicenter.y - radius, epicenter.y + radius)
     my_avias = vs.by_player[vs.me] & (vs.by_type[VehicleType.HELICOPTER]
                                       | vs.by_type[VehicleType.FIGHTER])
     my_avias_len = len(my_avias)
     if my_avias_len >= in_cluster_of_len:
         target = vs[navigator]
         shift = Unit(None, target.x - epicenter.x, target.y - epicenter.y)
         result = [
             select_vehicles(expl_area, vtype=VehicleType.HELICOPTER),
             move(shift),
             select_vehicles(expl_area, vtype=VehicleType.FIGHTER),
             move(shift),
         ]
     else:
         result = [select_vehicles(expl_area), scale(epicenter, 10)]
     result.append(wait(enemy.next_nuclear_strike_tick_index -
                        w.tick_index))
     s.current_action = deque(result) + s.current_action
Ejemplo n.º 15
0
 def read_inputs(self):
     u = []
     temperature = self.temperature_combo.currentText()
     u.append(Unit('temperature', temperature))
     u.append(Unit('delta_temperature', temperature))
     water_volume = self.water_volume_combo.currentText()
     u.append(Unit('water_volume', water_volume))
     malt_mass = self.malt_mass_combo.currentText()
     u.append(Unit('malt_mass', malt_mass))
     yeast_mass = self.yeast_mass_combo.currentText()
     u.append(Unit('yeast_mass', yeast_mass))
     hop_rate = self.hop_rate_combo.currentText()
     u.append(Unit('hop_rate', hop_rate))
     hop_mass = self.hop_mass_combo.currentText()
     u.append(Unit('hop_mass', hop_mass))
     'this is a special one'
     u.append(Unit('yeast_rate', 'Billion/°P/' + water_volume))
     return u
Ejemplo n.º 16
0
def patrol(me, world, game, move):
    global gotox
    global gotoy
    global need_request

    deltax = 6
    deltay = 4

    if gotox < 0 or gotoy < 0 or me.get_distance_to(gotox, gotoy) < 3:
        #print "patrol: where to go?"
        commander = [
            trooper for trooper in world.troopers
            if trooper.teammate and trooper.type == TrooperType.COMMANDER
        ]
        if commander:
            need_request = True
            gotox, gotoy = -1, -1
            print "patrol: made request"
            #move.action = ActionType.END_TURN
            #return False
            #else:
        print "patrol: cycle move"
        if me.x <= world.width / 2 and me.y <= world.height / 2:
            gotox, gotoy = world.width - deltax, deltay
            #print "patrol: new direction east"
        elif me.x >= world.width / 2 and me.y <= world.height / 2:
            gotox, gotoy = world.width - deltax, world.height - deltay
            #print "patrol: new direction south"
        elif me.x >= world.width / 2 and me.y >= world.height / 2:
            gotox, gotoy = deltax, world.height - deltay
            #print "patrol: new direction west"
        elif me.x <= world.width / 2 and me.y >= world.height / 2:
            gotox, gotoy = deltax, deltay
            #print "patrol: new direction north"

    print "patrol: me", me.x, me.y
    print "patrol: direction", gotox, gotoy

    if me.action_points >= get_move_cost(me, world, game, move):
        unit = Unit(-1000, gotox, gotoy)
        target = find_free_cell(me, world, game, move, unit)
        if move_to_unit(me, world, game, move, target):
            return True

    move.action = ActionType.END_TURN
    #print "patrol: cannot move"
    return False
Ejemplo n.º 17
0
 def adjust(clas):
     ## Perform a vertical move
     secondturn = deque()
     name = namefull + ":" + str(clas)
     counted = 0
     for i in [0, 2]:  # lines except central
         line = lines[i]
         target = Unit(None, 0, lines[1].top - line.top)
         for tt in types[clas]:
             squadtomove = vs.in_area(line) & vs.by_type[tt]
             if len(squadtomove) > 0:
                 secondturn += do_and_check(
                     [select_vehicles(s.full_area, vtype=tt),
                      move(target)], name, squadtomove)
                 counted += 1
     return (deque([at_flag(name, counted, deque([fill_flag(namefull)]))]) +
             secondturn)
Ejemplo n.º 18
0
def find_free_cell(me, world, game, move, unit):
    for i in range(min(world.width, world.height)):
        for j in [
                z for z in range(unit.x - i, unit.x + i)
                if 0 <= z <= world.width
        ]:
            for k in [
                    z for z in range(unit.y - i, unit.y + i)
                    if 0 <= z <= world.height
            ]:
                if world.cells[j][k] == CellType.FREE:
                    target = Unit(-1000, j, k)
                    #print "find_free_cell: original ", unit.x, ", ", unit.y
                    #print "find_free_cell: target found ", j, ", ", k
                    return target

    #print "find_free_cell: cannot find free cell ", unit.x, ", ", unit.y
    return unit
Ejemplo n.º 19
0
def commander_request(me, world, game, move):
    global gotox
    global gotoy
    global need_request

    if me.type == TrooperType.COMMANDER:
        players = [
            player for player in world.players
            if player.name != 'zoldatoff' and player.name != 'MyStrategy'
            and player.approximate_x >= 0 and player.approximate_y >= 0
        ]

        if players:
            min_player = players[0]
            min_distance = 10000
            for player in players:
                unit = Unit(-player.id, player.approximate_x,
                            player.approximate_y)
                distance = get_distance(me, world, game, move, unit)
                if distance < min_distance:
                    min_distance = distance
                    min_player = player

            if gotox >= 0 and gotoy >= 0:
                gotox, gotoy = min_player.approximate_x, min_player.approximate_y
                need_request = False
                print "commander_request: new destination", gotox, gotoy
                return False

    if (me.type == TrooperType.COMMANDER and
            me.action_points >= game.commander_request_enemy_disposition_cost
            and need_request):
        move.action = ActionType.REQUEST_ENEMY_DISPOSITION
        need_request = False
        print "commander_request: request sent"
        return True

    move.action = ActionType.END_TURN
    #print "commander_request: no action"
    return False
Ejemplo n.º 20
0
def use_bonus_grenade(me, world, game, move):
    if (me.holding_grenade and me.action_points >= game.grenade_throw_cost):
        my_troopers = [
            trooper for trooper in world.troopers if trooper.teammate
        ]
        enemy_troopers = [
            trooper for trooper in world.troopers if not trooper.teammate
        ]

        max_damage = 0

        for x in [
                z for z in range(me.x - int(game.grenade_throw_range), me.x +
                                 int(game.grenade_throw_range))
                if 0 <= z <= world.width
        ]:
            for y in [
                    z
                    for z in range(me.y - int(game.grenade_throw_range), me.y +
                                   int(game.grenade_throw_range))
                    if 0 <= z <= world.height
            ]:
                damage_to_me = False
                unit = Unit(-1000, x, y)

                if me.get_distance_to_unit(unit) > game.grenade_throw_range:
                    continue

                for my_trooper in my_troopers:
                    if my_trooper.get_distance_to_unit(unit) < 1.05:
                        damage_to_me = True
                        break

                if damage_to_me:
                    continue

                damage = 0

                for enemy_trooper in enemy_troopers:
                    if 0.95 < enemy_trooper.get_distance_to_unit(unit) < 1.05:
                        damage = damage + game.grenade_collateral_damage
                    elif enemy_trooper.get_distance_to_unit(unit) < 0.95:
                        damage = damage + game.grenade_direct_damage

                if damage > max_damage:
                    max_damage = damage
                    max_unit = unit

        if ((me.stance == TrooperStance.STANDING
             and 1.0 * max_damage / game.grenade_throw_cost * me.shoot_cost /
             me.standing_damage > 1.0)
                or (me.stance == TrooperStance.KNEELING
                    and 1.0 * max_damage / game.grenade_throw_cost *
                    me.shoot_cost / me.kneeling_damage > 1.0) or
            (me.stance == TrooperStance.PRONE and 1.0 * max_damage /
             game.grenade_throw_cost * me.shoot_cost / me.prone_damage > 1.0)):
            print "use_bonus_grenade: damage = ", max_damage
            print "use_bonus_grenade: me ", me.x, me.y
            print "use_bonus_grenade: target", max_unit.x, max_unit.y
            print "use_bonus_grenade: distance", me.get_distance_to_unit(
                max_unit)
            move.action = ActionType.THROW_GRENADE
            move.x = max_unit.x
            move.y = max_unit.y
            return True

    #print "use_bonus_grenade: cannot use grenade"
    move.action = ActionType.END_TURN
    return False
Ejemplo n.º 21
0
def test_unit_change_invis():
    unit = Unit(x=0, y=0)

    assert unit.invis == False
    unit.changeInvis()
    assert unit.invis == True
Ejemplo n.º 22
0
def do_shuffle(ss, w: World, g: Game, m: Move):
    vss = ss.worldstate.vehicles
    pv = vss.by_player[vss.me]
    myv = vss.resolve(pv)
    mya = get_square(myv)
    #print("Area after alighment")
    #print(mya)
    parts = 10
    step = (mya.bottom - mya.top) / parts
    central = Area.copy(ss.full_area)
    fragment_area = get_square(vss.resolve(pv & vss.by_type[VehicleType.IFV]))
    fragment = fragment_area.right - fragment_area.left
    central.left = (mya.left + mya.right - fragment) / 2
    central.right = central.left + fragment
    righter = Area.copy(ss.full_area)
    righter.right = mya.right
    righter.left = mya.right - fragment
    lefter = Area.copy(ss.full_area)
    lefter.left = mya.left
    lefter.right = mya.left + fragment

    #fourth_turn = deque([
    #select_vehicles(ss.full_area),
    #rotate(-pi/2, Unit(None, central.right + fragment/2, mya.top + fragment*2))
    def halfrotate(i, a, f):
        if i == 1:
            return deque()
        elif i == 0:
            rcenter = Unit(None, f.right + 1,
                           a.bottom + 1)  # minus unit radius
        elif i == 2:
            rcenter = Unit(None, f.left - 1, a.top - 1)  # minus unit radius
        return deque([select_vehicles(a), rotate(pi, rcenter)])

    fifth_turn = deque([
        at_flag("rerotated", 1, deque([fill_flag("formation_done")])),
        devide(vss.by_group[1], halfrotate, 3, "rerotated")
    ])
    fourth_turn = (do_and_check(tight(pv), "tighted", pv) +
                   deque([at_flag("tighted", 1, fifth_turn)]))
    third_turn = deque([
        select_vehicles(lefter),
        move(Unit(None, central.left - lefter.left, 0)),
        select_vehicles(righter),
        move(Unit(None, central.left - righter.left, 0)),
        wait(10),
        at_move_end(pv, fourth_turn)
    ])
    second_turn = deque([
        select_vehicles(ss.full_area, vtype=VehicleType.FIGHTER),
        move(Unit(None, 0, step + 1)),
        select_vehicles(ss.full_area, vtype=VehicleType.ARRV),
        move(Unit(None, 0, step + 1)),
        select_vehicles(ss.full_area, vtype=VehicleType.IFV),
        move(Unit(None, 0, 2 * step + 3)),
        wait(10),
        at_move_end(pv, third_turn)
    ])

    def each(i, a, f):
        step = a.bottom - a.top
        center = f.get_center().y
        distributed_size = parts * (3 * step + 4)
        top_from_bottom = ss.full_area.bottom - distributed_size
        top_from_center = center - distributed_size / 2
        top = (top_from_center < 0 and f.top + 10
               or top_from_bottom < top_from_center and top_from_bottom
               or top_from_center)
        target = Unit(None, 0, i * (2 * step + 4) - top)
        return deque([
            select_vehicles(a),
            move(target),
        ])

    ss.current_action.appendleft(devide(pv, each, parts, "loosed"))
    ss.current_action.appendleft(at_flag("loosed", 1, second_turn))
Ejemplo n.º 23
0
 def get_center(self):
     return Unit(None, (self.left + self.right) / 2,
                 (self.top + self.bottom) / 2)
Ejemplo n.º 24
0
 def decode_objects(d):
     if d.get("__type__") == "Tank":
         return Tank(0, "", 0, d["x"], d["y"], 0, 0, d["angle"], 0, d["turret_relative_angle"], 0, 0, 0, 0, 0, 0, TankType.MEDIUM)
     elif d.get("__type__") == "Unit":
         return Unit(0, d["width"], d["height"], d["x"], d["y"], 0, 0, d["angle"], 0)
     return d
Ejemplo n.º 25
0
def fictive_unit(prototype, x, y, angle=None):
    if angle is None:
        angle = prototype.angle
    return Unit(0, prototype.width, prototype.height, x, y, 0, 0, angle, 0)
Ejemplo n.º 26
0
    def trySkate(self, skateX, skateY, zeroSpeed=False):
        if self.world.puck.owner_hockeyist_id == self.me.id:
            #print "trySkate: calcAcceleration1"
            self.calcAcceleration(skateX, skateY)

            #if self.speed < 0.1:
            test = Unit(
                9913, 0.0, 0.0, self.me.x +
                6.0 * self.me.radius * cos(self.me.angle + self.move_turn),
                self.me.y +
                6.0 * self.me.radius * sin(self.me.angle + self.move_turn),
                0.0, 0.0, 0.0, 0.0)

            dangerUnits = [
                unit for unit in self.opponentUnits
                if unit.get_angle_to_unit(self.me) < pi / 3.0
            ]
            if dangerUnits:
                dangerUnits.sort(key=lambda x: dist2segment(self.me, test, x))
                dist = dist2segment(self.me, test, dangerUnits[0])

                if dist < 10.0 and self.me.get_angle_to_unit(
                        dangerUnits[0]) < 0.0:
                    self.move_turn = self.game.hockeyist_turn_angle_factor
                    #print "me+puck: angle +"
                elif dist < 10.0:
                    self.move_turn = -self.game.hockeyist_turn_angle_factor
                    #print "me+puck: angle -"

            return True

        elif self.tryStrikeOpponent():
            #print "trySkate: tryStrikeOpponent"
            return True

        elif zeroSpeed:
            # i don't have a puck
            # i don't have a puck

            angle = self.me.get_angle_to(skateX, skateY)
            dist = self.me.get_distance_to(skateX, skateY)

            #if dist < 10.0*self.me.radius and abs(angle) > pi/2:
            if abs(angle) > pi / 2.0 and dist < self.game.world_width / 2.0:
                # going back
                if angle > 0.0:
                    self.move_turn = angle - pi
                else:
                    self.move_turn = angle + pi

                if self.speed >= 0.0:
                    self.move_speed_up = -1.0
                elif dist / self.speed > self.speed / self.game.hockeyist_speed_up_factor:
                    self.move_speed_up = self.speed / self.game.hockeyist_speed_up_factor
                else:
                    self.move_speed_up = -1.0

            else:
                # going front

                self.move_turn = angle

                if self.speed <= 0.0:
                    self.move_speed_up = 1.0
                elif dist / self.speed < self.speed / self.game.hockeyist_speed_down_factor:
                    self.move_speed_up = -self.speed / self.game.hockeyist_speed_down_factor
                else:
                    self.move_speed_up = 1.0

            #print "zeroSpeed: " + str(self.move_turn) + " " + str(self.move_speed_up)
            return True

        else:
            #print "trySkate: calcAcceleration2"
            self.calcAcceleration(skateX, skateY)

            if self.speed < 0.1:
                test = Unit(
                    9914, 0.0, 0.0, self.me.x +
                    2.0 * self.me.radius * cos(self.me.angle + self.move_turn),
                    self.me.y +
                    2.0 * self.me.radius * sin(self.me.angle + self.move_turn),
                    0.0, 0.0, 0.0, 0.0)

                dist = min([
                    unit.get_distance_to_unit(test)
                    for unit in self.opponentUnits
                ])
                if test.x < self.game.rink_left or test.x > self.game.rink_right or test.y < self.game.rink_top or test.y > self.game.rink_bottom:
                    dist = 0.0

                if dist < 2.0 and self.me.get_angle_to_unit(
                        self.attackCircle) > 0.0:
                    self.move_turn += self.game.hockeyist_turn_angle_factor
                    #print "me-puck: angle +"
                elif dist < 2.0:
                    self.move_turn -= self.game.hockeyist_turn_angle_factor
                    #print "me-puck: angle -"

            return True
Ejemplo n.º 27
0
def initial_compact(s):
    ## Compactifies the initial spawn into one line
    ## At the end of process will set the "compacted" flag
    ## Returns deque with actions. s - MyStrategy
    result = deque()
    vs = s.worldstate.vehicles
    pv = vs.by_player[vs.me]
    # hardcoded, no way to obtain dynamicaly
    spawnarea = Area(18, 220, 18, 220)
    squadarea = get_square(vs.resolve(vs.by_type[VehicleType.IFV] & pv))
    spawnarea_width = (spawnarea.right - spawnarea.left)
    colwidth = squadarea.right - squadarea.left
    centralleft = spawnarea.left + (spawnarea_width - colwidth) / 2
    centralright = centralleft + colwidth
    linewidth = squadarea.bottom - squadarea.top
    lines = [
        Area(spawnarea.left, spawnarea.right, spawnarea.top,
             spawnarea.top + linewidth),
        Area(spawnarea.left, spawnarea.right, centralleft, centralright),
        Area(spawnarea.left, spawnarea.right, spawnarea.bottom - linewidth,
             spawnarea.bottom),
    ]
    columns = [
        Area(spawnarea.left, spawnarea.left + colwidth, spawnarea.top,
             spawnarea.bottom),
        Area(centralleft, centralright, spawnarea.top, spawnarea.bottom),
        Area(spawnarea.right - colwidth, spawnarea.right, spawnarea.top,
             spawnarea.bottom),
    ]
    sets = [
        reduce(lambda x, y: y | x, list(map(lambda x: vs.by_type[x], i)))
        for i in types
    ]
    namefull = "secondturn"

    def adjust(clas):
        ## Perform a vertical move
        secondturn = deque()
        name = namefull + ":" + str(clas)
        counted = 0
        for i in [0, 2]:  # lines except central
            line = lines[i]
            target = Unit(None, 0, lines[1].top - line.top)
            for tt in types[clas]:
                squadtomove = vs.in_area(line) & vs.by_type[tt]
                if len(squadtomove) > 0:
                    secondturn += do_and_check(
                        [select_vehicles(s.full_area, vtype=tt),
                         move(target)], name, squadtomove)
                    counted += 1
        return (deque([at_flag(name, counted, deque([fill_flag(namefull)]))]) +
                secondturn)

    for t in [GROUNDERS, FLYERS]:
        empties = set(range(3))
        registredflags = 0
        unitsfromset = [None] * len(columns)
        squadsfromset = [None] * len(columns)
        for i, col in enumerate(columns):
            colunits = vs.in_area(col)
            unitsfromset[i] = colunits & sets[t]
            squadsfromset[i] = len(unitsfromset[i]) // 100
            if squadsfromset[i] > 0:
                empties.discard(i)
        #print("Type " + str(t) + " has " + str(squadsfromset) + " squads by columns")
        #print(empties)
        for i, col in enumerate(columns):
            if squadsfromset[i] > 0:
                name = "firstturn:" + str(t)
                for tomovetype in movables:
                    if squadsfromset[i] <= 1:
                        break
                    movecandidateset = (unitsfromset[i]
                                        & vs.by_type[tomovetype])
                    if len(movecandidateset) == 0:
                        continue
                    if t == GROUNDERS and i != 1:
                        sample = vs[movecandidateset.pop()]
                        obstacle = set()
                        #print("Checking for obstacles...")
                        for lno, line in enumerate(lines):
                            if line.is_inside(sample):
                                #print("... at line " + str(lno))
                                obstacle = (vs.in_area(line)
                                            & vs.in_area(columns[1]) & sets[t])
                                break
                        if len(obstacle) > 0:
                            #print("Obstacle detected")
                            obstacletype = vs[obstacle.pop()].type
                            if obstacletype == VehicleType.TANK:
                                #print("It is tank, lets find something else to move")
                                continue
                            else:
                                tcol = empties.pop()
                                empties.add(1)
                                target = Unit(
                                    None, columns[tcol].left - columns[1].left,
                                    0)
                                #print("Move obstacle from 1 to " + str(tcol))
                                result += do_and_check([
                                    select_vehicles(s.full_area,
                                                    vtype=obstacletype),
                                    move(target)
                                ], name, unitsfromset[i])
                                registredflags += 1
                    tcol = empties.pop()
                    target = Unit(None, columns[tcol].left - columns[i].left,
                                  0)
                    #print("Move from " + str(i) + " to " + str(tcol))
                    result += do_and_check([
                        select_vehicles(s.full_area, vtype=tomovetype),
                        move(target)
                    ], name, unitsfromset[i])
                    registredflags += 1
                    squadsfromset[i] -= 1
        result = deque([
            at_flag("firstturn:" + str(t), registredflags, adjust(t))
        ]) + result
    return deque([at_flag(namefull, 2, deque([fill_flag("compacted")]))
                  ]) + result
Ejemplo n.º 28
0
 def do_move(s: MyStrategy,
             w: World,
             g: Game,
             m: Move,
             max_speed=max_speed):
     vs = s.worldstate.vehicles
     aviaspeedfactor = 1
     myg = vs.by_group[gr]
     my = list(vs.resolve(myg))
     marea = get_square(my)
     mycenter = get_center(my)
     aviasupport = vs.by_group[gr + 1]
     if len(aviasupport) > 0:
         aviacenter = get_center(list(vs.resolve(aviasupport)))
     enemies = list(vs.resolve(vs.by_player[vs.opponent]))
     if len(enemies) == 0:
         return  # some patroling action might be inserted later
     clusters = clusterize(enemies, thresh=20)
     aviaingroup = len(myg & aviasupport)
     #allmine = len(myg | aviasupport)
     groundmine = len(my)
     least = get_center(enemies)
     value = 500
     mindistance = 2000
     for c in clusters:
         #print("Cluster:" + str(len(c)))
         cluster = list(map(lambda x: enemies[x], c))
         clustercenter = get_center(cluster)
         distance = mycenter.get_distance_to_unit(clustercenter)
         #new_value = map(lambda i: 1-int(i.type==0)-int(i.type==1)/2, cluster)
         #new_value = reduce(lambda x, y: x+y, new_value)
         new_value = len(cluster)
         criticaldistance = (
             new_value + groundmine) / 2  # should be obtained empirically
         #print(str(value) + " == " + str(new_value))
         if distance < criticaldistance:
             # combat mode! fight or flee!
             cluset = set(map(lambda x: x.id, cluster))
             fulladvantage = calculate(s.effectiveness, vs,
                                       (myg | aviasupport) - vs.damaged,
                                       cluset)
             #if len((myg | aviasupport)-vs.damaged) / len(myg | aviasupport) > 0.7:
             print("Advantage: " + str(fulladvantage))
             print("Cluster length: " + str(len(cluster)))
             nuke_cd = w.get_my_player(
             ).remaining_nuclear_strike_cooldown_ticks
             if (nuke_cd == 0 and len(cluster) > 20):
                 print("NUKE IT!")
                 navigator = -1
                 dst = 2000
                 for i in aviasupport:
                     ndst = vs[i].get_distance_to_unit(clustercenter)
                     if ndst < dst:
                         dst = ndst
                         navigator = i
                 if navigator > 0:
                     narea = get_square([vs[navigator]])
                     aviaspeedfactor = 10
                     if dst <= 2 * g.fighter_vision_range / 3:
                         s.flags["nuking"] = w.tick_index + 60
                         s.current_action.append(
                             nuke_it(clustercenter, navigator))
                     else:
                         s.flags["nuking"] = 20000
                         target = Unit(None, clustercenter.x - aviacenter.x,
                                       clustercenter.y - aviacenter.y)
                         if target.x == 0:
                             target = Unit(
                                 None, target.x,
                                 target.y - g.fighter_vision_range)
                         elif target.y == 0:
                             target = Unit(
                                 None, target.x - g.fighter_vision_range,
                                 target.y)
                         else:
                             slope = target.y / target.x
                             dx = sqrt((g.fighter_vision_range**2) /
                                       (slope**2 + 1))
                             dy = dx * slope
                             target = Unit(None, target.x - dx,
                                           target.y - dy)
                         s.current_action.append(
                             select_vehicles(narea,
                                             vtype=VehicleType.FIGHTER))
                         s.current_action.append(move(target))
                     # slowly go to the enemy
                 else:
                     print("Navigator not found")
                 # NUKE IS COMMING!
             elif "nuking" in s.flags and s.flags["nuking"] < w.tick_index:
                 s.flags.pop("nuking")
             #fight!
             least = Unit(None,
                          mycenter.x + (clustercenter.x - mycenter.x) / 2,
                          mycenter.y + (clustercenter.y - mycenter.y) / 2)
             mindistance = distance
             value = new_value
             max_speed = max_speed * 0.8
             if aviaspeedfactor == 1:
                 aviaadvantage = calculate(s.effectiveness, vs,
                                           aviasupport - vs.damaged, cluset)
                 #print("Aviaadvantage: " + str(aviaadvantage))
                 if aviaadvantage > 0:
                     aviaspeedfactor = 10
                 elif aviaingroup > 0 and aviaadvantage < -10:
                     aviaspeedfactor = 0.5
         if value * valdst + mindistance > new_value * valdst + distance:
             #print(str(value) + " > " + str(new_value))
             least = clustercenter
             value = new_value
             mindistance = distance
     dx = (least.x - mycenter.x)
     dy = (least.y - mycenter.y)
     destination = Unit(None, dx, dy)
     if aviaspeedfactor != 1 or "nuking" in s.flags:
         aviadestination = Unit(None, least.x - aviacenter.x,
                                least.y - aviacenter.y)
         s.current_action.appendleft(
             move(aviadestination, max_speed=aviaspeedfactor * max_speed))
         s.current_action.appendleft(group(gr, action=ActionType.DISMISS))
         s.current_action.appendleft(select_vehicles(marea, group=gr + 1))
     elif aviaingroup == 0 and not "nuking" in s.flags:
         ddx = copysign(100 * max_speed, dx)
         ddy = copysign(100 * max_speed, dy)
         overmain = Unit(None, mycenter.x - aviacenter.x + ddx,
                         mycenter.y - aviacenter.y + ddy)
         s.current_action.appendleft(move(overmain,
                                          max_speed=2 * max_speed))
         s.current_action.appendleft(group(gr, action=ActionType.ASSIGN))
         s.current_action.appendleft(select_vehicles(marea, group=gr + 1))
     s.current_action.appendleft(move(destination, max_speed=max_speed))
Ejemplo n.º 29
0
    def __init__(self, me, world, game):
        #print "================ " + str(world.tick)

        self.me = me
        self.world = world
        self.game = game

        self.move_turn = None
        self.move_speed_up = None
        self.move_action = None
        self.move_pass_angle = None
        self.move_pass_power = None

        self.angle = self.me.angle

        speed = sqrt(self.me.speed_x * self.me.speed_x +
                     self.me.speed_y * self.me.speed_y)
        if self.me.speed_y > 0.0 and self.angle > 0.0:
            self.speed = speed
        elif self.me.speed_y > 0.0 and self.angle < 0.0:
            self.speed = -speed
        elif self.me.speed_y < 0.0 and self.angle > 0.0:
            self.speed = -speed
        elif self.me.speed_y < 0.0 and self.angle < 0.0:
            self.speed = speed
        elif self.me.speed_x > 0.0 and -pi / 2.0 < self.angle < pi / 2.0:
            self.speed = speed
        else:
            self.speed = -speed

        self.player = self.world.get_my_player()
        self.opponentPlayer = self.world.get_opponent_player()

        self.myUnits = [
            hockeyist for hockeyist in self.world.hockeyists
            if hockeyist.teammate and hockeyist.id != self.me.id
            and hockeyist.type != HockeyistType.GOALIE
            and hockeyist.state != HockeyistState.RESTING
        ]
        self.myUnits.sort(key=lambda x: self.me.get_distance_to_unit(x))
        self.team_count = len(self.myUnits) + 1

        goalies = [
            hockeyist for hockeyist in self.world.hockeyists
            if hockeyist.teammate and hockeyist.type == HockeyistType.GOALIE
        ]
        if goalies:
            self.goalie = goalies[0]
        else:
            self.goalie = None

        forwards = [
            hockeyist for hockeyist in self.world.hockeyists
            if hockeyist.teammate and hockeyist.type == HockeyistType.FORWARD
        ]
        if forwards:
            self.forward = forwards[0]
        else:
            self.forward = None

        versatiles = [
            hockeyist for hockeyist in self.world.hockeyists
            if hockeyist.teammate and hockeyist.type == HockeyistType.VERSATILE
        ]
        if versatiles:
            self.versatile = versatiles[0]
        else:
            self.versatile = None

        defenders = [
            hockeyist for hockeyist in self.world.hockeyists if
            hockeyist.teammate and hockeyist.type == HockeyistType.DEFENCEMAN
        ]
        if defenders:
            self.defender = defenders[0]
        else:
            self.defender = None

        self.opponentUnits = [
            hockeyist for hockeyist in self.world.hockeyists
            if not hockeyist.teammate and hockeyist.type !=
            HockeyistType.GOALIE and hockeyist.state != HockeyistState.RESTING
        ]
        self.opponentUnits.sort(key=lambda x: self.me.get_distance_to_unit(x))

        self.rink_center_x = 0.5 * (self.game.rink_left + self.game.rink_right)
        self.rink_center_y = 0.5 * (self.game.rink_top + self.game.rink_bottom)

        if self.player.net_front < self.rink_center_x:
            self.position = "left"
            forward_x = self.opponentPlayer.net_front - 0.4 * self.game.world_width
            defence_x = self.player.net_front + 3.1 * self.me.radius
        #  defence2_x = self.player.net_front + 4.1*self.me.radius
        else:
            self.position = "right"
            forward_x = self.opponentPlayer.net_front + 0.4 * self.game.world_width
            defence_x = self.player.net_front - 3.1 * self.me.radius
        #   defence2_x = self.player.net_front - 4.1*self.me.radius

        if self.me.y < self.rink_center_y:
            forward_y = self.game.rink_top + 0.2 * self.game.world_height
        else:
            forward_y = self.game.rink_bottom - 0.2 * self.game.world_height

        self.forwardPlace = Unit(9906, 0.0, 0.0, forward_x, forward_y, 0.0,
                                 0.0, 0.0, 0.0)
        self.defendCircle = Unit(9907, 0.0, 1.0 * self.game.stick_length,
                                 defence_x, self.rink_center_y, 0.0, 0.0, 0.0,
                                 0.0)
        #self.defendCircle2 = Unit(9901, 0.0, 1.0*self.game.stick_length,
        #                         defence2_x, self.rink_center_y+self.me.radius,
        #                         0.0, 0.0, 0.0, 0.0)

        self.attackAngle = pi / 2.0 - pi / 6.0

        if self.goalie:
            self.attackCircle = Unit(9908, 1.0, 0.4 * self.game.world_height,
                                     self.opponentPlayer.net_front,
                                     self.rink_center_y, 0.0, 0.0, 0.0, 0.0)
            self.attackPassDistance = 3.0 * self.me.radius
        else:
            self.attackCircle = Unit(9909, 1.0, self.game.world_width,
                                     self.opponentPlayer.net_front,
                                     self.rink_center_y, 0.0, 0.0, 0.0, 0.0)
            self.attackPassDistance = self.game.world_width
Ejemplo n.º 30
0
    def calcAcceleration(self, skateX, skateY):

        Tmin = 10000
        a_min = 1.0

        if self.me.get_distance_to(skateX,
                                   skateY) > self.game.world_width / 5.0:
            self.move_turn = self.me.get_angle_to(skateX, skateY)
            self.move_speed_up = 1.0
            return True

        if abs(self.me.get_angle_to(skateX, skateY)) <= pi / 2.0:
            direction = 'forward'
        else:
            direction = 'back'

        for i in range(10):
            (x, y) = (self.me.x, self.me.y)
            v = self.speed
            alpha = self.angle
            a0 = 1.0 - i / 10.0
            T = Tmin

            if direction == 'forward' and a0 < 0.0:
                break
            # if direction == 'back' and self.me.get_distance_to(skateX, skateY) > 100.0 and a < 0.0:
            #     break

            for j in range(100):
                aj = a0 - j * 0.001
                unit = Unit(999 + i * 100 + j, 0.0, 0.0, x, y, 0.0, 0.0, alpha,
                            0.0)
                if (x < self.game.rink_left or x > self.game.rink_right
                        or y < self.game.rink_top
                        or y > self.game.rink_bottom):
                    break

                if unit.get_distance_to(skateX, skateY) < 1.0:
                    T = j
                    break

                if aj > 0.0:
                    v += aj * self.game.hockeyist_speed_up_factor
                else:
                    v += aj * self.game.hockeyist_speed_down_factor

                v = 0.95 * v  # friction

                dalpha = unit.get_angle_to(skateX, skateY)
                if v < 0.0 and dalpha < 0.0:
                    dalpha = dalpha + pi
                elif v < 0.0 and dalpha > 0.0:
                    dalpha = dalpha - pi

                dalpha = copysign(
                    min(abs(dalpha), self.game.hockeyist_turn_angle_factor),
                    dalpha)

                alpha = normAngle(alpha + dalpha)
                (x, y) = (x + v * cos(alpha), y + v * sin(alpha))

            if T < Tmin:
                Tmin = T
                a_min = a0

        alpha = self.me.get_angle_to(skateX, skateY)
        if T == 10000:
            #print self.me.x, self.me.y, skateX, skateY, self.angle, direction, self.speed
            self.move_turn = alpha
            self.move_speed_up = 1.0
        elif direction == 'back' and a_min < 0.0 and alpha < 0.0:
            self.move_turn = alpha + pi
            self.move_speed_up = a_min
        elif direction == 'back' and a_min < 0.0 and alpha > 0.0:
            self.move_turn = alpha - pi
            self.move_speed_up = a_min
        else:
            self.move_turn = alpha
            self.move_speed_up = a_min

        return True