class TestCommandLine(unittest.TestCase):
    def setUp(self):
        time_step = 0.05
        self.agents = [Agent(0, 0, time_step)]
        self.arena = Arena(10, 20)
        self.biased_grid = BiasedGrid(self.arena.get_dimensions())
        self.algorithm = AStar(self.arena, self.agents, self.biased_grid)
        self.cli = CommandLine(self.arena, self.agents)

    def test_help(self):
        command = 'help'
        retval = self.cli.parse_command(command)
        self.assertTrue(retval)

    def test_help_specific(self):
        command = 'help move_agent'
        retval = self.cli.parse_command(command)
        self.assertTrue(retval)

    def test_agent_move(self):
        command = 'move_agent 0 X 4'
        retval = self.cli.parse_command(command)
        self.assertTrue(retval)

    def test_blockage(self):
        command = 'blockage set 4 4'
        retval = self.cli.parse_command(command)
        self.assertTrue(retval)
        self.assertEqual(TileState.BLOCKED, self.arena.get_tile_state(4, 4))
Example #2
0
def arena_panel(request):
    arena = Arena(request._char_id)
    response = ArenaPanelResponse()
    response.ret = 0

    arena._fill_up_panel_msg(response.panel)
    return pack_msg(response)
 def setUp(self):
     time_step = 0.05
     self.agents = [Agent(0, 0, time_step)]
     self.arena = Arena(10, 20)
     self.biased_grid = BiasedGrid(self.arena.get_dimensions())
     self.algorithm = AStar(self.arena, self.agents, self.biased_grid)
     self.cli = CommandLine(self.arena, self.agents)
 def setUp(self):
     time_step = 0.005
     self.arena = Arena(10, 10)
     self.biased_grid = BiasedGrid(self.arena.get_dimensions())
     self.agents = [Agent(0, 0, time_step), Agent(1, 1, time_step)]
     self.algorithm = SingleAgentAlgorithmMock(self.arena, self.agents,
                                               self.biased_grid)
Example #5
0
def arena_panel(request):
    arena = Arena(request._char_id)
    response = ArenaPanelResponse()
    response.ret = 0

    arena.fill_up_panel_msg(response.panel)
    return pack_msg(response)
Example #6
0
def arena_battle(request):
    char_id = request._char_id

    arena = Arena(char_id)
    msg = arena.battle()

    response = ArenaResponse()
    response.ret = 0
    response.battle.MergeFrom(msg)

    return pack_msg(response)
Example #7
0
def arena_battle(request):
    char_id = request._char_id

    arena = Arena(char_id)
    msg, drop = arena.battle()

    response = ArenaResponse()
    response.ret = 0
    response.battle.MergeFrom(msg)
    response.drop.MergeFrom(standard_drop_to_attachment_protomsg(drop))
    return pack_msg(response)
Example #8
0
def arena_battle(request):
    char_id = request._char_id

    arena = Arena(char_id)
    msg, drop = arena.battle()

    response = ArenaResponse()
    response.ret = 0
    response.battle.MergeFrom(msg)
    response.drop.MergeFrom(standard_drop_to_attachment_protomsg(drop))
    return pack_msg(response)
Example #9
0
def arena_battle(request):
    char_id = request._char_id

    arena = Arena(char_id)
    msg = arena.battle()

    response = ArenaResponse()
    response.ret = 0
    response.battle.MergeFrom(msg)

    return pack_msg(response)
Example #10
0
def get_honor_reward(request):
    server_id = request._game_session.server_id
    char_id = request._game_session.char_id

    honor = request._proto.honor

    a = Arena(server_id, char_id)
    resource_classified = a.get_honor_reward(honor)

    response = ArenaHonorGetRewardResponse()
    response.ret = 0
    response.drop.MergeFrom(resource_classified.make_protomsg())

    return ProtobufResponse(response)
Example #11
0
def match_start(request):
    server_id = request._game_session.server_id
    char_id = request._game_session.char_id

    formation_slots = parse_protocol_sync_formation_slots(request._proto.slots)

    a = Arena(server_id, char_id)
    msg = a.match(formation_slots)

    response = ArenaMatchStartResponse()
    response.ret = 0
    response.match.MergeFrom(msg)

    return ProtobufResponse(response)
Example #12
0
def match_start(request):
    server_id = request._game_session.server_id
    char_id = request._game_session.char_id

    formation_slots = parse_protocol_sync_formation_slots(request._proto.slots)

    a = Arena(server_id, char_id)
    msg = a.match(formation_slots)

    response = ArenaMatchStartResponse()
    response.ret = 0
    response.match.MergeFrom(msg)

    return ProtobufResponse(response)
Example #13
0
def get_honor_reward(request):
    server_id = request._game_session.server_id
    char_id = request._game_session.char_id

    honor = request._proto.honor

    a = Arena(server_id, char_id)
    resource_classified = a.get_honor_reward(honor)

    response = ArenaHonorGetRewardResponse()
    response.ret = 0
    response.drop.MergeFrom(resource_classified.make_protomsg())

    return ProtobufResponse(response)
Example #14
0
def arena_battle(request):
    char_id = request._char_id

    arena = Arena(char_id)
    msg, adding_score = arena.battle()

    response = ArenaResponse()
    response.ret = 0
    response.battle.MergeFrom(msg)

    drop = make_standard_drop_from_template()
    drop["stuffs"] = [(1001, adding_score)]

    response.drop.MergeFrom(standard_drop_to_attachment_protomsg(drop))
    return pack_msg(response)
