Esempio n. 1
0
 def friend_invite_list(self, msgtype, body):
     p = self.player
     if not p.factionID:
         return success_msg(msgtype, "")
     req = poem_pb.InviteFriendList()
     req.ParseFromString(body)
     logger.debug(req)
     try:
         ownerID, fbID = simple_load_friendfb(req.friendfbID, 'ownerID',
                                              'fbID')
     except DoesNotExistsException:
         return fail_msg(msgtype,
                         msgTips.FAIL_MSG_FRIENDFB_ALREADY_DISAPPEARED)
     if p.entityID != ownerID:
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     invitees = load_friendfb_invitees(req.friendfbID)
     # invitees 起码会有发现者
     assert invitees, "impossible"
     fields = ['entityID', 'name', 'prototypeID', 'level', "borderID"]
     #  过滤已经邀请的好友(2016-02-18 改会公会成员)
     f = Faction.simple_load(p.factionID, ["memberset"])
     rs = Player.batch_load(list(set(f.memberset) - invitees), fields)
     rsp = poem_pb.InviteFriendListResponse()
     config = get_config(FriendfbConfig)[fbID]
     for each in rs:
         info = {}
         if each.level < config.openlv:
             continue
         for f in fields:
             info[f] = getattr(each, f)
         info['id'] = info['entityID']
         rsp.friends.add(**info)
     return success_msg(msgtype, rsp)
Esempio n. 2
0
    def user_out(self, msgtype, body):
        req = rainbow_pb.KickOutRequest()
        req.ParseFromString(body)

        room_obj = g_roomManager.get_room(self.player.room_id)
        if not room_obj:
            return fail_msg(msgtype, msgTips.FAIL_MSG_ROOM_NOT_EXIST)

        if room_obj.master_entity_id != self.player.entityID:
            return fail_msg(msgtype, msgTips.FAIL_MSG_ROOM_KICK_OUT_PERMISSION_DENY)

        rsp_user_kick_out = rainbow_pb.UserKickOut()
        rsp_user_kick_out.kick_out_id = req.kick_out_id
        msg = success_msg(msgid.ROOM_USER_BEEN_KICK_OUT, rsp_user_kick_out)
        for role in room_obj.roles:
            if role.entityID == 0:
                continue

            p = g_entityManager.get_player(role.entityID)
            if p:
                if p.entityID == req.kick_out_id:
                    p.room_id = 0
                    p.pos_index = 0
                    p.save()
                g_playerManager.sendto(role.entityID, msg)

            if role.entityID == req.kick_out_id:
                role.entityID = 0
                role.username = ''

        return success_msg(msgtype, '')
Esempio n. 3
0
 def login(self, msgtype, body):
     limited, message = self.access_limited()
     if limited:
         return fail_msg(msgtype, reason=message)
     req = poem_pb.LoginWorldRequest()
     req.ParseFromString(body)
     if not req.verify_code:
         logger.error(
             'invalid verify_code %s, body %r', req.verify_code, body)
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     session = SessionStore(get_session_pool(), str(req.verify_code))
     if not req.userID or session.uid != req.userID:
         return fail_msg(msgtype, reason="登录超时,请重试")
     self.userID = req.userID
     # get role list
     user = User.load(self.userID)
     rsp = poem_pb.LoginWorldResponse()
     entityIDs = user.roles.get(settings.REGION['ID'])
     if not entityIDs:
         return success_msg(msgtype, rsp)
     #  if len(entityIDs) == 1:
     #      entityID = entityIDs[0]
     #  else:
     #      entityID = req.entityID
     if not req.entityID:
         entityID = min(entityIDs)
     else:
         entityID = req.entityID
     rsp.roles.add(id=entityID)
     rsp.need_rename = PlayerDuplicateNamesIndexing.exists(entityID)
     logger.debug(rsp)
     return success_msg(msgtype, rsp)
