Exemple #1
0
 def do_group(s: MyStrategy, w: World, g: Game, m: Move):
     m.action = action
     m.group = gnum
     if action == ActionType.ASSIGN:
         s.free_groups.discard(gnum)
     elif action == ActionType.DISBAND:
         s.free_groups.add(gnum)
Exemple #2
0
def test_speed():
    try:
        process_client = RemoteProcessClient('wgforge-srv.wargaming.net', 443)
        player = process_client.login("Test12345")
        map_graph = process_client.read_map()
        map_graph.pos = dict(
            [(cord['idx'], (cord['x'] / 200, cord['y'] / 200))
             for cord in process_client.read_position()["coordinate"]])
        objects = process_client.read_objects()
        process_client.update_objects(objects, map_graph, player)

        process_client.move(Move(1, 1, 1))
        process_client.turn()
        process_client.turn()
        process_client.update_objects(objects, map_graph, player)
        train = objects.trains[1]
        print(" pos - ", train.position, " speed - ", train.speed)

        process_client.move(Move(1, 0, 1))
        process_client.move(Move(1, -1, 1))
        process_client.turn()
        process_client.update_objects(objects, map_graph, player)
        print(" pos - ", train.position, " speed - ", train.speed)
    finally:
        process_client.logout()
        process_client.close()