Example #15
0
    def check_exist(self, server_id, char_id):
        from core.club import Club
        from core.bag import Bag
        from core.staff import StaffManger, StaffRecruit
        from core.territory import Territory
        from core.arena import Arena
        from core.energy import Energy

        money_text = self.money_as_text_dict()
        if money_text:
            Club(server_id, char_id).check_money(**money_text)
        if self.bag:
            Bag(server_id, char_id).check_items(self.bag)
        if self.staff:
            StaffManger(server_id,
                        char_id).check_original_staff_is_initial_state(
                            self.staff)
        if self.territory_product:
            Territory(server_id, char_id).check_product(self.territory_product)
        if self.work_card:
            Territory(server_id, char_id).check_work_card(self.work_card)
        if self.arena_point:
            Arena(server_id, char_id).check_point(self.arena_point)
        if self.energy:
            Energy(server_id, char_id).check(self.energy)
        if self.staff_recruit_score:
            StaffRecruit(server_id,
                         char_id).check_score(self.staff_recruit_score)
        if self.resource_data:
            _r = _Resource()
            _r.resource = dict(self.resource_data)
            _r.check_exists(server_id, char_id)
Example #16
0
def send_rank_reward(*args):
    logger = Logger("arena_send_rank_reward")
    logger.write("Start")

    try:
        for sid in Server.duty_server_ids():
            MongoArena.db(sid).update_many({}, {'$set': {'continue_win': 0}})

            Arena.send_rank_reward(sid)
            logger.write("Server {0} Finish".format(sid))
    except:
        logger.error(traceback.format_exc())
    else:
        logger.write("Done")
    finally:
        logger.close()
Example #17
0
    def add(self, server_id, char_id, message=""):
        from core.club import Club
        from core.bag import Bag
        from core.staff import StaffManger, StaffRecruit
        from core.talent import TalentManager
        from core.territory import Territory
        from core.vip import VIP
        from core.arena import Arena
        from core.energy import Energy
        from core.plunder import Plunder

        club_property = self.money_as_text_dict()
        if self.club_exp:
            club_property['exp'] = self.club_exp
        if club_property:
            club_property['message'] = message
            Club(server_id, char_id).update(**club_property)

        if self.vip_exp:
            VIP(server_id, char_id).add_exp(self.vip_exp)

        if self.bag:
            bag = Bag(server_id, char_id)
            bag.batch_add(self.bag)

        sm = StaffManger(server_id, char_id)
        if self.staff:
            sm.batch_add(self.staff)

        if self.staff_exp_pool:
            sm.add_exp_pool(self.staff_exp_pool)

        if self.talent_point:
            TalentManager(server_id,
                          char_id).add_talent_points(self.talent_point)

        if self.arena_point:
            Arena(server_id, char_id).add_point(self.arena_point)

        if self.territory_product:
            Territory(server_id, char_id).add_product(self.territory_product)

        if self.work_card:
            Territory(server_id, char_id).add_work_card(self.work_card)

        if self.energy:
            Energy(server_id, char_id).add(self.energy)

        if self.staff_recruit_score:
            StaffRecruit(server_id,
                         char_id).add_score(self.staff_recruit_score)

        if self.station_exp:
            Plunder(server_id, char_id).add_station_exp(self.station_exp)

        if self.resource_data:
            _r = _Resource()
            _r.resource = dict(self.resource_data)
            _r.add(server_id, char_id)
Example #18
0
 def parse_arena(self) -> None:
     """
     Creates the simulation arena
     :return:
     """
     arena = self.config['arena_properties']
     arena_size = arena['size']
     sim_arena = Arena(arena_size[0], arena_size[1])
     blockages = arena['blockages']
     for blockage in blockages:
         sim_arena.set_blockage([blockage[0]], [blockage[1]])
     self.arena = sim_arena
     self.biased_grid = BiasedGrid(self.arena.get_dimensions())
     biased_squares = arena['biases']
     self._event_squares = arena['event_squares']
     for bias in biased_squares:
         self.biased_grid[bias[0], bias[1]] = bias[2]
Example #19
0
 def try_cast_login_notify(self):
     # 这个玩家登陆要广播的消息
     from core.arena import Arena
     top = Arena.get_leader_board(self.server_id, amount=1)
     if top and top[0].id == self.char_id:
         template = ConfigBroadcastTemplate.get(4).template
         text = template.format(self.name)
         self.do_cast(text)
Example #20
0
def refresh(request):
    server_id = request._game_session.server_id
    char_id = request._game_session.char_id

    Arena(server_id, char_id).refresh()

    response = ArenaRefreshResponse()
    response.ret = 0
    return ProtobufResponse(response)
Example #21
0
def buy_times(request):
    server_id = request._game_session.server_id
    char_id = request._game_session.char_id

    Arena(server_id, char_id).buy_times()

    response = ArenaBuyTimesResponse()
    response.ret = 0
    return ProtobufResponse(response)
Example #22
0
def match_report(request):
    server_id = request._game_session.server_id
    char_id = request._game_session.char_id

    key = request._proto.key
    win = request._proto.win

    a = Arena(server_id, char_id)
    resource_classified, score_changed, rank_changed, max_rank, my_rank, my_score = a.report(key, win)

    response = ArenaMatchReportResponse()
    response.ret = 0
    response.drop.MergeFrom(resource_classified.make_protomsg())
    response.score_changed = score_changed
    response.rank_changed = rank_changed
    response.max_rank = max_rank
    response.my_rank = my_rank
    response.my_score = my_score
    return ProtobufResponse(response)
Example #23
0
def match_report(request):
    server_id = request._game_session.server_id
    char_id = request._game_session.char_id

    key = request._proto.key
    win = request._proto.win

    a = Arena(server_id, char_id)
    resource_classified, score_changed, rank_changed, max_rank, my_rank, my_score = a.report(
        key, win)

    response = ArenaMatchReportResponse()
    response.ret = 0
    response.drop.MergeFrom(resource_classified.make_protomsg())
    response.score_changed = score_changed
    response.rank_changed = rank_changed
    response.max_rank = max_rank
    response.my_rank = my_rank
    response.my_score = my_score
    return ProtobufResponse(response)