Esempio n. 4
0
    def send_message(self, msgtype, body):
        req = poem_pb.SendMessageRequest()
        req.ParseFromString(body)
        p = self.player
        if not g_chatManager.check_limited((p.entityID, req.type)):
            return fail_msg(msgtype,
                            msgTips.FAIL_MSG_CHAT_SPEAK_TOO_FREQUENTLY)
        if req.type == ChatType.Faction:
            if not p.factionID:
                return fail_msg(msgtype, reason="未加入公会")
        if req.type == ChatType.Group:
            if not p.groupID:
                return fail_msg(msgtype, reason="未加入同门")
        content = trie.trie_replace(dirty_words_trie, req.content, u'*')
        assert req.type in (ChatType.World, ChatType.Faction, ChatType.Group)

        if p.chat_blocked:
            m = Message(type=req.type,
                        content=content,
                        name=p.name,
                        entityID=p.entityID,
                        prototypeID=p.prototypeID,
                        is_faction_leader=p.faction_is_leader)
            return success_msg(msgid.RECV_MESSAGE, m)

        g_chatManager.send(req.type,
                           content,
                           p.name,
                           p.entityID,
                           prototypeID=p.prototypeID,
                           is_faction_leader=p.faction_is_leader,
                           borderID=p.borderID)
        return success_msg(msgtype, '')
Esempio n. 5
0
    def user_back(self, msgtype, body):
        room_obj = g_gameManager.get_room(self.player.room_id)

        rsp_user_offline = rainbow_pb.UserOffline()
        rsp_user_offline.entityID = self.player.entityID
        rsp_user_offline.offline = False
        msg = success_msg(msgid.ROOM_USER_OFFLINE, rsp_user_offline)
        for role in room_obj.roles:
            if not role['offline']:
                g_playerManager.sendto(role['entityID'], msg)

        role = room_obj.get_role(self.player.entityID)
        role.offline = False

        rsp = rainbow_pb.JoinRoomResponse()
        rsp.room_id = room_obj.room_id
        rsp.master_id = room_obj.master_entity_id
        rsp.master_server_index = room_obj.master_server_index
        rsp.game_id = room_obj.game_id
        rsp.game_settings = room_obj.game_settings
        rsp.play_count = room_obj.play_count
        rsp.min_player_count = room_obj.game_config['min_player_count']
        rsp.max_player_count = room_obj.game_config['max_player_count']
        for role in room_obj.roles:
            rsp.users.add(**role)
        return success_msg(msgtype, '')
Esempio n. 6
0
    def join_room(self, msgtype, body):
        req = rainbow_pb.JoinRoomRequest()
        req.ParseFromString(body)

        room_obj = g_roomManager.get_room(req.room_id)
        if not room_obj:
            return fail_msg(msgtype, msgTips.FAIL_MSG_ROOM_NOT_EXIST)

        if room_obj.max_count <= len(room_obj.roles):
            return fail_msg(msgtype, msgTips.FAIL_MSG_ROOM_LIMIT_EXCEED)

        # 
        rsp_user_info = rainbow_pb.UserInfo()
        rsp_user_info.entityID = self.player.entityID
        rsp_user_info.username = self.player.username
        rsp_user_info.sex = self.player.sex
        rsp_user_info.offline = False
        g_playerManager.broadcast(room_obj.roles, success_msg(msgid.ROOM_USER_IN, rsp_user_info))

        # 
        pos_index = -1
        for index, role in enumerate(room_obj.roles):
            if role.entityID == 0:
                role.entityID = self.player.entityID
                role.username = self.player.username
                role.sex = self.player.sex
                role.offline = False

                pos_index = index

        if pos_index == -1:
            pos_index = len(room_obj.roles)

            room_obj.roles.append({
                'entityID': self.player.entityID,
                'username': self.player.username,
                'sex': self.player.sex,
                'offline': False,
                })

        self.player.room_id = req.room_id
        self.player.pos_index = pos_index
        self.player.save()
        self.player.sync()

        rsp = rainbow_pb.JoinRoomResponse()
        rsp.room_id = room_obj.id
        rsp.master_id = room_obj.master_entity_id
        rsp.server_index = self.player.pos_index
        for role in room_obj.roles:
            rsp.users.add(**role)
        return success_msg(msgtype, rsp)
Esempio n. 7
0
    def user_leave(self, msgtype, body):
        room_obj = g_gameManager.get_room(self.player.room_id)
        role = room_obj.get_role(self.player.entityID)
        role['offline'] = True

        rsp_user_offline = rainbow_pb.UserOffline()
        rsp_user_offline.entityID = self.player.entityID
        rsp_user_offline.offline = True
        msg = success_msg(msgid.ROOM_USER_OFFLINE, rsp_user_offline)
        for role in room_obj.roles:
            if not role['offline']:
                g_playerManager.sendto(role['entityID'], msg)

        return success_msg(msgtype, '')