Exemple #3
0
    def move(self, me: Car, world: World, game: Game, move: Move):
        if world.tick < game.initial_freeze_duration_ticks:
            if world.tick == 0:
                self.worldWidth = world.width
                self.build_path(world)
                return
            if world.tick == 1:
                aFrom = (int(me.x//game.track_tile_size), int(me.y//game.track_tile_size))
                aTo = (me.next_waypoint_x, me.next_waypoint_y)
                print(aFrom, aTo)
                dijkstra(self.path, self.path.get_vertex(aFrom), self.path.get_vertex(aTo))

                target = self.path.get_vertex(aTo)
                path = [target.get_id()]
                shortest(target, path)
                print('The shortest path : %s' %(path[::-1]))

        nextWaypointX = (me.next_waypoint_x + 0.5) * game.track_tile_size
        nextWaypointY = (me.next_waypoint_y + 0.5) * game.track_tile_size

        angleToWaypoint = me.get_angle_to(nextWaypointX, nextWaypointY)
        speedModule = hypot(me.speed_x, me.speed_y)

        move.wheel_turn = angleToWaypoint  / pi
        move.engine_power = 0.8

        if (speedModule * speedModule * abs(angleToWaypoint) > 2.5 * 2.5 * pi):
            move.setBrake = True
            move.engine_power = -0.5
    def move(self, me: Car, world: World, game: Game, move: Move):
        move.engine_power = 1.0
        move.throw_projectile = True
        move.spill_oil = True

        if world.tick > game.initial_freeze_duration_ticks:
            move.use_nitro = True
Exemple #5
0
 def testGameStatus(self):
     self.assertEqual(self.controller.gameStatus(), 0)
     self.repository.addMove(Move("X", 1, 1))
     self.repository.addMove(Move("X", 2, 2))
     self.repository.addMove(Move("X", 3, 3))
     self.repository.addMove(Move("X", 4, 4))
     self.assertEqual(self.controller.gameStatus(), 1)
Exemple #6
0
    def move(self, me: Wizard, world: World, game: Game, move: Move):
        # First, initialize some common things.
        attack_faction = self.get_attack_faction(me.faction)
        skills = set(me.skills)

        # Learn some skill.
        move.skill_to_learn = self.skill_to_learn(skills)
        # Apply some skill.
        move.status_target_id = me.id

        # Bonus pick up.
        bonus_tick_index = world.tick_index % 2500
        if self.pick_up_bonus is None and (me.x > 1600.0 or me.y < 2400.0) and bonus_tick_index >= 2000:
            self.pick_up_bonus = min(BONUSES, key=(lambda bonus: me.get_distance_to(*bonus)))
        if me.x < 400.0 and me.y > 3600.0:
            self.pick_up_bonus = None
        if self.pick_up_bonus is not None:
            x, y = self.pick_up_bonus
            if not MyStrategy.attack_nearest_enemy(me, world, game, move, skills, attack_faction):
                move.turn = me.get_angle_to(x, y)
            if bonus_tick_index >= 2000 and me.get_distance_to(x, y) < me.radius + 2.0 * game.bonus_radius:
                # Bonus hasn't appeared yet. Stay nearby.
                return
            if 0 < bonus_tick_index < 2000 and (
                # Bonus has just been picked up.
                me.get_distance_to(x, y) < me.radius or
                # No bonus there.
                (me.get_distance_to(x, y) < me.vision_range and not world.bonuses)
            ):
                self.pick_up_bonus = None
            else:
                self.move_by_tiles_to(me, world, game, move, x, y)
            return

        # Check if I'm healthy.
        if self.is_in_danger(me, world, game, me.x, me.y, attack_faction):
            # Retreat to the nearest safe tile.
            x, y = min((
                (x, y)
                for x, y in KEY_TILES
                if not self.is_in_danger(me, world, game, x, y, attack_faction)
            ), key=(lambda point: me.get_distance_to(*point)))
            self.move_by_tiles_to(me, world, game, move, x, y)
            MyStrategy.attack_nearest_enemy(me, world, game, move, skills, attack_faction)
            return

        # Else try to attack the best target.
        if MyStrategy.attack_best_target(me, world, game, move, skills, attack_faction):
            return

        # Quick and dirty fix to avoid being stuck near the base.
        if me.x < 400.0 and me.y > 3600.0:
            move.turn = me.get_angle_to(*self.move_by_tiles_to(me, world, game, move, 200.0, 200.0))
            return

        # Nothing to do. Just go to enemy base.
        x, y = self.move_by_tiles_to(me, world, game, move, ATTACK_BASE_X, ATTACK_BASE_Y)
        move.turn = me.get_angle_to(x, y)
def apply_go_to_move(point: Point2D, me: Wizard, game: Game, move: Move):
    """
    Простейший способ перемещения волшебника.
    """
    angle = me.get_angle_to(point.x, point.y)
    move.turn = angle

    if math.fabs(angle) < game.staff_sector / 4.0:
        move.speed = game.wizard_forward_speed
Exemple #8
0
    def move(self, me: Hockeyist, world: World, game: Game, move: Move):
        factory = self.create_factory(me, world, game, move)
        strategy = self.create_strategy(factory, me, world, game, move)

        move.action = strategy.action
        move.speed_up = strategy.speed_up
        move.turn = strategy.turn

        factory.info[type(strategy)] = strategy.info
Exemple #9
0
    def move(self, me: Hockeyist, world: World, game: Game, move: Move):
        factory = self.create_factory(me, world, game, move)
        strategy = self.create_strategy(factory, me, world, game, move)

        move.action = strategy.action
        move.speed_up = strategy.speed_up
        move.turn = strategy.turn

        factory.info[type(strategy)] = strategy.info
Exemple #10
0
 def attack(me: Wizard, game: Game, move: Move, skills: Set, unit: LivingUnit, allow_fireball: bool):
     action_type, min_cast_distance = MyStrategy.get_action(me, game, skills, unit, allow_fireball)
     if action_type == ActionType.NONE:
         return False
     # We can cast something.
     is_oriented, cast_angle = MyStrategy.is_oriented_to_unit(me, game, unit)
     if is_oriented:
         # Attack!
         move.cast_angle = cast_angle
         move.action = action_type
         move.min_cast_distance = min_cast_distance
         return True
     # Turn around to the enemy.
     move.turn = me.get_angle_to_unit(unit)
     return True
Exemple #11
0
    def move(self, me: Wizard, world: World, game: Game, move: Move):
        # Every tick, update state first
        state_machine.update_state(me, world, game)

        # Take action for this state
        state_machine.run(me, world, game)

        # Current state
        state = state_machine.get_state()

        # Move
        move.speed = state.forward_speed
        move.strafe_speed = state.strafe_speed
        move.turn = state.turn_angle
        move.action = state.action
 def testAddMove(self):
     move = Move("X", 0, 0)
     self.moveRepository.addMove(move)
     self.assertEqual(self.moveRepository.getMove(0, 0), move)
     self.assertEqual(self.moveRepository.getMove(1, 1), None)
     with self.assertRaises(DuplicateMoveError):
         self.moveRepository.addMove(move)
Exemple #13
0
    def run(self, pid=None):
        try:
            self.remote_process_client.write_token_message(self.token)
            self.remote_process_client.write_protocol_version_message()
            team_size = self.remote_process_client.read_team_size_message()
            game = self.remote_process_client.read_game_context_message()

            strategies = []

            for _ in range(team_size):
                strategies.append(MyStrategy())

            while True:
                player_context = self.remote_process_client.read_player_context_message()
                if player_context is None:
                    break

                player_wizards = player_context.wizards
                if player_wizards is None or player_wizards.__len__() != team_size:
                    break

                moves = []

                for wizard_index in range(team_size):
                    player_wizard = player_wizards[wizard_index]

                    move = Move()
                    moves.append(move)
                    strategies[wizard_index].move(player_wizard, player_context.world, game, move)

                self.remote_process_client.write_moves_message(moves)
        finally:
            self.remote_process_client.close()
            if pid:
                os.kill(pid, signal.SIGTERM)
Exemple #14
0
    def run(self):
        try:
            self.remote_process_client.write_token(self.token)
            team_size = self.remote_process_client.read_team_size()

            strategies = []
            tank_types = []

            for strategy_index in range(team_size):
                strategy = MyStrategy()
                strategies.append(strategy)
                tank_types.append(strategy.select_tank(strategy_index, team_size))

            self.remote_process_client.write_selected_tanks(tank_types)

            while True:
                player_context = self.remote_process_client.read_player_context()
                if player_context is None:
                    break

                player_tanks = player_context.tanks
                if player_tanks.__len__() != team_size:
                    break

                moves = []

                for strategy_index in range(team_size):
                    move = Move()
                    moves.append(move)
                    strategies[strategy_index].move(player_tanks[strategy_index], player_context.world, move)

                self.remote_process_client.write_moves(moves)
        finally:
            self.remote_process_client.close()
Exemple #15
0
    def run(self):
        try:
            self.remote_process_client.write_token_message(self.token)
            self.remote_process_client.write_protocol_version_message()
            self.remote_process_client.read_team_size_message()
            game = self.remote_process_client.read_game_context_message()

            strategy = MyStrategy()

            while True:
                player_context = self.remote_process_client.read_player_context_message(
                )
                if player_context is None:
                    break

                player = player_context.player
                if player is None:
                    break

                move = Move()
                strategy.move(player, player_context.world, game, move)

                self.remote_process_client.write_move_message(move)
        finally:
            self.remote_process_client.close()
Exemple #16
0
    def get_moves(self):
        self.update_targets()

        moves = []
        trains_targets = dict()
        for train_id in self.trains_points:
            train = self.objects.trains[train_id]
            if train.point:
                trains_targets[train.idx] = (train.point, self.trains_points[train.idx][0])
        print(trains_targets)

        self.solver = TrafficController()
        paths = self.solver.find_paths(self.map, self.objects.trains, trains_targets)

        for train_id in paths:
            path = paths[train_id]
            if path:
                next_step = path[1]
                print("move {}, {}".format(self.objects.trains[train_id].point, next_step))
                move_obj = self._move_to_point(self.objects.trains[train_id], next_step)
                moves.append(move_obj)
            else:
                train = self.objects.trains[train_id]
                moves.append(Move(train.line_idx, 0, train.idx))

        # moves = self.step()
        # print(move_obj)
        if moves:
            return moves
Exemple #17
0
    def run(self):
        try:
            self.remote_process_client.write_token_message(self.token)
            team_size = self.remote_process_client.read_team_size_message()
            self.remote_process_client.write_protocol_version_message()
            game = self.remote_process_client.read_game_context_message()

            strategies = []

            for _ in xrange(team_size):
                strategies.append(MyStrategy())

            while True:
                player_context = self.remote_process_client.read_player_context_message(
                )
                if player_context is None:
                    break

                player_cars = player_context.cars
                if player_cars is None or player_cars.__len__() != team_size:
                    break

                moves = []

                for car_index in xrange(team_size):
                    player_car = player_cars[car_index]

                    move = Move()
                    moves.append(move)
                    strategies[player_car.teammate_index].move(
                        player_car, player_context.world, game, move)

                self.remote_process_client.write_moves_message(moves)
        finally:
            self.remote_process_client.close()
Exemple #18
0
 def test_right_move_from_line(self):
     self.train.position = 5
     self.train.line_idx = 1
     self.process_client.turn_trains()
     move = Move(1, 1, self.train.idx)
     self.process_client.move(move)
     assert self.train.speed == 1
     assert self.train.line_idx == 1
Exemple #19
0
 def test_wrong_move_from_node(self):
     self.train.position = 10
     self.train.line_idx = 1
     self.process_client.turn_trains()
     move = Move(3, 1, self.train.idx)
     self.process_client.move(move)
     assert self.train.speed == 0
     assert self.train.line_idx == 1
 def get_move(self, train: Train, map_graph: Map):
     if train.speed == 0:
         train.arrival()
         if train.position is None:  # Если поезд ещё не начинал путь
             train.departure(self.home,
                             map_graph.get_first_neighbor(self.home)
                             )  # Отправляем его к первому соседнему городу
             line = map_graph.get_line(train.departure_point,
                                       train.arrival_point)
             return Move(line, 1, train.idx)
         if train.current_point != self.home:  # Если поезд прибыл не домой
             train.departure(train.current_point,
                             self.home)  # Отправляем поезд домой
             line = map_graph.get_line(train.departure_point,
                                       train.arrival_point)
             return Move(line, 1, train.idx)
         self.in_progress = False
def test_defult_example():
    remote_process_client = RemoteProcessClient('wgforge-srv.wargaming.net',
                                                443)
    assert remote_process_client.login("Test12345")[0] == 0
    assert remote_process_client.move(Move(1, 1, 0))[0] == 0
    assert remote_process_client.map(1)[0] == 0
    assert remote_process_client.turn()[0] == 0
    remote_process_client.logout()
    remote_process_client.close()
Exemple #22
0
def test_defult():

    strategy = Strategy(start_data)
    next_move = strategy.move(world, game)

    print(next_move)
    test_move = Move(12, 1, 0)
    assert next_move.line_idx == test_move.line_idx
    assert next_move.speed == test_move.speed
    assert next_move.train_idx == test_move.train_idx
Exemple #23
0
def test_run_example():
    runner = Runner()
    runner.remote_process_client.login("Test_Conway")
    runner.remote_process_client.map(0)
    runner.remote_process_client.turn()                 # reset timer on server
    runner.remote_process_client.move(Move(1, 1, 0))
    for i in range(11):
        response = runner.remote_process_client.map(1)
        print("Position - ", response[1]["train"][0]["position"])
        runner.remote_process_client.turn()
    assert response[1]["train"][0]["position"] == 10
    runner.remote_process_client.move(Move(1, 1, 0))
    for i in range(11):
        response = runner.remote_process_client.map(1)
        print("Position - ", response[1]["train"][0]["position"])
        runner.remote_process_client.turn()
    assert response[1]["train"][0]["position"] == 10
    runner.remote_process_client.logout()
    runner.remote_process_client.close()
Exemple #24
0
    def run(self):
        try:
            self.remote_process_client.write_token_message(self.token)
            self.remote_process_client.write_protocol_version_message()
            team_size = self.remote_process_client.read_team_size_message()
            game = self.remote_process_client.read_game_context_message()

            self.strategies = []
            self.start_input()
            world_time = 0

            while True:
                while self.freeze:
                    time.sleep(0.5)

                if self.reload:
                    print(f'actually reloading at {world_time}')
                    for module in [
                            x for x in sys.modules if x.startswith('aicup2016')
                    ]:
                        del sys.modules[module]
                    from aicup2016.strategy import Strategy

                    self.strategies = []
                    for _ in range(team_size):
                        self.strategies.append(
                            Strategy(debug_client=self.debug_client,
                                     input_event=self.input_event))
                    self.reload = False

                player_context = self.remote_process_client.read_player_context_message(
                )
                if player_context is None:
                    break
                world_time = player_context.world.tick_index

                player_wizards = player_context.wizards
                if player_wizards is None or player_wizards.__len__(
                ) != team_size:
                    break

                moves = []

                for wizard_index in range(team_size):
                    player_wizard = player_wizards[wizard_index]

                    move = Move()
                    moves.append(move)
                    self.strategies[wizard_index].move(player_wizard,
                                                       player_context.world,
                                                       game, move)

                self.remote_process_client.write_moves_message(moves)
        finally:
            self.remote_process_client.close()
Exemple #25
0
    def step(self):
        moves = []
        trains = dict()
        trains_order = []
        self.update_targets()

        for train in self.objects.get_my_trains(self.player.idx):
            pos = Position(train.point, train.line_idx, train.position)
            trains.update({train.idx: pos})
            trains_order.append(train.idx)
        shuffle(trains_order)

        while len(trains_order):
            train_id = trains_order.pop(0)
            train = self.objects.trains[train_id]
            maybe_next = self.next_step(train_id)
            pos = trains[train_id]

            if not maybe_next:
                print("No Path")
                for t in trains_order:
                    self.unreserve(t)
                    self.paths[t] = []

            if not self.valid(train, pos, maybe_next):
                print("Path Invalid")
                self.paths[train_id] = []
                maybe_next = self.next_step(train_id)

            if not maybe_next:
                maybe_next = pos

            line_speed = self.pos_to_line_speed(pos, maybe_next)
            if line_speed[0] == train.line_idx and line_speed[1] == train.speed:
                continue
            if train.speed == -line_speed[1]:
                moves.append(Move(line_speed[0], 0, train_id))
            moves.append(Move(line_speed[0], line_speed[1], train_id))
        logger.info("reservation on tick - %d \n %s", self.objects.tick,
                    pformat(self.trains_reservations, indent=4))
        pprint(self.trains_roles)
        return moves
Exemple #26
0
 def do_select(s: MyStrategy, w: World, g: Game, m: Move, a=area):
     m.action = action
     #print("Selecting: " + str(a))
     m.left = a.left - fuzz
     m.right = a.right + fuzz
     m.top = a.top
     m.bottom = a.bottom
     m.group = group
     m.vehicle_type = vtype
Exemple #27
0
 def makeMove(self, xCoordinate, yCoordinate):
     """
     Makes a move for the player
     :param xCoordinate: The x coordinate of the move
     :param yCoordinate: The y coordinate of the move
     """
     move = Move(self.sign, xCoordinate, yCoordinate)
     Validator.validateMove(
         move, self.__moveRepository.lastMove.sign
         if self.__moveRepository.lastMove is not None else "")
     self.__moveRepository.addMove(move)
    def read_move(self):
        if not self.read_boolean():
            return None

        move = Move()

        move.engine_power = self.read_double()
        move.brake = self.read_boolean()
        move.wheel_turn = self.read_double()
        move.throw_projectile = self.read_boolean()
        move.use_nitro = self.read_boolean()
        move.spill_oil = self.read_boolean()

        return move
Exemple #29
0
 def select_all(self, move: Move, vehicle_type=None, add_to_selection=False):
     move.action = ActionType.CLEAR_AND_SELECT if not add_to_selection else ActionType.ADD_TO_SELECTION
     move.left = 0.0
     move.top = 0.0
     move.right = self.game.world_width
     move.bottom = self.game.world_height
     if vehicle_type is not None:
         move.vehicle_type = vehicle_type
Exemple #30
0
    def move(self, me: Hockeyist, world: World, game: Game, move: Move):

        # self.me = me
        # self.world = world
        # self.game = game
        # self.me_move = move

        if me.state == HockeyistState.SWINGING:
            move.action = ActionType.STRIKE
            return

        if world.puck.owner_player_id == me.player_id:

            if world.puck.owner_hockeyist_id == me.id:

                opponent = world.get_opponent_player()

                net_x = 0.5 * (opponent.net_back + opponent.net_front)
                net_y = 0.5 * (opponent.net_bottom + opponent.net_top)

                angle_to_net = me.get_angle_to(net_x, net_y)
                move.turn = angle_to_net

                if abs(angle_to_net) < self.STRIKE_ANGLE:
                    move.action = ActionType.STRIKE

            else:

                nearest_opponent = self.get_nearest_opponent(me, world)

                if nearest_opponent is not None:

                    if me.get_distance_to_unit(nearest_opponent) > game.stick_length:
                        move.speed_up = 1
                    else:
                        move.action = ActionType.STRIKE

                    move.turn = me.get_angle_to_unit(nearest_opponent)

        else:
            move.speed_up = 1
            move.turn = me.get_angle_to_unit(world.puck)
            move.action = ActionType.TAKE_PUCK
Exemple #31
0
 def move_to(me: Wizard, world: World, game: Game, move: Move, x: float, y: float):
     x, y = MyStrategy.avoid_collisions(me, world, x, y)
     direction_x, direction_y = x - me.x, y - me.y
     # Normalize the destination vector.
     distance = math.sqrt(direction_x * direction_x + direction_y * direction_y)
     if abs(distance) < 1.0:
         return
     direction_x /= distance
     direction_y /= distance
     # Wizard's turn vector.
     turn_x, turn_y = math.cos(me.angle), math.sin(me.angle)
     # Project the destination vector onto the speed vector.
     speed = direction_x * turn_x + direction_y * turn_y
     # Project the destination vector onto the strafe speed vector.
     strafe_speed = direction_x * (-turn_y) + direction_y * turn_x
     # Finally, set up the movement.
     max_speed = 10.0
     if speed > 0.0:
         move.speed = speed * max_speed
         move.strafe_speed = strafe_speed * max_speed
     else:
         move.speed = speed * max_speed
         move.strafe_speed = strafe_speed * max_speed
Exemple #32
0
    def _move_to_point(self, train, arrival_point):
        if train.point == arrival_point:
            return None
        if train.point is None:
            line = self.map.lines[train.line_idx]
        else:
            line = self.map.Graph.get_edge_data(train.point, arrival_point)['line']
            if line is None:
                return None
        speed = -1 if line.start_point == arrival_point else 1

        if line == train.line_idx and speed == train.speed:
            return None
        return Move(line.idx, speed, train.idx)
Exemple #33
0
    def read_move(self):
        if not self.read_boolean():
            return None

        move = Move()

        move.speed_up = self.read_double()
        move.turn = self.read_double()
        move.action = self.read_enum(ActionType)
        if move.action == ActionType.PASS:
            move.pass_power = self.read_double()
            move.pass_angle = self.read_double()
        elif move.action == ActionType.SUBSTITUTE:
            move.teammate_index = self.read_int()

        return move
Exemple #34
0
    def move(self, me: Player, world: World, game: Game, move: Move):
        if world.tick_index == 0:
            move.action = ActionType.CLEAR_AND_SELECT
            move.right = world.width
            move.bottom = world.height

        if world.tick_index == 1:
            move.action = ActionType.MOVE
            move.x = world.width / 2.0
            move.y = world.height / 2.0
    def read_move(self):
        if not self.read_boolean():
            return None

        move = Move()

        move.engine_power = self.read_double()
        move.brake = self.read_boolean()
        move.wheel_turn = self.read_double()
        move.throw_projectile = self.read_boolean()
        move.use_nitro = self.read_boolean()
        move.spill_oil = self.read_boolean()

        return move
Exemple #36
0
    def moveToNonMedic(self, me: Trooper, world: object, game: Game, move: Move):
        troopers = world.troopers

        for trooper in troopers:
            if trooper.type != TrooperType.FIELD_MEDIC and trooper.teammate:
                targetX = 0
                targetY = 0
                move.action = ActionType.MOVE

                if me.type == TrooperType.FIELD_MEDIC and trooper.hitpoints < trooper.maximal_hitpoints:
                    targetX = trooper.x
                    targetY = trooper.y
                else:
                    targetX = trooper.x + randint(0, 9) % 3
                    targetY = trooper.y + randint(0, 9) % 3

                self.moveToPoint(targetX, targetY, me, world, game, move)
    def read_move(self):
        if not self.read_boolean():
            return None

        move = Move()

        move.speed_up = self.read_double()
        move.turn = self.read_double()
        move.action = self.read_enum(ActionType)
        if move.action == ActionType.PASS:
            move.pass_power = self.read_double()
            move.pass_angle = self.read_double()
        elif move.action == ActionType.SUBSTITUTE:
            move.teammate_index = self.read_int()

        return move
Exemple #38
0
	def makeNextMove(opponentsLastMove=None, iLost=None, iScored=None):
		if opponentsLastMove != None:
			if self.defence in opponentsLastMove.getAttacks():
				self.comment = 'haha, blocked your attack to my' + self.defence
			else:
				self.comment = 'ouch'

		self.attack2 = Kickboxer.createRandomArea()

		if opponentsLastMove != None:
			if Kickboxer.attack1 in opponentsLastMove.getBlocks():
				self.attack1 = Kickboxer.createRandomArea()

		move = Move()
		print(move.getAttacks, move.getBlocks)
		move.addAttack(self.attack1)
		move.addAttack(self.attack2)
		move.addBlock(self.defence)
		move.setComment(self.comment)
		print(move.getAttacks, move.getBlocks)
		return move
Exemple #39
0
	def parseMove(Input):
		sys.stdout.flush()
		if Input == False or Input == None:
			print("Input stream was closed")

		Input = Input.strip()
		rez = Move()

		index = 0

		while index < len(Input):
			Type = Input[index]
			index += 1
			
			#TODO
			if 'a'==Type: 
				rez.addAttack(Protocol.getArea(Input, index)); index += 1 #######?TODO
			
			elif 'b'==Type: 
				rez.addBlock(Protocol.getArea(Input, index)); index += 1 #######?TODO
			
			elif '.'==Type:
				pass

			elif 'c'==Type:
				rez.setComment(Input[index]); index = len(Input) + 1
			
			elif ' '==Type:
				pass
			
			elif r'\t'==Type:
				continue
			
			else:
				print("Unrecognized input:" + Type)
		return rez
Exemple #40
0
 def throwGrenade(self, trooper : Trooper, move : Move):
     move.action = ActionType.THROW_GRENADE
     move.x = trooper.x
     move.y = trooper.y
Exemple #41
0
	def makeNextMove(self, opponentsLastMove=None, myLastScore=0, opponentsLastScore=0):
		move = Move()
		move.addAttack('NOSE')
		move.addBlock('GROIN')
		move.addBlock('NOSE')
		return move
Exemple #42
0
	def makeNextMove(self, opponentsLastMove=None, myLastScore=None, opponentsLastScore=None): #I do not understand move part
		move = Move()
		
		move.addAttack(self.attack1)
		move.addAttack(self.attack2) ##
		move.addBlock(self.defence) ##
		#Commentator().setComment("blocked your move to my $this->defence... hahaha")

		if opponentsLastMove != None:
			if self.defence in opponentsLastMove.getAttacks():
				#pass
				move.setComment("blocked your move to my self->defence... hahaha")
			else:
				self.changeDefence()

		self.myScoreTotal += myLastScore #TODO:  type object 'Boxer' has no attribute 'myScoreTotal'
		self.opponentScoreTotal += opponentsLastScore

		if self.myScoreTotal < self.opponentScoreTotal:
			#move.setComment('okay, meat, me is mad now... going berserk')
			move.addAttack(self.createRandomAttack())
		else:
			move.addBlock(self.defence)

		return move
Exemple #43
0
 def shootTrooper(self, trooper : Trooper, move : Move, game : Game, me : Trooper):
     move.action = ActionType.SHOOT
     move.x = trooper.x
     move.y = trooper.y
Exemple #44
0
 def heal(self, trooper : Trooper, move : Move):
     move.action = ActionType.HEAL
     move.x = trooper.x
     move.y = trooper.y
     print('Солдат полечил')
Exemple #45
0
 def decreaseStance(self, move : Move, game : Game, me : Trooper):
     move.action = ActionType.LOWER_STANCE
     move.direction = Direction.CURRENT_POINT
Exemple #46
0
    def move(self, me: Car, world: World, game: Game, move: Move):

        self.grid = world.tiles_x_y
        self.grid_width = len(world.tiles_x_y)
        self.grid_height = len(world.tiles_x_y[0])

        curr_tile_x = int(
            me.x // game.track_tile_size + (-1 if me.x % game.track_tile_size == 0 else 0))
        curr_tile_y = int(
            me.y // game.track_tile_size + (-1 if me.y % game.track_tile_size == 0 else 0))
        curr_tile_type = world.tiles_x_y[curr_tile_x][curr_tile_y]
        curr_speed_module = hypot(me.speed_x, me.speed_y)

        print('----------', world.tick)
        # if world.tick == 0:
        #     for j in range(self.grid_height):
        #         print(', '.join([str(self.grid[i][j]).rjust(2, '0') for i in range(self.grid_width)]))
        # print(self.pts)
        # print(me.next_waypoint_x, me.next_waypoint_y)
        # print(self.ticks_without_move, self.rear_move_ticks_remain)

        # путь до следующего way point
        # if self.route:
        #     steps = self.route[len(self.tmp_route):]
        # else:
        #     if len(self.tmp_route) > 1 and self.tmp_route[0] == (curr_tile_x, curr_tile_y):
        #         self.route = list(self.tmp_route)
        #         self.tmp_route.clear()

        steps = self.steps_to_point(curr_tile_x, curr_tile_y, me.next_waypoint_x, me.next_waypoint_y)

        # if not self.tmp_route or self.tmp_route[-1] != (curr_tile_x, curr_tile_y):
        #     self.tmp_route.append((curr_tile_x, curr_tile_y))
        # print(steps, len(steps))
        straight_moves = 1
        if steps:
            next_tile_x, next_tile_y = steps[0]

            direction = (next_tile_x - curr_tile_x, next_tile_y - curr_tile_y)
            for i in range(1, len(steps)):
                if direction == (steps[i][0] - steps[i-1][0], steps[i][1] - steps[i-1][1]):
                    straight_moves += 1
                    next_tile_x, next_tile_y = steps[i]
                else:
                    break
        else:
            next_tile_x, next_tile_y = me.next_waypoint_x, me.next_waypoint_y

        next_tile_type = world.tiles_x_y[next_tile_x][next_tile_y]
        # print(straight_moves)

        if self.state == DEFAULT_ST or self.state == ACCELERATION_ST:
            # до начала движения
            if world.tick < game.initial_freeze_duration_ticks:
                return self.move_forward_and_return(move)

            # счётчик простоя перед задним ходом
            if abs(curr_speed_module) < SMALL_SPEED:
                self.ticks_without_move += 1
            else:
                self.ticks_without_move = 0
            if self.ticks_without_move > TICKS_WITHOUT_MOVE.get(self.state):
                self.ticks_without_move = 0
                self.state = REVERSE_ST
                self.rear_move_ticks_remain = MAX_REAR_MOVE_TICKS

            if self.state == ACCELERATION_ST:
                if abs(curr_speed_module) >= SMALL_SPEED:
                    self.state = DEFAULT_ST

            # print(curr_tile_x, curr_tile_y)
            # print(next_tile_x, next_tile_y, next_tile_type)
            # print(me.next_waypoint_x, me.next_waypoint_y, next_tile_type)
            # print(self.grid_width, self.grid_height)
            # print(steps)
            # print(me.speed_x, me.speed_y)
            # print(me.x, me.y)
            # print(cars_is_close)
            # print(curr_speed_module)
            # print(curr_speed_module > BIG_SPEED and straight_moves == 1)

            # # FIXME есть ли машины рядом
            # cars_is_close = False
            # for car in world.cars:
            #     if car.id != me.id and me.get_distance_to_unit(car) <= me.width * 1.2:
            #         cars_is_close = True
            #
            # if cars_is_close and any((
            #     all((
            #         next_tile_type == TileType.VERTICAL,
            #         abs(me.speed_x) < SMALL_SPEED,
            #         # abs(me.speed_y) > MEDIUM_SPEED,
            #     )),
            #     all((
            #         next_tile_type == TileType.HORIZONTAL,
            #         abs(me.speed_y) < SMALL_SPEED,
            #         # abs(me.speed_x) > MEDIUM_SPEED,
            #     ))
            # )):
            #     return self.move_forward_and_return(move)
            # # FIXME ends

            next_x = (next_tile_x + NEXT_TILE_OFFSET) * game.track_tile_size
            next_y = (next_tile_y + NEXT_TILE_OFFSET) * game.track_tile_size

            corner_tile_offset = 0.32 * game.track_tile_size
            if next_tile_type == TileType.LEFT_TOP_CORNER:
                next_x += corner_tile_offset
                next_y += corner_tile_offset
            elif next_tile_type == TileType.RIGHT_TOP_CORNER:
                next_x -= corner_tile_offset
                next_y += corner_tile_offset
            elif next_tile_type == TileType.LEFT_BOTTOM_CORNER:
                next_x += corner_tile_offset
                next_y -= corner_tile_offset
            elif next_tile_type == TileType.RIGHT_BOTTOM_CORNER:
                next_x -= corner_tile_offset
                next_y -= corner_tile_offset
            elif next_tile_type == TileType.BOTTOM_HEADED_T and straight_moves == 1:
                next_y += corner_tile_offset
            elif next_tile_type == TileType.LEFT_HEADED_T and straight_moves == 1:
                next_x -= corner_tile_offset
            elif next_tile_type == TileType.RIGHT_HEADED_T and straight_moves == 1:
                next_x += corner_tile_offset
            elif next_tile_type == TileType.TOP_HEADED_T and straight_moves == 1:
                next_y -= corner_tile_offset

            angle_to_next_tile = me.get_angle_to(next_x, next_y)
            move.wheel_turn = angle_to_next_tile * 32.0 / pi

            if curr_speed_module ** 2 * abs(angle_to_next_tile) > 3 ** 2 * pi or \
                    curr_speed_module > BIG_SPEED and straight_moves == 1:
                move.engine_power = 0.7
                move.brake = True
            else:
                move.engine_power = 1.0

            # используем инвентарь
            if self.check_other_cars(world, me, PROJECTILE_THROW_DISTANCE, 0):
                move.throw_projectile = True
            if self.check_other_cars(world, me, OIL_SPILL_DISTANCE, pi) and curr_tile_type in TURN_TILES:
                move.spill_oil = True
            if straight_moves > 3 and angle_to_next_tile < ANGLE_DELTA:
                move.use_nitro = True

        # задний ход
        elif self.state == REVERSE_ST:
            if self.rear_move_ticks_remain > 0:
                self.rear_move_ticks_remain -= 1
                next_x = (next_tile_x + NEXT_TILE_OFFSET) * game.track_tile_size
                next_y = (next_tile_y + NEXT_TILE_OFFSET) * game.track_tile_size
                move.wheel_turn = -100 if me.get_angle_to(next_x, next_y) * 32.0 / pi > 0 else 100
                move.engine_power = -1.0
                return
            else:
                if curr_speed_module > SMALL_SPEED:
                    move.brake = True
                    move.engine_power = 1
                    return
                else:
                    self.state = ACCELERATION_ST
 def move(self, me: Hockeyist, world: World, game: Game, move: Move):
     move.speed_up = -1.0
     move.turn = pi
     move.action = ActionType.STRIKE
Exemple #48
0
    def moveToPoint(self, targetX, targetY, me: Trooper, world: object, game: Game, move: Move):
        cells = world.cells

        offsetX = 0

        if me.x > targetX:
            offsetX = -1
        elif me.x < targetX:
            offsetX = 1
        else:
            offsetX = 0

        offsetY = 0

        if me.y > targetY:
            offsetY = -1
        elif me.y < targetY:
            offsetY = 1
        else:
            offsetY = 0

        x = -1
        y = -1
        canMoveToPoint = False

        if offsetX != 0:
            x = me.x + offsetX
            y = me.y
        elif offsetY != 0:
            x = me.x
            y = me.y + offsetY

        for bonus in world.bonuses:
            if bonus.x == x and bonus.y == y:
                canMoveToPoint = True

        canMoveX = offsetX != 0 and cells[me.x + offsetX][me.y] == CellType.FREE
        canMoveY = offsetY != 0 and cells[me.x][me.y + offsetY] == CellType.FREE

        canMoveX = canMoveX or canMoveToPoint
        canMoveY = canMoveY or canMoveToPoint

        if canMoveX or canMoveY:
            move.action = ActionType.MOVE

            if canMoveX and canMoveY:
                if randint(0, 9) % 2 == 0:
                    move.x = me.x + offsetX
                    move.y = me.y
                else:
                    move.x = me.x
                    move.y = me.y + offsetY
            elif canMoveX:
                move.x = me.x + offsetX
                move.y = me.y
            else:
                move.x = me.x
                move.y = me.y + offsetY
        else:
            print('Recalculate direction')

            quarter = 0

            if me.x > targetX and me.y < targetY:
                quarter = 1
            elif me.x > targetX and me.y > targetY:
                quarter = 2
            elif me.x < targetX and me.y > targetY:
                quarter = 3
            elif me.x < targetX and me.y < targetY:
                quarter = 4

            if quarter == 1:
                offsetX = 1
                offsetY = -1
            elif quarter == 2:
                offsetX = 1
                offsetY = 1
            elif quarter == 3:
                offsetX = -1
                offsetY = 1
            elif quarter == 4:
                offsetX = -1
                offsetY = -1

            if offsetX != 0:
                x = me.x + offsetX
                y = me.y
            elif offsetY != 0:
                x = me.x
                y = me.y + offsetY

            canMoveX = offsetX != 0 and cells[me.x + offsetX][me.y] == CellType.FREE
            canMoveY = offsetY != 0 and cells[me.x][me.y + offsetY] == CellType.FREE

            #if not canMoveX and not canMoveY:
                #self.moveToPoint(targetX + randint(0, 9) % 2, targetY + randint(0, 9) % 2, me, world, game, move)
                #return

            if canMoveX or canMoveY:
                print('Can move new direction')
                move.action = ActionType.MOVE

                if canMoveX and canMoveY:
                    if randint(0, 9) % 2 == 0:
                        move.x = me.x + offsetX
                        move.y = me.y
                    else:
                        move.x = me.x
                        move.y = me.y + offsetY
                elif canMoveX:
                    move.x = me.x + offsetX
                    move.y = me.y
                else:
                    move.x = me.x
                    move.y = me.y + offsetY