Example #24
0
    def __init__(self,
                 arena: Arena,
                 agents: list,
                 routing_manager: MultiAgentAlgorithm,
                 biased_grid: BiasedGrid,
                 timestep: float,
                 dpi_scaling: int = 40) -> None:
        """
        Create a new canvas for rendering the simulation. The base canvas is based on an Arena object,
        which controls the domain of the simulation
        :param: arena: the arena object
        :param: agents: list of agents
        :param: routing_manager: routing manager object
        :param: biased_grid: biased grid for routing only in certain directions
        :param: timestep: the animation timestep in seconds
        :param: dpi_scaling: the dpi scaling to use for one grid square
        :return:
        """
        # initialize pygame as a renderer
        pygame.init()
        pygame.font.init()

        # create the rendering canvas
        self.x_size, self.y_size = arena.get_dimensions()
        self.dpi = dpi_scaling
        self._display_x = self.x_size * self.dpi
        self._display_y = self.y_size * self.dpi
        self.screen = pygame.display.set_mode(
            (self._display_x, self._display_y))
        self.clock = pygame.time.Clock()

        self.arena = arena
        self.agents = agents
        self.routing_manager = routing_manager
        self.biased_grid = biased_grid
        self.agent_selected = None
        self._render_directions = True
        self._event_tiles = None

        # dict of color keys
        self.colors_dict = {
            'tile_free': (180, 180, 180),
            'tile_blocked': (0, 0, 0),
            'tile_reserved': (60, 60, 60),
            'tile_target': (200, 135, 135),
            'grid_lines': (255, 255, 255),
            'agent': COLORS,
            'agent_selected': (245, 100, 90),
            'agent_border': (0, 0, 0),
            'soft_bias': (225, 225, 225),
            'hard_bias': (200, 80, 80),
            'event_tile': (255, 255, 200)
        }
        self.total_elements = len(self.colors_dict)
Example #25
0
def send_rank_reward(*args):
    logger = Logger("arena_send_rank_reward")
    logger.write("Start")

    try:
        for sid in Server.duty_server_ids():
            MongoArena.db(sid).update_many(
                {},
                {'$set': {
                    'continue_win': 0
                }}
            )

            Arena.send_rank_reward(sid)
            logger.write("Server {0} Finish".format(sid))
    except:
        logger.error(traceback.format_exc())
    else:
        logger.write("Done")
    finally:
        logger.close()
Example #26
0
def login_notify(char_id):
    hero_objs = char_heros_obj(char_id)

    Char(char_id).send_notify()

    hero_notify(char_id, hero_objs)
    Item(char_id).send_notify()

    f = Formation(char_id)
    f.send_socket_notify()
    f.send_formation_notify()

    hang = Hang(char_id)
    hang.send_notify()

    Plunder(char_id).send_notify()

    p = Prison(char_id)
    p.send_prisoners_notify()

    Arena(char_id).send_notify()

    f = Friend(char_id)
    f.send_friends_notify()
    f.send_friends_amount_notify()

    m = Mail(char_id)
    m.send_mail_notify()

    CheckIn(char_id).send_notify()


    stage = Stage(char_id)
    stage.send_already_stage_notify()
    stage.send_new_stage_notify()

    stage_elite = EliteStage(char_id)
    stage_elite.send_notify()
    stage_elite.send_remained_times_notify()

    stage_activity = ActivityStage(char_id)
    stage_activity.send_notify()
    stage_activity.send_remained_times_notify()

    HeroPanel(char_id).send_notify()
    Task(char_id).send_notify()
    Achievement(char_id).send_notify()
    HeroSoul(char_id).send_notify()
    FunctionOpen(char_id).send_notify()
    Levy(char_id).send_notify()
    Attachment(char_id).send_notify()
Example #27
0
def leader_board(request):
    server_id = request._game_session.server_id

    clubs = Arena.get_leader_board(server_id)

    response = ArenaLeaderBoardResponse()
    response.ret = 0
    for index, club in enumerate(clubs):
        response_rival = response.rival.add()
        response_rival.id = str(club.id)
        response_rival.name = club.name
        response_rival.club_flag = club.flag
        response_rival.level = club.level
        response_rival.power = club.power
        response_rival.rank = index + 1
        response_rival.score = ArenaScore(server_id, club.id).score

    return ProtobufResponse(response)
Example #28
0
def _func_opened(char_id, func_ids, **kwargs):
    need_task_notify = False
    task_related_func_ids = [t.func for t in TASKS.values() if t.func]
    for _id in func_ids:
        if _id in task_related_func_ids:
            need_task_notify = True
            break

    if need_task_notify:
        Task(char_id).send_notify()

    # dirty fix...
    # 比武功能没开放的时候,没有初始化
    # 所以在这里要初始化以便自动进入竞技场
    from core.arena import Arena
    for _id in func_ids:
        if _id == Arena.FUNC_ID:
            Arena(char_id).send_notify()
Example #29
0
def leader_board(request):
    server_id = request._game_session.server_id

    clubs = Arena.get_leader_board(server_id)

    response = ArenaLeaderBoardResponse()
    response.ret = 0
    for index, club in enumerate(clubs):
        response_rival = response.rival.add()
        response_rival.id = str(club.id)
        response_rival.name = club.name
        response_rival.club_flag = club.flag
        response_rival.level = club.level
        response_rival.power = club.power
        response_rival.rank = index+1
        response_rival.score = ArenaScore(server_id, club.id).score

    return ProtobufResponse(response)
Example #30
0
    def remove(self, server_id, char_id, message=""):
        from core.club import Club
        from core.bag import Bag
        from core.staff import StaffManger, StaffRecruit
        from core.territory import Territory
        from core.arena import Arena
        from core.energy import Energy

        money_text = self.money_as_text_dict()
        if money_text:
            money_text = {k: -v for k, v in money_text.iteritems()}
            money_text['message'] = message
            Club(server_id, char_id).update(**money_text)

        if self.bag:
            bag = Bag(server_id, char_id)
            for _id, _amount in self.bag:
                bag.remove_by_item_id(_id, _amount)

        if self.staff:
            StaffManger(server_id, char_id).internal_remove_by_oid(self.staff)

        if self.territory_product:
            Territory(server_id,
                      char_id).remove_product(self.territory_product)

        if self.work_card:
            Territory(server_id, char_id).remove_work_card(self.work_card)

        if self.arena_point:
            Arena(server_id, char_id).remove_point(self.arena_point)

        if self.energy:
            Energy(server_id, char_id).remove(self.energy)

        if self.staff_recruit_score:
            StaffRecruit(server_id,
                         char_id).remove_score(self.staff_recruit_score)

        if self.resource_data:
            _r = _Resource()
            _r.resource = dict(self.resource_data)
            _r.remove(server_id, char_id)