Esempio n. 8
0
 def dlc_dispatch(self, msgtype, body):
     p = self.player
     req = poem_pb.DlcDispatchRequest()
     req.ParseFromString(body)
     # 检查关卡开启
     if not validate_prevs(p, req.fbID):
         return fail_msg(msgtype, reason="前置未通")
     if not validate_dlc_fb(p, req.fbID):
         return fail_msg(msgtype, reason="此关已通")
     # 校验精灵
     if not validate_start(p, req.fbID, req.pets):
         return fail_msg(msgtype, reason="精灵校验失败")
     pets = []
     now = int(time.time())
     for pp in req.pets:
         if pp:
             pet = p.pets.get(pp)
             if not pet or max(pet.dispatched - now, 0):
                 return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
             pets.append(pet)
     config = get_config(DlcFbInfoConfig)[req.fbID]
     for pet in pets:
         pet.dispatched = now + config.cd
         pet.save()
         pet.sync()
     p.dlc_dispatch[req.fbID] = {"pets": req.pets, "time": now + config.cd}
     dd = dict(p.dlc_dispatch[req.fbID])
     dd["cd"] = max(dd["time"] - now, 0)
     rsp = poem_pb.DlcDispatchInfo(**dd)
     p.save()
     p.sync()
     return success_msg(msgtype, rsp)
Esempio n. 9
0
 def friend_list(self, msgtype, body):
     p = self.player
     # 推荐好友
     if p.friend_count < p.friend_max_count:
         recommend(p.entityID)
     rsp = poem_pb.FriendList()
     fields = [
         'entityID', 'name', 'prototypeID', 'level', 'credits', 'lastlogin',
         "groupID", "borderID"
     ]
     rs = Player.batch_load(list(p.friendset), fields)
     for each in rs:
         info = {}
         for f in fields:
             info[f] = getattr(each, f)
         info['id'] = info['entityID']
         if info['lastlogin']:
             info['time'] = time.mktime(info['lastlogin'].timetuple())
         else:
             info['time'] = 0
         info['gifted'] = info['id'] in p.friendgiftedset
         info['vip'] = get_vip(info['credits'] or 0)
         info["messages_count"] = len(
             p.friend_messages.get(info['entityID'], []))
         rsp.friends.add(**info)
     logger.debug(rsp)
     return success_msg(msgtype, rsp)
Esempio n. 10
0
    def create_room(self, msgtype, body):
        req = rainbow_pb.CreateRoomRequest()
        req.ParseFromString(body)

        room_obj = g_gameManager.create_room(self.player, req.game_id,
                                             req.game_settings)

        self.player.room_id = room_obj.room_id
        self.player.save()
        self.player.sync()

        rsp = rainbow_pb.JoinRoomResponse()
        rsp.room_id = room_obj.room_id
        rsp.master_id = room_obj.master_entity_id
        rsp.master_server_index = room_obj.master_server_index
        rsp.server_index = 0
        rsp.game_id = room_obj.game_id
        rsp.game_settings = room_obj.game_settings
        rsp.play_count = room_obj.play_count
        rsp.min_player_count = room_obj.game_config['min_player_count']
        rsp.max_player_count = room_obj.game_config['max_player_count']
        for index, role in enumerate(room_obj.roles):
            if role['entityID'] != 0:
                rsp.users.add(**role)
        return success_msg(msgtype, rsp)
Esempio n. 11
0
    def user_out(self, msgtype, body):
        req = rainbow_pb.KickOutRequest()
        req.ParseFromString(body)

        room_obj = g_gameManager.get_room(self.player.room_id)
        if room_obj.master_entity_id != self.player.entityID:
            return fail_msg(msgtype,
                            msgTips.FAIL_MSG_ROOM_KICK_OUT_PERMISSION_DENY)

        rsp = rainbow_pb.KickOutResponse()
        rsp.kick_out_id = req.kick_out_id
        msg = success_msg(msgtype, rsp)
        for role in room_obj.roles:
            if role['entityID'] == 0:
                continue

            p = g_entityManager.get_player(role['entityID'])
            if p:
                # 如果就是这个玩家被踢的话,清空一下数据
                if p.entityID == req.kick_out_id:
                    p.room_id = 0
                    p.save()
                    p.sync()

                # 发送踢人的消息
                if role['entityID'] != self.player.entityID:
                    g_playerManager.sendto(role['entityID'], msg)

            # 把这个位置空出来
            if role['entityID'] == req.kick_out_id:
                role['entityID'] = 0
                role['username'] = ''

        return msg