Example #31
0
def arena_info(request):
    servers_select = get_servers_select_context()
    context = {
        'current': 'arena',
        'servers_select': servers_select,
        'clubs': []
    }

    sid = request.GET.get('sid', 0)
    if not sid:
        return render_to_response(
            'dianjing_statistics_arena.html',
            context=context
        )

    try:
        sid = int(sid)
    except:
        raise Http404()

    clubs = Arena.get_leader_board(sid)
    data = []
    for _index, c in enumerate(clubs):
        data.append({
            'rank': _index + 1,
            'id': c.id,
            'name': c.name,
            'level': c.level,
            'power': c.power,
            'score': ArenaScore(sid, c.id).score,
            'is_npc': is_npc_club(str(c.id)),
        })

    context['clubs'] = data
    return render_to_response(
        'dianjing_statistics_arena.html',
        context=context
    )
Example #32
0
def game_start_handler(server_id, char_id, **kwargs):
    MessagePipe(char_id).clean()

    msg = UTCNotify()
    msg.timestamp = arrow.utcnow().timestamp
    MessagePipe(char_id).put(msg=msg)

    msg = SocketServerNotify()
    ss = random.choice(settings.SOCKET_SERVERS)
    msg.ip = ss['host']
    msg.port = ss['tcp']
    MessagePipe(char_id).put(msg=msg)

    _Resource.send_notify(server_id, char_id)

    UnitManager(server_id, char_id).send_notify()

    Bag(server_id, char_id).send_notify()

    StaffManger(server_id, char_id).send_notify()
    StaffRecruit(server_id, char_id).send_notify()

    f = Formation(server_id, char_id)
    f.send_formation_notify()
    f.send_slot_notify()

    club = Club(server_id, char_id)
    club.set_login()
    club.send_notify()

    msg = CreateDaysNotify()
    msg.days = days_passed(club.create_at)
    msg.create_at = club.create_at
    MessagePipe(char_id).put(msg=msg)

    chall = Challenge(server_id, char_id)
    chall.send_chapter_notify()
    chall.send_challenge_notify()

    FriendManager(server_id, char_id).send_notify()
    MailManager(server_id, char_id).send_notify()

    TaskMain(server_id, char_id).send_notify()
    TaskDaily(server_id, char_id).send_notify()

    Chat(server_id, char_id).send_notify()

    Notification(server_id, char_id).send_notify()

    FinanceStatistics(server_id, char_id).send_notify()

    TalentManager(server_id, char_id).send_notify()

    Dungeon(server_id, char_id).send_notify()

    a = Arena(server_id, char_id)
    a.send_notify()
    a.send_honor_notify()

    t = Tower(server_id, char_id)
    t.send_notify()
    t.send_goods_notify()

    Territory(server_id, char_id).send_notify()
    TerritoryStore(server_id, char_id).send_notify()
    TerritoryFriend(server_id, char_id).send_remained_times_notify()

    Store(server_id, char_id).send_notify()
    VIP(server_id, char_id).send_notify()
    Collection(server_id, char_id).send_notify()

    Energy(server_id, char_id).send_notify()

    w = Welfare(server_id, char_id)
    w.send_signin_notify()
    w.send_new_player_notify()
    w.send_level_reward_notify()
    w.send_energy_reward_notify()

    Union(server_id, char_id).send_all_notify()

    Purchase(server_id, char_id).send_notify()

    ac = ActivityNewPlayer(server_id, char_id)
    ac.send_notify()
    ac.send_daily_buy_notify()

    ActivityOnlineTime(server_id, char_id).send_notify()
    ActivityChallenge(server_id, char_id).send_notify()
    ActivityPurchaseDaily(server_id, char_id).send_notify()
    ActivityPurchaseContinues(server_id, char_id).send_notify()
    ActivityLevelGrowing(server_id, char_id).send_notify()

    p = Plunder(server_id, char_id)

    p.send_search_notify()
    p.send_result_notify()
    p.send_revenge_notify()
    p.send_station_notify()
    p.send_formation_notify()
    p.send_plunder_times_notify()
    p.send_plunder_daily_reward_notify()

    SpecialEquipmentGenerator(server_id, char_id).send_notify()

    Party(server_id, char_id).send_notify()

    ins = Inspire(server_id, char_id)
    ins.try_open_slots(send_notify=False)
    ins.send_notify()

    cs = Championship(server_id, char_id)
    cs.try_initialize(send_notify=False)
    cs.send_notify()

    WinningPlunder(server_id, char_id).send_notify()
    WinningArena(server_id, char_id).send_notify()
    WinningChampionship(server_id, char_id).send_notify()
    Worship(server_id, char_id).send_notify()
    CommonArenaWinningChat(server_id, char_id).send_notify()
    CommonPlunderWinningChat(server_id, char_id).send_notify()
    CommonChampionshipChat(server_id, char_id).send_notify()

    send_system_notify(server_id, char_id)
    BroadCast(server_id, char_id).try_cast_login_notify()
Example #33
0
 def get_current_value(self, char_id):
     from core.arena import Arena
     return Arena(char_id).rank