Esempio n. 12
0
 def maze_case_recv(self, msgtype, body):
     p = self.player
     req = poem_pb.MazeEventRequest()
     req.ParseFromString(body)
     index = req.index or 0
     try:
         event = p.mazes[index]
     except IndexError:
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     count = 1
     cost = {}
     if req.treble:
         count = 3
         cost = {"gold": p.maze_case_cost}
     if event.get("type") != MazeEventType.Case:
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     drop = event.get("argv", 0)
     drops = [drop] * count
     if drop:
         reward = open_reward(RewardType.MazeDrop, *drops)
     if cost:
         reward.cost_after(p, **cost)
     result = reward.apply(p)
     p.mazes.remove(event)
     p.touch_mazes()
     p.save()
     p.sync()
     rsp = poem_pb.MazeCaseResponse()
     build_reward_msg(rsp, result)
     return success_msg(msgtype, rsp)
Esempio n. 13
0
 def visit_visit(self, msgtype, body):
     p = self.player
     req = poem_pb.VisitRequest()
     req.ParseFromString(body)
     cost = {}
     count = 1
     if req.onekey:
         count = 10
     gain, cost, ids, luck = visit(p, count)
     try:
         apply_reward(p, gain, cost=cost, type=RewardType.Visit)
     except AttrNotEnoughError:
         incr_visit_flag(count=-count)
         return fail_msg(msgtype, reason="钻石不足")
     if p.visit_free_rest_count < count:
         p.visit_free_used_count += p.visit_free_rest_count
         count -= p.visit_free_rest_count
     else:
         p.visit_free_used_count += count
         count = 0
     p.visit_today_used_count += count
     rsp = poem_pb.VisitResponse(ids=ids)
     if luck:
         rsp.rewards = build_reward(luck)
     campaign = g_campaignManager.visit_campaign
     if campaign.is_open():
         config = campaign.get_current()
         p.visit_group = config.reward_group
     p.visit_time = int(time.time())
     p.save()
     p.sync()
     from chat.manager import on_visit
     on_visit(p, rsp.rewards)
     return success_msg(msgtype, rsp)
Esempio n. 14
0
 def reborn(self, msgtype, body):
     p = self.player
     cost = get_cons_value("DailyRebornCost")
     # if not g_campaignManager.dailypvp_campaign.is_open():
     #     return fail_msg(msgtype, msgTips.FAIL_MSG_DAILY_CAMPAIGN_CLOSED)
     try:
         apply_reward(
             p, {}, cost={"gold": cost}, type=RewardType.DailyPVPReborn)
     except AttrNotEnoughError:
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     changeds = set()
     lineups = [
         p.lineups.get(LineupType.Daily, []),
         p.lineups.get(LineupType.City, []),
     ]
     for lineup in lineups:
         for each in lineup:
             pet = p.pets.get(each)
             if pet:
                 pet.daily_dead = False
                 pet.daily_restHP = 0
                 changeds.add(pet)
     for pet in changeds:
         pet.save()
         pet.sync()
     p.daily_dead_cd = 0
     p.save()
     p.sync()
     return success_msg(msgtype, "")