Example #34
0
def game_start_handler(server_id, char_id, **kwargs):
    MessagePipe(char_id).clean()

    msg = UTCNotify()
    msg.timestamp = arrow.utcnow().timestamp
    MessagePipe(char_id).put(msg=msg)


    msg = SocketServerNotify()
    ss = random.choice(settings.SOCKET_SERVERS)
    msg.ip = ss['host']
    msg.port = ss['tcp']
    MessagePipe(char_id).put(msg=msg)

    _Resource.send_notify(server_id, char_id)

    UnitManager(server_id, char_id).send_notify()

    Bag(server_id, char_id).send_notify()

    StaffManger(server_id, char_id).send_notify()
    StaffRecruit(server_id, char_id).send_notify()

    f = Formation(server_id, char_id)
    f.send_formation_notify()
    f.send_slot_notify()

    club = Club(server_id, char_id)
    club.set_login()
    club.send_notify()

    msg = CreateDaysNotify()
    msg.days = days_passed(club.create_at)
    msg.create_at = club.create_at
    MessagePipe(char_id).put(msg=msg)

    chall = Challenge(server_id, char_id)
    chall.send_chapter_notify()
    chall.send_challenge_notify()

    FriendManager(server_id, char_id).send_notify()
    MailManager(server_id, char_id).send_notify()

    TaskMain(server_id, char_id).send_notify()
    TaskDaily(server_id, char_id).send_notify()

    Chat(server_id, char_id).send_notify()

    Notification(server_id, char_id).send_notify()

    FinanceStatistics(server_id, char_id).send_notify()

    TalentManager(server_id, char_id).send_notify()

    Dungeon(server_id, char_id).send_notify()

    a = Arena(server_id, char_id)
    a.send_notify()
    a.send_honor_notify()

    t = Tower(server_id, char_id)
    t.send_notify()
    t.send_goods_notify()

    Territory(server_id, char_id).send_notify()
    TerritoryStore(server_id, char_id).send_notify()
    TerritoryFriend(server_id, char_id).send_remained_times_notify()

    Store(server_id, char_id).send_notify()
    VIP(server_id, char_id).send_notify()
    Collection(server_id, char_id).send_notify()

    Energy(server_id, char_id).send_notify()

    w = Welfare(server_id, char_id)
    w.send_signin_notify()
    w.send_new_player_notify()
    w.send_level_reward_notify()
    w.send_energy_reward_notify()

    Union(server_id, char_id).send_all_notify()

    Purchase(server_id, char_id).send_notify()

    ac = ActivityNewPlayer(server_id, char_id)
    ac.send_notify()
    ac.send_daily_buy_notify()

    ActivityOnlineTime(server_id, char_id).send_notify()
    ActivityChallenge(server_id, char_id).send_notify()
    ActivityPurchaseDaily(server_id, char_id).send_notify()
    ActivityPurchaseContinues(server_id, char_id).send_notify()
    ActivityLevelGrowing(server_id, char_id).send_notify()

    p = Plunder(server_id, char_id)

    p.send_search_notify()
    p.send_result_notify()
    p.send_revenge_notify()
    p.send_station_notify()
    p.send_formation_notify()
    p.send_plunder_times_notify()
    p.send_plunder_daily_reward_notify()

    SpecialEquipmentGenerator(server_id, char_id).send_notify()

    Party(server_id, char_id).send_notify()

    ins = Inspire(server_id, char_id)
    ins.try_open_slots(send_notify=False)
    ins.send_notify()

    cs = Championship(server_id, char_id)
    cs.try_initialize(send_notify=False)
    cs.send_notify()

    WinningPlunder(server_id, char_id).send_notify()
    WinningArena(server_id, char_id).send_notify()
    WinningChampionship(server_id, char_id).send_notify()
    Worship(server_id, char_id).send_notify()
    CommonArenaWinningChat(server_id, char_id).send_notify()
    CommonPlunderWinningChat(server_id, char_id).send_notify()
    CommonChampionshipChat(server_id, char_id).send_notify()

    send_system_notify(server_id, char_id)
    BroadCast(server_id, char_id).try_cast_login_notify()
Example #35
0
from core.agent import *
from core.arena import Arena

BASE_TIME_STEP = 0.05
BASE_DPI = 40


# CLI thread
def cli_thread_func(arena: Arena, agents: list) -> None:
    cli = CommandLine(arena, agents)
    while True:
        cli.get_input()


# setup an arena
sim_arena = Arena(40, 40)

# create some agents and add them to the agents list
sim_agent = Agent(0, 0, BASE_TIME_STEP)
sim_agent_1 = Agent(5, 5, BASE_TIME_STEP)
sim_agent_1.set_kinematic_parameters(4, 4, 4)
sim_agent.set_kinematic_parameters(6, 6, 6)
sim_agents = list()
sim_agents.append(sim_agent)
sim_agents.append(sim_agent_1)

# setup the routing algorithm
algorithm = AStar(sim_arena, sim_agents)
algorithm.turn_factor = 2

# create the pathing algorithm
 def setUp(self):
     time_step = 0.005
     self.arena = Arena(10, 10)
     self.biased_grid = BiasedGrid(self.arena.get_dimensions())
     self.agents = [Agent(0, 0, time_step), Agent(1, 1, time_step)]
     self.a_star = AStar(self.arena, self.agents, self.biased_grid)