Esempio n. 15
0
    def enchant(self, msgtype, body):
        p = self.player
        req = EnchantEquip()
        req.ParseFromString(body)
        need = pow(2, len(req.locks))
        enchant_free_used_count = 0
        if req.ex:
            need *= get_cons_value("EnchantExCostBase")
        else:
            if p.enchant_free_rest_count:
                need = 0
                enchant_free_used_count = 1

            else:
                need *= get_cons_value("EnchantCostBase")
        if need:
            if p.stone < need:
                gold = (need - p.stone) * get_cons_value("EnchantStoneToGold")
                cost = {"stone": p.stone, "gold": gold}
            else:
                cost = {"stone": need}
            try:
                apply_reward(p, {}, cost=cost, type=RewardType.EnchantEquip)
            except (AttrNotEnoughError, MatNotEnoughError):
                return fail_msg(msgtype, reason="消耗不足")
        enchant_equip(p, req.equipID, locks=req.locks, ex=req.ex)
        p.enchant_free_used_count += enchant_free_used_count
        p.save()
        p.sync()
        return success_msg(msgtype, "")
Esempio n. 16
0
 def friend_applys(self, msgtype, body):
     p = self.player
     rsp = poem_pb.ApplysList()
     applys = p.friend_applys or {}
     fields = [
         'entityID', 'name', 'prototypeID', 'level', 'credits', "borderID"
     ]
     now = int(time.time())
     pending = []
     rs = Player.batch_load(applys.keys(), fields)
     for each in rs:
         info = {}
         applytime = applys.get(each.entityID, {}).get('applytime', 0)
         if applytime and now > applytime + FRIEND_APPLY_CD:
             pending.append(each.entityID)
             continue
         for f in fields:
             info[f] = getattr(each, f)
         info['id'] = info['entityID']
         info['time'] = applytime
         info['vip'] = get_vip(info['credits'] or 0)
         rsp.applys.add(**info)
     if pending:
         for i in pending:
             del p.friend_applys[i]
         p.save()
         p.sync()
     logger.debug(rsp)
     return success_msg(msgtype, rsp)
Esempio n. 17
0
 def flowerboss_friendfb_reborn(self, msgtype, body):
     req = poem_pb.RebornFriendfb()
     req.ParseFromString(body)
     p = self.player
     try:
         hp, fbID = simple_load_friendfb(req.friendfbID, 'hp', 'fbID')
     except DoesNotExistsException:
         return fail_msg(msgtype,
                         msgTips.FAIL_MSG_FRIENDFB_ALREADY_DISAPPEARED)
     if hp <= 0:
         return fail_msg(msgtype, reason='BOSS已经被击杀了')
     if not player_is_dead(p, req.friendfbID):
         return fail_msg(msgtype, reason="无须复活")
     count = p.friendfb_reborn_counts[req.friendfbID] =\
         p.friendfb_reborn_counts.get(req.friendfbID, 0) + 1
     cost = get_cons_value("FlowerBossRebornCost") * count
     try:
         apply_reward(p, {},
                      cost={"gold": cost},
                      type=RewardType.FriendfbReborn)
     except AttrNotEnoughError:
         return fail_msg(msgtype, reason="钻石不足")
     p.friendfb_deads.remove(req.friendfbID)
     if fbID in p.friendfb_deadtimes:
         del p.friendfb_deadtimes[fbID]
     p.friendfb_buff = get_cons_value("GveBuffAddition")
     p.save()
     p.sync()
     return success_msg(msgtype, "")
Esempio n. 18
0
 def dlc_dispatch_end(self, msgtype, body):
     p = self.player
     req = poem_pb.DlcDispatchEndRequest()
     req.ParseFromString(body)
     # 检查关卡开启
     if not validate_prevs(p, req.fbID):
         return fail_msg(msgtype, reason="前置未通")
     if not validate_dlc_fb(p, req.fbID):
         return fail_msg(msgtype, reason="此关已通")
     dispatch = p.dlc_dispatch.get(req.fbID)
     if not dispatch:
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     now = int(time.time())
     if now < dispatch["time"]:
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     reward = apply_dlc_reward(req.fbID, isfirst=is_first(p, req.fbID))
     apply_reward(p, reward, type=RewardType.DlcDispatch)
     set_dlc_progress(p, req.fbID)
     set_fb_score(p, req.fbID, 1)   # FIXME
     from task.manager import on_end_dlc_fb
     from task.manager import on_dlc_score
     from task.manager import on_end_spec_fb_count
     from task.manager import on_end_fb_count
     on_end_spec_fb_count(p, req.fbID)
     on_end_fb_count(p, req.fbID)
     on_end_dlc_fb(p, req.fbID)
     on_dlc_score(p)
     p.save()
     p.sync()
     rsp = poem_pb.DlcDispatchEnd()
     build_reward_msg(rsp, reward)
     return success_msg(msgtype, rsp)
Esempio n. 19
0
 def dlc_done_task(self, msgtype, body):
     p = self.player
     today = datedate.today()
     req = poem_pb.DlcTaskDoneRequest()
     req.ParseFromString(body)
     # logger.debug(req)
     dlc_task = get_config(DlcTaskConfig).get(req.taskID)
     if not dlc_task:
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     campaign = g_dlcCampaignManager.campaigns.get(dlc_task.dlcID)
     if not campaign or not campaign.is_open() or\
             is_done(p, req.taskID, today):
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     now = int(time.time())
     cd = p.dlc_tasks_cd.get(dlc_task.dlcID, 0)
     if max(cd - now, 0):
         return fail_msg(msgtype, reason="cd中")
     try:
         apply_reward(
             p, {}, cost={"gold": dlc_task.gold},
             type=RewardType.DlcDoneTask)
     except AttrNotEnoughError:
         return fail_msg(msgtype, msgTips.FAIL_MSG_INVALID_REQUEST)
     done_task(p, req.taskID, today)
     from task.manager import on_dlc_score
     on_dlc_score(p)
     p.save()
     p.sync()
     return success_msg(msgtype, '')
Esempio n. 20
0
 def tap_start(self, msgtype, body):
     p = self.player
     start_tap(p)
     m = get_config(TapMonsterConfig)[p.tap_monster]
     rsp = poem_pb.StartTapResponse(**m._asdict())
     rsp.index = p.tap_hurts_index
     # from: [1, 1, 1, 10, 10, 1, 1, 10, 1]
     # to  : [[1, 3], [10, 2], [1, 2], [10, 1], [1, 1]]
     prev = None
     result = []
     for i in p.tap_hurts:
         if prev is not None:
             if i == prev:
                 result[-1][1] += 1
             else:
                 result.append([i, 1])
         else:
             result.append([i, 1])
         prev = i
     for hurt, repeat in result:
         rsp.hurts.append(hurt)
         rsp.repeats.append(repeat)
     logger.debug("tap start")
     logger.debug(rsp)
     return success_msg(msgtype, rsp)
Esempio n. 21
0
 def maze_events(self, msgtype, body):
     p = self.player
     rsp = poem_pb.MazeEvents()
     now = int(time.time())
     pending = []
     event_exists = set()
     events = []
     flag = False
     for maze in p.mazes[::-1]:
         cd = max(maze["time"] - now, 0)
         if cd == 0:
             flag = True
             pending.append(maze)
             continue
         if maze["type"] == MazeEventType.Shop:
             if (maze["type"], maze["argv"]) in event_exists:
                 flag = True
                 pending.append(maze)
                 continue
             else:
                 event_exists.add((maze["type"], maze["argv"]))
         events.insert(0, dict(cd=cd, **maze))
     rsp.events = events
     for each in pending:
         p.mazes.remove(each)
     if flag:
         p.touch_mazes()
         p.save()
         p.sync()
     return success_msg(msgtype, rsp)
Esempio n. 22
0
 def trigger_fb_info(self, msgtype, body):
     p = self.player
     if not check_trigger_event_type(p, EventType.Fb):
         return fail_msg(msgtype, reason="无触发事件或错误的事件类型")
     config = get_config(TriggerEventConfig)[p.trigger_event]
     rsp = poem_pb.TriggerFbInfo(fbID=config.event_param)
     return success_msg(msgtype, rsp)
Esempio n. 23
0
 def trigger_chest_recv(self, msgtype, body):
     p = self.player
     if not check_trigger_event_type(p, EventType.Chest):
         return fail_msg(msgtype, reason="无触发事件或错误的事件类型")
     req = poem_pb.TriggerChestRecvRequest()
     req.ParseFromString(body)
     config = get_config(TriggerEventConfig)[p.trigger_event]
     chest = get_config(TriggerChestConfig).get(config.event_param)
     if not chest:
         return fail_msg(msgtype, reason="不存在的宝箱")
     if req.is_double:
         cost = {"gold": get_cons_value("TriggerChestDoubleCost")}
         gain = {}
         for i in range(get_cons_value("TriggerChestMultiple")):
             gain = combine_reward([chest.reward], [], data=gain)
     else:
         cost = {}
         gain = parse_reward([chest.reward])
     try:
         apply_reward(p, gain, cost=cost, type=RewardType.TriggerChest)
     except AttrNotEnoughError:
         return fail_msg(msgtype, reason="钻石不足")
     p.trigger_event = 0
     p.save()
     p.sync()
     rsp = poem_pb.TriggerChestRecv()
     build_reward_msg(rsp, gain)
     return success_msg(msgtype, rsp)