class TestAStar(unittest.TestCase):
    def setUp(self):
        time_step = 0.005
        self.arena = Arena(10, 10)
        self.biased_grid = BiasedGrid(self.arena.get_dimensions())
        self.agents = [Agent(0, 0, time_step), Agent(1, 1, time_step)]
        self.a_star = AStar(self.arena, self.agents, self.biased_grid)

    def test_a_star_init(self):
        self.assertEqual(self.arena, self.a_star.arena)
        self.assertEqual(self.agents, self.a_star.agents)
        self.assertEqual([], self.a_star.path)

    def test_check_blocked_square_fails(self):
        self.arena.set_blockage([0], [1])
        status = self.a_star.check_target_location(0, 1)
        self.assertEqual(RoutingStatus.TARGET_BLOCKED, status)

    def test_check_reserved_square_fails(self):
        self.arena.set_reserved([0], [1])
        status = self.a_star.check_target_location(0, 1)
        self.assertEqual(RoutingStatus.TARGET_RESERVED, status)

    def test_route_to_blocked_square_fails(self):
        self.arena.set_blockage([0], [1])
        status = self.a_star.route(self.agents[0], (0, 1))
        self.assertEqual(RoutingStatus.TARGET_BLOCKED, status)

    def test_route_to_reserved_square_fails(self):
        self.arena.set_reserved([0], [1])
        status = self.a_star.route(self.agents[0], (0, 1))
        self.assertEqual(RoutingStatus.TARGET_RESERVED, status)

    def test_initialize_nodes(self):
        start = (0, 0)
        target = (0, 4)
        start_node = AStarNode(start)
        end_node = AStarNode(target)
        self.a_star.initialize_nodes(self.agents[0], target)
        start_eq = start_node == self.a_star.start
        end_eq = end_node == self.a_star.target
        self.assertTrue(start_eq)
        self.assertTrue(end_eq)

    def test_get_new_nodes_in_empty_area(self):
        # initialize the search, and then get neighbouring tiles
        start = (1, 1)
        expected_neighbours = [(2, 1), (1, 2), (0, 1), (1, 0)]
        parent_node = AStarNode(start)
        new_nodes = self.a_star.generate_new_nodes(parent_node)
        self.assertEqual(len(expected_neighbours), len(new_nodes))
        # make sure all of the correct nodes are returned
        for node_location in expected_neighbours:
            test_node = AStarNode(node_location)
            node_exists = test_node in new_nodes
            self.assertTrue(node_exists)

    def test_get_new_nodes_in_corner(self):
        # initialize the search in a corner, and then get neighbouring tiles
        start = (0, 0)
        expected_neighbours = [(0, 1), (1, 0)]
        parent_node = AStarNode(start)
        new_nodes = self.a_star.generate_new_nodes(parent_node)
        self.assertEqual(len(expected_neighbours), len(new_nodes))
        # make sure all of the correct nodes are returned
        for node_location in expected_neighbours:
            test_node = AStarNode(node_location)
            node_exists = test_node in new_nodes
            self.assertTrue(node_exists)

    def test_get_new_nodes_with_blockage(self):
        # initialize the search, set some blockages, and then make sure only the free tiles are returned
        start = (1, 1)
        self.arena.set_blockage([2], [0, 1, 2, 3])
        expected_neighbours = [(1, 2), (0, 1), (1, 0)]
        parent_node = AStarNode(start)
        new_nodes = self.a_star.generate_new_nodes(parent_node)
        self.assertEqual(len(expected_neighbours), len(new_nodes))
        # make sure all of the correct nodes are returned
        for node_location in expected_neighbours:
            test_node = AStarNode(node_location)
            node_exists = test_node in new_nodes
            self.assertTrue(node_exists)

    def test_calculate_heuristic(self):
        start = (1, 1)
        target = (4, 4)
        start_node = AStarNode(start)
        target_node = AStarNode(target)
        heuristic = self.a_star.calculate_heuristic_cost(
            start_node, target_node)
        self.assertEqual(6, heuristic)

    @unittest.skip('debug')
    def test_routing_simple_path(self):
        target = (4, 4)
        status = self.a_star.route(self.agents[0], target)
        self.assertEqual(RoutingStatus.SUCCESS, status)
        # make sure the final nodes are correct
        self.assertTupleEqual((4, 4), self.a_star.node_path[-1].location)

    def test_route_to_tile_with_other_agent_fails(self):
        status = self.a_star.check_target_location(1, 1)
        self.assertEqual(RoutingStatus.TARGET_RESERVED, status)

    def test_calculate_turn_cost_no_factor(self):
        start_node = AStarNode((0, 0))
        node_1 = AStarNode((1, 0), parent=start_node)
        node_2 = AStarNode((2, 0), parent=node_1)
        node_3 = AStarNode((2, 1), parent=node_2)
        node_4 = AStarNode((2, 2), parent=node_3)
        node_5 = AStarNode((3, 2), parent=node_4)
        turn_cost = self.a_star.calculate_turn_cost(node_5)
        self.assertEqual(0, turn_cost)

    def test_calculate_turn_cost_with_weight(self):
        start_node = AStarNode((0, 0))
        self.a_star.turn_factor = 1
        node_1 = AStarNode((1, 0), parent=start_node)
        node_2 = AStarNode((2, 0), parent=node_1)
        node_3 = AStarNode((2, 1), parent=node_2)
        node_4 = AStarNode((2, 2), parent=node_3)
        node_5 = AStarNode((3, 2), parent=node_4)
        turn_cost = self.a_star.calculate_turn_cost(node_5)
        self.assertEqual(2, turn_cost)

    def test_calculate_inline_cost(self):
        self.a_star.inline_factor = 10
        self.arena.set_agent_target(3, 3)
        node = AStarNode((1, 3))
        score = self.a_star.calculate_inline_cost(node)
        self.assertEqual(10, score)

    def test_is_direction_valid(self):
        parents = [(1, 1), (1, 1), (1, 1), (1, 1)]
        children = [(2, 1), (0, 1), (1, 2), (1, 0)]
        main_biases = [
            BiasedDirection.ONLY_X_POSITIVE, BiasedDirection.ONLY_X_NEGATIVE,
            BiasedDirection.ONLY_Y_POSITIVE, BiasedDirection.ONLY_Y_NEGATIVE
        ]
        secondary_biases = [
            BiasedDirection.ONLY_Y_POSITIVE, BiasedDirection.ONLY_Y_NEGATIVE,
            BiasedDirection.ONLY_X_POSITIVE, BiasedDirection.ONLY_X_NEGATIVE
        ]
        for idx in range(len(parents)):
            parent = parents[idx]
            child = children[idx]
            bias = main_biases[idx]
            self.biased_grid[child] = bias
            self.biased_grid[parent] = bias
            self.assertTrue(self.a_star.is_direction_valid(parent, child))
            self.assertFalse(self.a_star.is_direction_valid(child, parent))
            bias = secondary_biases[idx]
            self.biased_grid[child] = bias
            self.biased_grid[parent] = bias
            self.assertFalse(self.a_star.is_direction_valid(parent, child))