Esempio n. 24
0
 def trigger_chests_recv(self, msgtype, body):
     p = self.player
     if not check_trigger_event_type(p, EventType.Chests):
         return fail_msg(msgtype, reason="无触发事件或错误的事件类型")
     config = get_config(TriggerEventConfig)[p.trigger_event]
     chest = get_config(TriggerChestsConfig).get(config.event_param)
     if len(p.trigger_chests) > 0:
         cost = {"gold": get_cons_value("TriggerChestsMoreCost")}
     else:
         cost = {}
     rests = set(range(len(chest.rewards))) - p.trigger_chests
     if not rests:
         return fail_msg(msgtype, reason="已经没有宝箱了")
     index = choice_one(list(rests))
     is_best = False
     if index == 0:
         p.trigger_event = 0
         is_best = True
     gain = parse_reward([chest.rewards[index]])
     try:
         apply_reward(p, gain, cost=cost, type=RewardType.TriggerChests)
     except AttrNotEnoughError:
         return fail_msg(msgtype, reason="钻石不足")
     p.trigger_chests.add(index)
     p.save()
     p.sync()
     rsp = poem_pb.TriggerChestsRecv(is_best=is_best)
     build_reward_msg(rsp, gain)
     return success_msg(msgtype, rsp)
Esempio n. 25
0
    def user_ready(self, msgtype, body):
        room_obj = g_gameManager.get_room(self.player.room_id)

        req = rainbow_pb.UserReadyRequest()
        req.ParseFromString(body)

        role = room_obj.get_role(self.player.entityID)
        role['is_ready'] = req.is_ready

        # 判断是否所有玩家都准备就绪了,如果是的话,就开始游戏吧
        is_all_ready = True
        for role in RoleIterator(room_obj):
            if not role['is_ready']:
                is_all_ready = False

        if is_all_ready:
            room_obj.game_start()

        rsp = rainbow_pb.UserReadyResponse()
        rsp.pos_index = role['pos_index']
        rsp.is_ready = req.is_ready
        msg = success_msg(msgtype, rsp)

        room_obj.broadcast(self.player.entityID, msg)
        return msg
Esempio n. 26
0
 def friend_gift(self, msgtype, body):
     p = self.player
     req = poem_pb.GiftFriend()
     req.ParseFromString(body)
     logger.debug(req)
     count = len(req.ids)
     if p.friend_gift_used_count + count > p.friend_gift_max_count:
         return fail_msg(msgtype, reason="次数不足,无法赠送能量")
     for i in req.ids:
         if i not in p.friendset:
             return fail_msg(msgtype, reason="该玩家还不是你的好友")
         if i in p.friendgiftedset:
             return fail_msg(msgtype, reason="已经给该玩家赠送过能量")
     sp = 1
     money = 1000
     rewards = {"sp": sp, "money": money}
     for i in req.ids:
         proxy.gift_friend(i, p.name, rewards)
         p.friend_gift_used_count += 1
         p.friendgiftedset.add(i)
     self_rewards = {"sp": sp * count, "money": money * count}
     apply_reward(p, self_rewards, type=RewardType.GiftFriend)
     p.save()
     p.sync()
     rsp = poem_pb.GiftFriendResponse(ids=req.ids)
     build_reward_msg(rsp, self_rewards)
     return success_msg(msgtype, rsp)