class TestSingleAgentAlgorithm(unittest.TestCase):
    def setUp(self):
        time_step = 0.005
        self.arena = Arena(10, 10)
        self.biased_grid = BiasedGrid(self.arena.get_dimensions())
        self.agents = [Agent(0, 0, time_step), Agent(1, 1, time_step)]
        self.algorithm = SingleAgentAlgorithmMock(self.arena, self.agents,
                                                  self.biased_grid)

    def tearDown(self):
        pass

    def test_reconstruct_empty_path_is_invalid(self):
        self.algorithm.node_path = list()
        status = self.algorithm.create_path()
        self.assertEqual(RoutingStatus.INVALID_PATH, status)

    def test_diagonal_path_is_invalid(self):
        self.algorithm.node_path = [NodeMock((0, 0)), NodeMock((1, 1))]
        status = self.algorithm.create_path()
        self.assertEqual(RoutingStatus.INVALID_PATH, status)

    def test_reconstruct_path(self):
        # force a list of nodes to be the node path
        self.algorithm.node_path = [
            NodeMock((0, 0)),
            NodeMock((0, 1)),
            NodeMock((0, 2)),
            NodeMock((1, 2)),
            NodeMock((2, 2))
        ]
        status = self.algorithm.create_path()
        self.assertEqual(RoutingStatus.SUCCESS, status)
        # The order of the tasks should be: Move X 2, Move Y 2
        task_direction = [AgentCoordinates.Y, AgentCoordinates.X]
        task_distance = [2, 2]
        for idx, task in enumerate(self.algorithm.path):
            self.assertEqual(task_direction[idx], task.args[0])
            self.assertEqual(task_distance[idx], task.args[1])

    def test_reconstruct_path_zig_zag(self):
        # force a list of nodes to be the node path
        self.algorithm.node_path = [
            NodeMock((0, 0)),
            NodeMock((1, 0)),
            NodeMock((1, 1)),
            NodeMock((2, 1)),
            NodeMock((2, 2)),
            NodeMock((3, 2)),
            NodeMock((3, 3)),
            NodeMock((4, 3)),
            NodeMock((4, 4))
        ]
        status = self.algorithm.create_path()
        self.assertEqual(RoutingStatus.SUCCESS, status)
        # this path should contain 8 tasks
        self.assertEqual(8, len(self.algorithm.path))
        # The order of the tasks should be: Move X 1, Move Y 1, Move X 1, Move Y 1
        task_direction = [
            AgentCoordinates.X, AgentCoordinates.Y, AgentCoordinates.X,
            AgentCoordinates.Y, AgentCoordinates.X, AgentCoordinates.Y,
            AgentCoordinates.X, AgentCoordinates.Y
        ]
        task_distance = [1, 1, 1, 1, 1, 1, 1, 1]
        for idx, task in enumerate(self.algorithm.path):
            self.assertEqual(task_direction[idx], task.args[0])
            self.assertEqual(task_distance[idx], task.args[1])
Example #39
0
def login_notify(char_id):
    message_clean(char_id)
    function_open = FunctionOpen(char_id)
    function_open.send_notify()

    hero_objs = char_heros_obj(char_id)

    Char(char_id).send_notify()
    VIP(char_id).send_notify()

    hero_notify(char_id, hero_objs)
    Item(char_id).send_notify()

    f = Formation(char_id)
    f.send_socket_notify()
    f.send_formation_notify()


    Plunder(char_id).send_notify()

    p = Prison(char_id)
    p.send_prisoners_notify()

    a = Arena(char_id)
    a.send_notify()
    a.login_process()

    f = Friend(char_id)
    f.send_friends_notify()
    f.send_friends_amount_notify()

    CheckIn(char_id).send_notify()

    stage = Stage(char_id)
    stage.send_already_stage_notify()
    stage.send_new_stage_notify()

    stage_elite = EliteStage(char_id)
    stage_elite.send_notify()
    stage_elite.send_times_notify()

    stage_activity = ActivityStage(char_id)
    stage_activity.check(send_notify=False)
    stage_activity.send_notify()
    stage_activity.send_remained_times_notify()

    HeroPanel(char_id).send_notify()
    Task(char_id).send_notify()
    Achievement(char_id).send_notify()
    HeroSoul(char_id).send_notify()
    Levy(char_id).send_notify()
    Attachment(char_id).send_notify()

    BasePurchaseAction(char_id).send_notify()

    SystemBroadcast(char_id).send_global_broadcast()
    ChatMessagePublish(char_id).send_notify()

    affairs = Affairs(char_id)
    affairs.send_city_notify()
    affairs.send_hang_notify()

    HorseFreeTimesManager(char_id).send_notify()
    Horse(char_id).send_notify()

    union.send_notify(char_id)


    ae = ActivityEntry(char_id, 50006)
    if ae and ae.is_valid():
        ae.enable(ae.get_current_value(char_id))

    ActivityStatic(char_id).send_notify()

    # mail notify 要放在最后,因为 其他功能初始化时可能会产生登录邮件
    Mail(char_id).send_notify()