Esempio n. 27
0
 def giftkey(self, msgtype, body):
     from protocol.poem_pb import Giftkey, GiftkeyResponse
     from config.configs import get_config, GiftkeyConfig
     from reward.manager import open_reward, build_reward_msg, RewardType
     from giftkey import use_key, InvalidGiftkeyError, ExceedUseCountError, ExceedDeallineError
     player = self.player
     req = Giftkey()
     req.ParseFromString(body)
     try:
         giftID = use_key(player, req.key)
     except InvalidGiftkeyError:
         return fail_msg(msgtype, reason='无效的兑换码')
     except ExceedUseCountError:
         return fail_msg(msgtype, reason='已经达到最大兑换次数了')
     except ExceedDeallineError:
         return fail_msg(msgtype, reason='已经超过有效期了')
     gift = get_config(GiftkeyConfig)[giftID]
     reward = open_reward(RewardType.Giftkey, gift)
     result = reward.apply(player)
     player.save()
     player.sync()
     rsp = GiftkeyResponse()
     build_reward_msg(rsp, result)
     gm_logger.info(
         {'giftkey': {
             'entityID': player.entityID,
             'giftkey': req.key
         }})
     return success_msg(msgtype, rsp)
Esempio n. 28
0
 def dlc_helper_list(self, msgtype, body):
     p = self.player
     req = poem_pb.DlcHelperListRequest()
     req.ParseFromString(body)
     now = int(time.time())
     if req.social == 1:  # friend
         helpers = list(p.friendset)
     else:
         if not p.factionID:
             helpers = []
         else:
             f = Faction.simple_load(p.factionID, ["memberset"])
             helpers = list(f.memberset)
             try:
                 helpers.remove(p.entityID)
             except ValueError:
                 pass
         if req.social == 3:  # both
             helpers += list(p.friendset)
             helpers = list(set(helpers))
     rsp = poem_pb.DlcHelperList()
     details = []
     for helper in helpers:
         detail = get_opponent_detail(helper)
         last = int(time.mktime(
             detail['lastlogin'].timetuple()
         ))
         detail['time'] = now - last
         detail["dlc_cd"] = get_helper_cd(p, helper, now=now)
         details.append(detail)
     update_onlines(details)
     rsp.helpers = details
     return success_msg(msgtype, rsp)
Esempio n. 29
0
 def trigger_store_buy(self, msgtype, body):
     p = self.player
     if not check_trigger_event_type(p, EventType.Store):
         return fail_msg(msgtype, reason="无触发事件或错误的事件类型")
     config = get_config(TriggerEventConfig)[p.trigger_event]
     goods = get_config(TriggerStoreConfig).get(config.event_param)
     if not goods:
         return fail_msg(msgtype, reason="没有这个商品")
     cost = parse_reward([{
         'count': goods.discount_price,
         'type': goods.discount_price_type}])
     gain = parse_reward([goods.reward])
     try:
         apply_reward(p, gain, cost=cost, type=RewardType.TriggerStore)
     except AttrNotEnoughError as e:
         if e.attr == "gold":
             return fail_msg(msgtype, reason="钻石不足")
         elif e.attr == "money":
             return fail_msg(msgtype, reason="金币不足")
         else:
             return fail_msg(msgtype, reason="消耗不足")
     p.trigger_event = 0
     p.save()
     p.sync()
     return success_msg(msgtype, "")
Esempio n. 30
0
 def friend_friendfb_detail(self, msgtype, body):
     p = self.player
     req = poem_pb.FriendfbDetailRequest()
     req.ParseFromString(body)
     rsp = poem_pb.FriendfbDetail()
     friendfb = load_friendfb(req.friendfbID)
     logger.debug("detail %r", friendfb)
     if not friendfb:
         return fail_msg(msgtype,
                         msgTips.FAIL_MSG_FRIENDFB_ALREADY_DISAPPEARED)
     config = get_config(FriendfbConfig)[friendfb['fbID']]
     friendfb.update(**config._asdict())
     if p.entityID in friendfb['activists']:
         friendfb['done'] = True
     rsp.friendfb = poem_pb.Friendfb(**friendfb)
     rsp.rewards = config.rewards
     #  # 排行榜
     #  ranks = load_ranks(req.friendfbID)
     #  for rank in ranks:
     #      rsp.ranks.add(**rank)
     rsp.is_dead = player_is_dead(p, req.friendfbID)
     rsp.reborn_cost = (p.friendfb_reborn_counts.get(req.friendfbID, 0) +
                        1) * get_cons_value("FriendfbRebornCost")
     logger.debug(rsp)
     return success_msg(msgtype, rsp)