class TestMultiAgentAlgorithm(unittest.TestCase):
    def setUp(self):
        time_step = 0.005
        self.arena = Arena(10, 10)
        self.biased_grid = BiasedGrid(self.arena.get_dimensions())
        self.agents = [Agent(0, 0, time_step), Agent(5, 5, time_step)]
        self.algorithm = SingleAgentAlgorithmMock(self.arena, self.agents,
                                                  self.biased_grid)
        self.routing_manager = MultiAgentAlgorithmMock(self.arena, self.agents,
                                                       self.algorithm)

    def tearDown(self):
        pass

    def test_is_simulation_completed_passes_if_final_goal_reached(self):
        self.routing_manager.add_agent_goal(0, (0, 0))
        self.routing_manager.add_agent_goal(1, (5, 5))
        self.assertTrue(self.routing_manager.is_simulation_complete())

    def test_simulation_not_completed_if_final_goal_not_reached(self):
        # add the current location as a segment, but also add a second location for each agent
        self.routing_manager.add_agent_goal(0, (0, 0))
        self.routing_manager.add_agent_goal(1, (5, 5))
        self.routing_manager.add_agent_goal(0, (1, 1))
        self.routing_manager.add_agent_goal(1, (4, 4))
        self.assertFalse(self.routing_manager.is_simulation_complete())

    def test_update_agent_goal(self):
        self.routing_manager.add_agent_goal(0, (0, 0))
        self.routing_manager.add_agent_goal(0, (1, 1))
        self.assertTrue(self.routing_manager.is_agent_at_goal(0))
        self.routing_manager.update_agent_goal(0)
        self.assertTupleEqual((1, 1), self.routing_manager.agent_goals[0][0])
        self.assertFalse(self.routing_manager.is_agent_at_goal(0))
        self.assertFalse(self.routing_manager.is_simulation_complete())

    def test_routing_blockages(self):
        move_x_task = AgentTask(AgentTasks.MOVE, [AgentCoordinates.X, 3])
        move_y_task = AgentTask(AgentTasks.MOVE, [AgentCoordinates.Y, 3])
        self.routing_manager.add_agent_task(0, move_x_task)
        for i in range(1, 3):
            self.assertEqual(TileState.RESERVED,
                             self.arena.get_tile_state(i, 0))
        self.assertEqual(TileState.AGENT_TARGET,
                         self.arena.get_tile_state(3, 0))
        self.routing_manager.add_agent_task(0, move_y_task)
        for i in range(1, 3):
            self.assertEqual(TileState.RESERVED,
                             self.arena.get_tile_state(3, i))
        self.assertEqual(TileState.AGENT_TARGET,
                         self.arena.get_tile_state(3, 3))

    def test_adding_and_completing_task_clears_blockage(self):
        move_x_task = AgentTask(AgentTasks.MOVE, [AgentCoordinates.X, 3])
        self.routing_manager.add_agent_task(0, move_x_task)
        for i in range(1, 3):
            self.assertEqual(TileState.RESERVED,
                             self.arena.get_tile_state(i, 0))
        self.assertEqual(TileState.AGENT_TARGET,
                         self.arena.get_tile_state(3, 0))
        self.routing_manager.signal_agent_event(0, AgentEvent.TASK_COMPLETED)
        for i in range(1, 4):
            self.assertEqual(TileState.FREE, self.arena.get_tile_state(i, 0))

    def test_completing_task_clears_agent_active(self):
        move_x_task = AgentTask(AgentTasks.MOVE, [AgentCoordinates.X, 3])
        self.routing_manager.add_agent_task(0, move_x_task)
        self.routing_manager.signal_agent_event(0, AgentEvent.TASK_COMPLETED)
        self.assertFalse(self.routing_manager.active_agents[0])

    def test_initialize_algorithm(self):
        self.routing_manager.initialize()
        self.assertTrue(self.routing_manager.initialized)

    def test_is_agent_at_goal(self):
        self.routing_manager.add_agent_goal(0, (0, 0))
        self.assertTrue(self.routing_manager.is_agent_at_goal(0))

    def test_start_new_task(self):
        move_x_task = AgentTask(AgentTasks.MOVE, [AgentCoordinates.X, 3])
        self.routing_manager.add_agent_task(0, move_x_task)
        self.routing_manager.start_new_task(0)
        self.assertTrue(self.routing_manager.active_agents[0])
Example #41
0
    def buy(self, tp, goods_id):
        if tp not in ALL_TYPES:
            raise GameException(
                ConfigErrorMessage.get_error_id("INVALID_OPERATE"))

        config = ConfigStore.get(goods_id)
        if not config:
            raise GameException(
                ConfigErrorMessage.get_error_id("STORE_GOODS_NOT_EXIST"))

        try:
            data = self.doc['tp'][str(tp)]['goods'][str(goods_id)]
        except KeyError:
            raise GameException(
                ConfigErrorMessage.get_error_id("INVALID_OPERATE"))

        if data['times'] >= config.times_limit:
            raise GameException(
                ConfigErrorMessage.get_error_id("STORE_GOODS_NO_TIMES"))

        if config.condition_id == 1:
            # VIP 等级
            VIP(self.server_id, self.char_id).check(config.condition_value)
        elif config.condition_id == 2:
            # 爬塔历史最高星
            Tower(self.server_id,
                  self.char_id).check_history_max_star(config.condition_value)
        elif config.condition_id == 3:
            # 竞技场当前排名
            Arena(self.server_id,
                  self.char_id).check_current_rank(config.condition_value)
        elif config.condition_id == 4:
            # 当前公会等级
            Union(self.server_id,
                  self.char_id).check_level(config.condition_value)

        item_id, item_amount, need_id, need_amount = config.content[
            data['index']]
        resource_classify = ResourceClassification.classify([(need_id,
                                                              need_amount)])
        resource_classify.check_exist(self.server_id, self.char_id)
        resource_classify.remove(self.server_id,
                                 self.char_id,
                                 message="Store.buy:{0}".format(goods_id))

        resource_classify = ResourceClassification.classify([(item_id,
                                                              item_amount)])
        resource_classify.add(self.server_id,
                              self.char_id,
                              message="Store.buy:{0}".format(goods_id))

        data['times'] += 1

        MongoStore.db(self.server_id).update_one({'_id': self.char_id}, {
            '$set': {
                'tp.{0}.goods.{1}.times'.format(tp, goods_id): data['times']
            }
        })

        self.send_notify(tp=tp)
        return resource_classify