Пример #1
0
    def _do_room__signin(self, msg):
        userId = msg.getParam('userId')
        signinParams = msg.getParam('signinParams', {})
        feeIndex = msg.getParam('feeIndex', 0)
        
        if ftlog.is_debug():
            ftlog.debug('DizhuCtrlRoomGroupMatch._do_room__signin',
                       'roomId=', self.roomId,
                       'userId=', userId,
                       'signinParams=', signinParams,
                       'feeIndex=', feeIndex)

        mp = MsgPack()
        mp.setCmd('m_signin')
        try:
            # 检查禁赛
            res, remains = BanHelper.checkBanValid(userId, self.bigRoomId)
            if res:
                raise MatchBanException(remains)

            self.ensureCanSignInMatch(userId, mp)
            signer = self.match.signin(userId, signinParams, feeIndex)
            clientId = signer.clientId if signer else sessiondata.getClientId(userId)
            finalUserChip = userchip.getChip(userId)
            try:
                sequence = int(self.match.curInst.instId.split('.')[1])
            except:
                sequence = 0
            bireport.reportGameEvent('MATCH_SIGN_UP', userId, DIZHU_GAMEID, self.roomId, 0, sequence, 0,
                                     0, 0, [], clientId, 0, finalUserChip)
        except (MatchException, MatchBanException), e:
            self._handleMatchException(e, userId, mp)
Пример #2
0
    def doRecieveDailyFreeGive(self, gameId, userId, clientId):
        try:
            mo = MsgPack()
            mo.setCmd('daily_free_give')
            mo.setResult('action', 'recieve')
            ret = daily_free_give.receiveDailyFreeGive(userId, gameId)
            if not ret:
                mo.setResult('ok', 0)
                ftlog.info('maybe is script userId =', userId)
                mo.setResult('tip', '领取失败')
                router.sendToUser(mo, userId)
                return

            mo.setResult('deltaChip', ret[1])
            mo.setResult('finalChip', ret[2])
            mo.setResult('freeGiveCountLeft', ret[3])
            mo.setResult('ok', 1)
            router.sendToUser(mo, userId)
            #统计
            bireport.reportGameEvent('SZMJ_DAILY_FREE_GIVE_RECIEVE', userId,
                                     gameId, 0, 0, 0, 0, 0, 0, [], clientId)
        except Exception as e:
            mo = MsgPack()
            mo.setCmd('daily_free_give')
            mo.setResult('action', 'recieve')
            mo.setError(e.errorCode, e.message)
            router.sendToUser(mo, userId)
Пример #3
0
 def doQueryDailyFreeGive(self, gameId, userId, shareId, clientId):
     try:
         mo = MsgPack()
         mo.setCmd('daily_free_give')
         mo.setResult('action', 'query')
         mo.setResult('dailyFreeGive',
                      daily_free_give.queryDailyFreeGive(userId, gameId))
         mo.setResult(
             'todayCheckIn',
             sevendayscheckin.loadStatus(userId, gameId).isTodayCheckined())
         share = hallshare.findShare(shareId)
         if share:
             shareInfo = hallshare.getShareStatus(
                 userId, share, pktimestamp.getCurrentTimestamp())
             mo.setResult('shareRewardCount', shareInfo[1])
         else:
             mo.setResult('shareRewardCount', 0)
         router.sendToUser(mo, userId)
         #统计
         bireport.reportGameEvent('SZMJ_DAILY_FREE_GIVE_QUERY', userId,
                                  gameId, 0, 0, 0, 0, 0, 0, [], clientId)
     except Exception as e:
         mo = MsgPack()
         mo.setCmd('daily_free_give')
         mo.setResult('action', 'query')
         mo.setError(e.errorCode, e.message)
         router.sendToUser(mo, userId)
Пример #4
0
    def _onGameReady(self, event):
        if ftlog.is_debug():
            ftlog.debug('BIReportTable._onGameReady', 'tableId=',
                        event.table.tableId, 'seats=',
                        [(s.userId, s.seatId) for s in event.table.seats])

        userIds = []
        for seat in event.table.seats:
            userIds.append(seat.userId)
            finalTableChip, finalUserChip = comm_table_remote.getUserChips(
                event.table.gameId, seat.userId, event.table.tableId)
            try:
                roomId = event.table.roomId
                # 金币场混房
                if hasattr(seat.player,
                           'mixConf') and seat.player.mixConf.get('roomId'):
                    roomId = seat.player.mixConf.get('roomId')
                # 红包赛混房
                if hasattr(
                        seat.player, 'mixId'
                ) and seat.player.mixId and seat.player.mixId.isdigit():
                    roomId = int(seat.player.mixId)
                bireport.reportGameEvent('TABLE_START', seat.userId,
                                         event.table.gameId, roomId,
                                         event.table.tableId,
                                         event.table.gameRound.roundNum, 0, 0,
                                         0, [], seat.player.clientId,
                                         finalTableChip, finalUserChip)
            except:
                ftlog.error('BIReportTable._onGameReady', 'tableId=',
                            event.table.tableId, 'seat=',
                            (seat.userId, seat.seatId))
Пример #5
0
 def reportEvent(self, event, players, gameId, roomId, tableId, roundId):
     ftlog.info('MTableStatisticLongNet.reportEvent event:', event
             , ' players:', players
             , ' gameId:', gameId
             , ' roomId:', roomId
             , ' tableId:', tableId
             , ' roundId:', roundId
     )
     
     uids = []
     for player in players:
         if player.isRobot():
             continue
         
         uids.append(player.userId)
         bireport.reportGameEvent(event
                 , player.userId
                 , gameId
                 , roomId
                 , tableId
                 , roundId
                 , 0, 0, 0, []
                 , player.clientId)
     
     if event == MTableStatistic.TABLE_START:  
         bireport.tableStart(gameId, roomId, tableId, roundId, uids)
     elif event == MTableStatistic.TABLE_WIN:
         bireport.tableWinLose(gameId, roomId, tableId, roundId, uids)
Пример #6
0
    def get_award(self, uid):
        if not self.checkOperative():
            return 'acitivity expired!'

        actkey = ACTIVITY_KEY.format(HALL_GAMEID, uid, self.getid())
        weekcnt, daycnt = self._get_click_cnt(uid, actkey)
        if weekcnt >= self._clientConf['config'][
                'weeklimit'] or daycnt >= self._clientConf['config'][
                    'daylimit']:
            return 'awardcnt:({},{}) expand limitcnt!'.format(weekcnt, daycnt)

        shareid = self._serverConf["share"]
        share = hallshare.findShare(shareid)
        if not share:
            return 'share:{} not exist!'.format(shareid)

        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_DAY_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_WEEK_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_TOTAL_CNT, 1)
        hallshare.sendReward(HALL_GAMEID, uid, share, 'share_click')
        # 分享BI日志汇报
        clientid = sessiondata.getClientId(uid)
        bireport.reportGameEvent('SHARE_CALLBACK', uid, HALL_GAMEID, shareid,
                                 0, 0, 0, 0, 0, [], clientid)
        if share.mail:
            message.send(HALL_GAMEID, message.MESSAGE_TYPE_SYSTEM, uid,
                         share.mail)
        return 'ok'
Пример #7
0
 def report_bi_game_event(self,
                          eventId,
                          userId,
                          roomId,
                          tableId,
                          roundId,
                          detalChip,
                          state1,
                          state2,
                          cardlist,
                          tag=''):
     try:
         finalUserChip = userchip.getChip(userId)
         finalTableChip = 0
         clientId = sessiondata.getClientId(userId)
         bireport.reportGameEvent(eventId, userId, 6, roomId, tableId,
                                  roundId, detalChip, state1, state2,
                                  cardlist, clientId, finalTableChip,
                                  finalUserChip)
         self._logger.debug('PlayerNotifierDizhu.report_bi_game_event tag=',
                            tag, 'eventId=', eventId, 'userId=', userId,
                            'gameId=', 6, 'roomId=', roomId, 'tableId=',
                            tableId, 'roundId=', roundId)
     except:
         self._logger.error(
             'PlayerNotifierDizhu.report_bi_game_event error tag=', tag,
             'eventId=', eventId, 'userId=', userId, 'gameId=', 6,
             'roomId=', roomId, 'tableId=', tableId, 'roundId=', roundId)
Пример #8
0
    def _onGameRoundOver(self, event):
        if ftlog.is_debug():
            ftlog.debug('BIReportTable._onGameRoundOver', 'tableId=',
                        event.table.tableId, 'seats=',
                        [(s.userId, s.seatId) for s in event.table.seats])

        # userIds = []
        # sfeealls = [event.table.gameId, event.table.roomId, event.table.tableId, [], []]
        # for sst in event.gameResult.seatStatements:
        #     userIds.append(sst.seat.userId)
        #     sfeealls[3].append(sst.feeMulti)
        #     sfeealls[3].append(sst.fee)
        #     sfeealls[4].append(sst.seat.userId)
        #     sfeealls[4].append(sst.delta)
        # bireport.tableRoomFee(event.table.gameId, sfeealls)
        # bireport.tableWinLose(event.table.gameId,
        #                       event.table.roomId,
        #                       event.table.tableId,
        #                       event.gameResult.gameRound.roundId,
        #                       userIds,
        #                       self._complainCodec.encode(self._tableCtrl.replay.curRound))

        for sst in event.gameResult.seatStatements:
            roomId = event.table.roomId
            kickOutCoin = event.table.room.roomConf.get('kickOutCoin', 0)
            if hasattr(sst.seat.player,
                       'mixConf') and sst.seat.player.mixConf.get('roomId'):
                roomId = sst.seat.player.mixConf.get('roomId')
                kickOutCoin = sst.seat.player.mixConf.get('kickOutCoin', 0)

            # 红包赛混房
            if hasattr(
                    sst.seat.player, 'mixId'
            ) and sst.seat.player.mixId and sst.seat.player.mixId.isdigit():
                roomId = int(sst.seat.player.mixId)
            # 房间内破产标志
            userRoomBust = 0
            if kickOutCoin > 0 and int(sst.final) < kickOutCoin:
                userRoomBust = 1
            if ftlog.is_debug():
                ftlog.debug('BIReportTable._onGameRoundOver', 'userId=',
                            sst.seat.userId, 'gameId=', event.table.gameId,
                            'roomId=', roomId, 'tableId=', event.table.tableId,
                            'userRoomBust=', userRoomBust, 'final=',
                            int(sst.final), 'chip=', int(sst.seat.player.chip))

            bireport.reportGameEvent(
                'TABLE_WIN',
                sst.seat.userId,
                event.table.gameId,
                roomId,
                event.table.tableId,
                event.gameResult.gameRound.roundNum,
                sst.delta,
                1 if sst.isPunish else 0,
                0,
                [userRoomBust],  # 房间内破产
                sst.seat.player.clientId,
                int(sst.final),
                int(sst.seat.player.chip))
Пример #9
0
 def report_bi_game_event(self,
                          eventId,
                          userId,
                          roomId,
                          tableId,
                          roundId,
                          detalChip,
                          state1,
                          state2,
                          cardlist,
                          tag=''):
     try:
         clientId = sessiondata.getClientId(userId)
         bireport.reportGameEvent(eventId, userId, 6, roomId, tableId,
                                  roundId, detalChip, state1, state2,
                                  cardlist, clientId, 0, 0)
         ftlog.debug('report_bi_game_event tag=',
                     tag,
                     'eventId=',
                     eventId,
                     'userId=',
                     userId,
                     'gameId=6',
                     'roomId=',
                     roomId,
                     'tableId=',
                     tableId,
                     'roundId=',
                     roundId,
                     caller=self)
     except:
         ftlog.error('report_bi_game_event error tag=', tag, 'eventId=',
                     eventId, 'userId=', userId, 'gameId=6', 'roomId=',
                     roomId, 'tableId=', tableId, 'roundId=', roundId)
Пример #10
0
    def _onTuoguan(self, event):
        isQuit = 0
        if hasattr(event.seat.player, 'isQuit'):
            isQuit = 1 if event.seat.player.isQuit else 0
        if ftlog.is_debug():
            ftlog.debug('BIReportTable._onTuoguan', 'tableId=',
                        event.table.tableId, 'userId=', event.seat.userId,
                        'seatId=', event.seat.seatId, 'isQuit=', isQuit,
                        'oper=', event.oper, 'isTuoguan=', event.isTuoguan,
                        'location=', event.location)
        try:
            roomId = event.table.roomId
            if hasattr(event.seat.player,
                       'mixConf') and event.seat.player.mixConf.get('roomId'):
                roomId = event.seat.player.mixConf.get('roomId')
            # 红包赛混房
            if hasattr(
                    event.seat.player, 'mixId'
            ) and event.seat.player.mixId and event.seat.player.mixId.isdigit(
            ):
                roomId = int(event.seat.player.mixId)

            bireport.reportGameEvent(
                'SEAT_TUOGUAN', event.seat.userId, event.table.gameId, roomId,
                event.table.tableId,
                event.table.gameRound.roundNum if event.table.gameRound else 0,
                0, 1 if event.isTuoguan else 0, event.oper,
                [isQuit, event.location], event.seat.player.clientId, 0, 0)
        except:
            ftlog.error('BIReportTable._onTuoguan', 'tableId=',
                        event.table.tableId, 'userId=', event.seat.userId,
                        'seatId=', event.seat.seatId, 'isQuit=', isQuit,
                        'oper=', event.oper, 'isTuoguan=', event.isTuoguan,
                        'location=', event.location)
Пример #11
0
 def _onSeatOnlineChanged(self, event):
     if ftlog.is_debug():
         ftlog.debug('BIReportTable._onSeatOnlineChanged', 'tableId=',
                     event.table.tableId, 'userId=', event.seat.userId,
                     'seatId=', event.seat.seatId, 'online=',
                     event.seat.player.online)
     try:
         roomId = event.table.roomId
         if hasattr(event.seat.player,
                    'mixConf') and event.seat.player.mixConf.get('roomId'):
             roomId = event.seat.player.mixConf.get('roomId')
         # 红包赛混房
         if hasattr(
                 event.seat.player, 'mixId'
         ) and event.seat.player.mixId and event.seat.player.mixId.isdigit(
         ):
             roomId = int(event.seat.player.mixId)
         bireport.reportGameEvent(
             'SEAT_ONLINE_CHANGED', event.seat.userId, event.table.gameId,
             roomId, event.table.tableId,
             event.table.gameRound.roundNum if event.table.gameRound else 0,
             0, 1 if event.seat.player.online else 2, 0, [],
             event.seat.player.clientId, 0, 0)
     except:
         ftlog.error('BIReportTable._onSeatOnlineChanged', 'tableId=',
                     event.table.tableId, 'userId=', event.seat.userId,
                     'seatId=', event.seat.seatId, 'online=',
                     event.seat.player.online)
Пример #12
0
 def taskEnd(self):
     """
     任务结束
     """
     if ftlog.is_debug():
         ftlog.debug("taskBase_______taskEnd", self.taskId, self.userId, self.taskData["state"])
     beforeState = self.taskData["state"]
     self.clear()
     if beforeState == TaskState.Update:
         isComplete = self._isComplete()
         if isComplete:
             _, rewards = self._receiveTaskReward()
             self.receiveRewards = rewards
             self.taskSystem.saveRedState()  # 保存红包
         else:
             self.taskSystem.taskExpedite = 1
             self.taskData["state"] = TaskState.Fail
             if self.isLimitTime():
                 self.taskData["failTime"] += 1
         from newfish.game import TGFish
         from newfish.entity.event import TableTaskEndEvent
         event = TableTaskEndEvent(self.userId, FISH_GAMEID, self.taskSystem.table.tableId, self.getTaskId(),
                                   isComplete,  self.isLimitTime(), self.receiveRewards)
         TGFish.getEventBus().publishEvent(event)
         # 上传当前完成任务进度
         if self.taskSystem.taskModel == TaskModel.Main and self.taskSystem.isRedRoom():
             ftlog.debug("BI_NFISH_THOUSAND_RED_TASK_PROGRESS--->000", self.getTaskId())
             bireport.reportGameEvent("BI_NFISH_GE_THOUSAND_RED_TASK", self.userId,FISH_GAMEID,
                             self.taskSystem.table.roomId, self.taskSystem.table.tableId,
                             self.getTaskId(), int(isComplete), 0,  0, [], config.CLIENTID_ROBOT)
             # 新手引导步骤完成
             if self.taskConfig["type"] == TaskType.UpgradeLevel:
                 util.addGuideStep(self.player.userId, config.NEWBIE_GUIDE_GUN_UP, self.player.clientId)
     self.sendUserTaskInfo()
Пример #13
0
    def doUserBind_3_3(self, userId, gameId, clientId, isFirstuserInfo):
        # 检查是否禁止登录
        if self.checkForceLogout(userId):
            return
        loc = ''
        isReconnect = False
        if isFirstuserInfo:
            loc = onlinedata.checkUserLoc(userId, clientId, 0)
            self.recoverUserTableChips(userId, clientId)
            isReconnect = self._isReconnect(userId, gameId, clientId, loc)
        # # 更新基本信息
        #         halluser.updateUserBaseInfo(userId, clientId, runcmd.getMsgPack())
        # 登录游戏处理
        isdayfirst, _ = halluser.loginGame(userId, gameId, clientId)
        # 发送udata响应消息
        self.helper.sendUserInfoResponse(userId, gameId, clientId, loc, 1, 0)
        # 发送gdata响应消息
        self.helper.sendUserInfoResponse(userId, gameId, clientId, loc, 0, 1)
        # 发送响应消息
        if not isReconnect:
            self.helper.sendTodoTaskResponse(userId, gameId, clientId,
                                             isdayfirst)
        # 标记游戏时长开始
        gamedata.incrPlayTime(userId, 0, gameId)
        # BI日志统计
        bireport.userBindUser(gameId, userId, clientId)
        bireport.reportGameEvent('BIND_USER', userId, gameId, 0, 0, 0, 0, 0, 0,
                                 [], clientId)

        evt = OnLineGameChangedEvent(userId, gameId, 1, clientId)
        TGHall.getEventBus().publishEvent(evt)
Пример #14
0
    def _do_room__signin(self, msg):
        if ftlog.is_debug():
            ftlog.debug('DizhuErdayiMatchCtrlRoom._do_room__signin', msg)
        userId = msg.getParam('userId')
        signinParams = msg.getParam('signinParams', {})
        feeIndex = msg.getParam('feeIndex', 0)

        if ftlog.is_debug():
            ftlog.debug('DizhuErdayiMatchCtrlRoom._do_room__signin', 'roomId=',
                        self.roomId, 'userId=', userId, 'signinParams=',
                        signinParams, 'feeIndex=', feeIndex)

        try:
            mp = MsgPack()
            mp.setCmd('m_signin')
            self._ensureCanSignInMatch(userId, mp)
            signer = self.match.signin(userId, feeIndex)
            clientId = signer.clientId if signer else sessiondata.getClientId(
                userId)
            finalUserChip = userchip.getChip(userId)
            bireport.reportGameEvent('MATCH_SIGN_UP', userId, DIZHU_GAMEID,
                                     self.roomId, 0, 0, 0, 0, 0, [], clientId,
                                     0, finalUserChip)
        except MatchException, e:
            self._handleMatchException(e, userId, mp)
Пример #15
0
    def doUserBind_3_3(self, userId, gameId, clientId, isFirstuserInfo):
        # 检查是否禁止登录
        if self.checkForceLogout(userId):
            return
        loc = ''
        isReconnect = False
        if isFirstuserInfo:
            loc = onlinedata.checkUserLoc(userId, clientId, 0)
            self.recoverUserTableChips(userId, clientId)
            isReconnect = self._isReconnect(userId, gameId, clientId, loc)
        # # 更新基本信息
        #         halluser.updateUserBaseInfo(userId, clientId, runcmd.getMsgPack())
        # 登录游戏处理
        isdayfirst, _ = halluser.loginGame(userId, gameId, clientId)
        # 发送udata响应消息
        self.helper.sendUserInfoResponse(userId, gameId, clientId, loc, 1, 0)
        # 发送gdata响应消息
        self.helper.sendUserInfoResponse(userId, gameId, clientId, loc, 0, 1)
        # 发送响应消息
        if not isReconnect:
            self.helper.sendTodoTaskResponse(userId, gameId, clientId, isdayfirst)
        # 标记游戏时长开始
        gamedata.incrPlayTime(userId, 0, gameId)
        # BI日志统计
        bireport.userBindUser(gameId, userId, clientId)
        bireport.reportGameEvent('BIND_USER',
                                 userId, gameId, 0, 0, 0, 0, 0, 0, [], clientId)

        evt = OnLineGameChangedEvent(userId, gameId, 1, clientId)
        TGHall.getEventBus().publishEvent(evt)
Пример #16
0
def checkSkillUpgrade(userId):
    """
    检查技能能否升级升星
    """
    upSkills = []
    for skillId in config.getAllSkillId():
        skillId = int(skillId)
        if not config.getSkillStarConf(skillId, 1, config.MULTIPLE_MODE):
            continue
        code, skill = checkSkillStatus(userId, skillId)
        if code != 0:
            continue
        if skill[INDEX_ORIGINAL_LEVEL] < MAX_ORIGINAL_LEVEL:
            skillGradeConf = config.getSkillGradeCommonConf(
                skillId, skill[INDEX_ORIGINAL_LEVEL] + 1)
            if checkUpgradeSkillItemCount(userId, skillGradeConf["consume"]):
                upSkills.append(skillId)
        if skill[INDEX_STAR_LEVEL] > 0 and skill[
                INDEX_STAR_LEVEL] < MAX_STAR_LEVEL:
            skillStarConf = config.getSkillStarCommonConf(
                skillId, skill[INDEX_STAR_LEVEL] + 1)
            if checkUpgradeSkillItemCount(userId, skillStarConf["consume"]):
                upSkills.append(skillId)
        bireport.reportGameEvent(
            "BI_NFISH_GE_SKILL_UPGRADE", userId, FISH_GAMEID, 0, 0, skillId, 0,
            0, 0, [skill[INDEX_STAR_LEVEL], skill[INDEX_ORIGINAL_LEVEL]],
            util.getClientId(userId))
    module_tip.resetModuleTip(userId, "upskill")
    if upSkills:
        module_tip.addModuleTipEvent(userId, "upskill", upSkills)
    else:
        module_tip.resetModuleTipEvent(userId, "upskill")
Пример #17
0
def _publishWinLoseEvent(roomId, tableId, seatUid, roundId, winUserIds,
                         isDizhu, winuserid, seat_delta, detalChipAll,
                         findChips, windoubles, bomb, chuntian, winslam,
                         clientId, topValidCard, skillLevelUp):
    from dizhu.game import TGDizhu
    ebus = TGDizhu.getEventBus()
    hallebus = TGHall.getEventBus()
    isWin = True if seatUid in winUserIds else False
    winlose = Winlose(winuserid, topValidCard, isWin, isDizhu, seat_delta,
                      findChips, windoubles, bomb, chuntian > 1, winslam)
    ebus.publishEvent(
        UserTableWinloseEvent(DIZHU_GAMEID, seatUid, roomId, tableId, winlose,
                              skillLevelUp))

    isWinNum = 0
    if isWin:
        isWinNum = 1
    roomLevel = gdata.roomIdDefineMap()[roomId].configure.get('roomLevel', 1)
    ftlog.debug('hallebus push gameoverevent userId=', seatUid)
    hallebus.publishEvent(
        GameOverEvent(seatUid, DIZHU_GAMEID, clientId, roomId, tableId,
                      isWinNum, roomLevel))

    finalUserChip = userchip.getChip(seatUid)
    finalTableChip = userchip.getTableChip(seatUid, DIZHU_GAMEID, tableId)
    bireport.reportGameEvent('TABLE_WIN', seatUid, DIZHU_GAMEID, roomId,
                             tableId, roundId, detalChipAll, 0, 0, [],
                             clientId, finalTableChip, finalUserChip)
    return finalUserChip
Пример #18
0
def _sendUserBehaviourReward(event):
    userId = event.userId
    behaviourConf = dizhuconf.getUserBehaviourReward()
    if not _checkExpectedUser(userId, behaviourConf):
        return
    try:
        ret = daobase.executeUserCmd(event.userId, 'HGET', 'userBehaviour:6:' + str(event.userId), 'info')
        if ret:
            behaviourInfo = strutil.loads(ret)
            behaviourType = behaviourInfo.get('type', 0)
            clientId = sessiondata.getClientId(event.userId)
            if behaviourType == BEHAVIOUR_TYPE_REWARD:
                _changeUserBehaviourInfo(event.userId, behaviourInfo, behaviourConf)
                reportGameEvent('DIZHU_BEHAVIOUR_GROUP', event.userId, DIZHU_GAMEID, 0, 0, 0, 0, behaviourType, 0, [],
                                clientId)
            elif behaviourType == BEHAVIOUR_TYPE_NOUSE:
                behaviourInfo['type'] = BEHAVIOUR_TYPE_NOUSEED
                behaviourInfo['date'] = int(dizhu_util.calcTodayIssueNum())
                daobase.executeUserCmd(userId, 'HSET', 'userBehaviour:6:' + str(userId), 'info',
                                       strutil.dumps(behaviourInfo))
                reportGameEvent('DIZHU_BEHAVIOUR_GROUP', event.userId, DIZHU_GAMEID, 0, 0, 0, 0, behaviourType, 0, [], clientId)
        #else #这个分支在玩家登陆时处理过了,无对应属性的玩家不处理。
        if ftlog.is_debug():
            ftlog.debug('userBehaviour.setUserData userId=', event.userId, 'ret=', ret)
    except Exception, e:
        ftlog.warn('_sendUserBehaviourReward userId=', userId, 'error=', e)
Пример #19
0
    def endGrandPrix(self):
        """
        大奖赛结束
        """
        if self.userId == 0:
            return

        if self.grandPrixEndTimer:
            self.grandPrixEndTimer.cancel()
            self.grandPrixEndTimer = None

        if not self.isGrandPrixMode():
            return

        grandPrixFinalPoint = self.saveGrandPrixPoint()
        # 完成大奖赛事件
        event = FinishGrandPrixEvent(self.userId, FISH_GAMEID,
                                     self.table.bigRoomId, grandPrixFinalPoint)
        TGFish.getEventBus().publishEvent(event)
        bireport.reportGameEvent("BI_NFISH_GRAND_PRIX_END", self.userId,
                                 FISH_GAMEID, 0, 0, grandPrixFinalPoint, 0, 0,
                                 0, [], util.getClientId(self.userId))
        if self.inGameTimes:
            bireport.reportGameEvent("BI_NFISH_GRAND_PRIX_INGAMETIMES",
                                     self.userId, FISH_GAMEID, 0, 0,
                                     self.grandPrixStartTS, self.inGameTimes,
                                     0, 0, [], util.getClientId(self.userId))
            self.inGameTimes = 0

        self.cancelUsingSkills()  # 恢复技能数据 取消处于使用中的技能
        self.unloadSkills()  # 下载所有技能
        self._resetGrandPrixData()  # 重置数据存档
        self.loadAllSkillData()  # 重新加载技能 读取并初始化所有技能数据
        self.syncSkillSlots()  # 同步技能槽消息
        rank, rankRewards = ranking_system.getUserRankAndRewards(
            RankType.TodayGrandPrix, self.userId)
        if ftlog.is_debug():
            ftlog.debug("endGrandPrix", self.grandPrixStartTS,
                        self.grandPrixFireCount, self.grandPrixFishPoint)
        mo = MsgPack()
        mo.setCmd("end_grand_prix")
        mo.setResult("gameId", FISH_GAMEID)
        mo.setResult("userId", self.userId)
        mo.setResult("seatId", self.seatId)
        mo.setResult("fishPoint", grandPrixFinalPoint)
        mo.setResult("rank", rank)
        mo.setResult("rankRewards", rankRewards)
        mo.setResult("fee", config.getGrandPrixConf("fee"))
        mo.setResult(
            "tabs",
            ranking_system.getRankingTabs(self.userId,
                                          util.getClientId(self.userId),
                                          RankType.TodayGrandPrix,
                                          rankDetail=True))
        GameMsg.sendMsg(mo, self.userId)
        self.sendGrandPrixInfo()
        self.table.clearPlayer(self)  # 从桌子中踢掉玩家
Пример #20
0
    def _sendActiveReward(self, userId, rewardKind, scheduleId):
        # 发奖接口
        if ftlog.is_debug():
            ftlog.debug('ActivityWxUserActive._sendActiveReward userId= ',
                        userId, 'rewardKind= ', rewardKind, 'scheduleId= ',
                        scheduleId)
        actInstance = _getActInstance(userId)
        if actInstance:
            userData, expireDay, expireWeek = UserActiveData(userId).loadData()
            if rewardKind == ActiveRewardItem.DAY:
                reward = actInstance.getDayRewardByScheduleId(scheduleId)
                if not reward:
                    raise ActivityWxException(-6, '您没有获得奖励哦~')
                if expireDay:
                    raise ActivityWxException(-7, '您来晚了哦,明天记得早点领取哦~')
                if scheduleId in userData.activeDataDay.scheduleIdList:
                    raise ActivityWxException(-8, '您已领取奖励哦~')
                if userData.activeDataDay.active < reward.active:
                    raise ActivityWxException(-9, '您的日活跃度不够哦~')

                dizhu_util.sendRewardItems(userId, reward.rewards, None,
                                           'ACTIVE_REWARD', 0)
                bireport.reportGameEvent('ACTIVE_REWARDS', userId,
                                         DIZHU_GAMEID, 0, 0, 0, 0, 0, 0,
                                         [scheduleId],
                                         sessiondata.getClientId(userId))
                userData.addDayScheduleId(scheduleId)
                return {
                    'rewards': TYContentItem.encodeList(reward.rewards),
                    'success': 1
                }
            else:
                reward = actInstance.getWeekRewardByScheduleId(scheduleId)
                if not reward:
                    raise ActivityWxException(-6, '您没有获得奖励哦~')

                if expireWeek:
                    raise ActivityWxException(-7, '您来晚了哦,下周记得早点领取哦~')

                if scheduleId in userData.activeDataWeek.scheduleIdList:
                    raise ActivityWxException(-8, '您已领取奖励哦~')
                if userData.activeDataWeek.active < reward.active:
                    raise ActivityWxException(-9, '您的周活跃度不够哦~')

                dizhu_util.sendRewardItems(userId, reward.rewards, None,
                                           'ACTIVE_REWARD', 0)
                userData.addWeekScheduleId(scheduleId)
                bireport.reportGameEvent('ACTIVE_REWARDS', userId,
                                         DIZHU_GAMEID, 0, 0, 0, 0, 0, 0,
                                         [scheduleId],
                                         sessiondata.getClientId(userId))
                return {
                    'rewards': TYContentItem.encodeList(reward.rewards),
                    'success': 1
                }
        raise ActivityWxException(-10, '活动不存在')
Пример #21
0
 def doGameEnter(self, userId, gameId, clientId):
     isdayfirst, iscreate = halluser.loginGame(userId, gameId, clientId)
     self.helper.sendUserInfoResponse(userId, gameId, clientId, '', 0, 1)
     self.helper.sendTodoTaskResponse(userId, gameId, clientId, isdayfirst)
     # BI日志统计
     bireport.userGameEnter(gameId, userId, clientId)
     bireport.reportGameEvent('BIND_GAME',
                              userId, gameId, 0, 0, 0, 0, 0, 0, [], clientId, iscreate)
     evt = OnLineGameChangedEvent(userId, gameId, 1, clientId)
     TGHall.getEventBus().publishEvent(evt)
Пример #22
0
def getQuestRewards(userId, clientId, taskId):
    """
    领取单个主线任务奖励
    """
    mo = MsgPack()
    mo.setCmd("task")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("taskId", taskId)
    mo.setResult("action", "mainReward")
    code = 3
    taskConf = config.getMainQuestTaskConf(clientId, taskId)
    if taskConf:
        state = getTask(userId, taskId)[QuestIndex.State]
        if state == QuestState.Default:
            code = 2
        elif state == QuestState.Received:
            code = 1
        else:
            code = 0
            chestInfo = {}
            rewards = []
            rewards.extend(taskConf["normalRewards"])
            chestRewards = taskConf["chestRewards"]
            if chestRewards:
                chestId = chestRewards[0]["name"]
                chestInfo = chest_system.getChestInfo(chestId)
                _rewards = chest_system.getChestRewards(userId, chestId)
                rewards.extend(_rewards)
            setTask(
                userId, clientId, taskId,
                [QuestState.Received, int(time.time())])  # 领取任务奖励
            util.addRewards(userId, rewards, "BI_NFISH_MAIN_QUEST_REWARDS",
                            int(taskId))
            module_tip.cancelModuleTipEvent(userId, "mainquest", taskId)
            # 检查主线任务增加的星级能否解锁对应星级奖励.
            sectionId = getSectionId(taskId)
            sectionData = getSection(userId, sectionId)
            sectionConf = config.getMainQuestSectionConf(clientId, sectionId)
            totalStar = _getSectionStar(userId, clientId, sectionId)
            for val in sectionConf["starRewards"]:
                if totalStar >= val["star"] and val["star"] not in sectionData[
                        SectionIndex.TakenStars]:
                    module_tip.addModuleTipEvent(userId, "mainquest",
                                                 "star_%d" % val["star"])
            mo.setResult("chestInfo", chestInfo)  # 宝箱奖励
            mo.setResult("rewards", rewards)
            bireport.reportGameEvent("BI_NFISH_GE_MAIN_QUEST_TASKID", userId,
                                     FISH_GAMEID, 0, 0, 0, 0, 0, 0, [taskId],
                                     clientId)
    mo.setResult("code", code)
    router.sendToUser(mo, userId)
    pushCurrTask(userId)
Пример #23
0
def addPool(userId, gameId, value):
    '''
    增加奖池
    :param userId:
    :param gameId:
    :param count:
    '''
    if not isOpen(gameId):
        return 0
    bireport.reportGameEvent('HALL_LOTTERY_TASK_ADD', userId, gameId, 0, 0, 0,
                             value, 0, 0, [], sessiondata.getClientId(userId))
    return gamedata.incrGameAttr(userId, gameId, "lotterytask_pool", value)
Пример #24
0
 def triggerBankruptEvent(self, bankruptCount):
     """
     玩家破产
     """
     if self.fishPool == 44003:
         if bankruptCount <= 1:
             self.resetOdds()
     bireport.reportGameEvent("BI_NFISH_GE_BANKRUPT", self.player.userId,
                              FISH_GAMEID, self.table.roomId,
                              self.table.tableId, bankruptCount,
                              self.player.level, 0, 0, [],
                              self.player.clientId)
Пример #25
0
def _incQuestValue(userId, taskType, incVlaue, resetTime=0, fishPool=0, fpMultiple=0, gunX=0):
    """
    更新每日任务进度并检测;任务是否完成
    """
    if util.getDayStartTimestamp(resetTime) != util.getDayStartTimestamp(int(time.time())):
        resetTime = weakdata.getDayFishData(userId, "resetTime")
        if not resetTime:
            weakdata.setDayFishData(userId, WeakData.resetTime, int(time.time()))
            refreshDailyQuestData(userId)
    key = _getUserDailyQuestKey(userId)
    newValue = daobase.executeUserCmd(userId, "HINCRBY", key, str(taskType), incVlaue)
    confs = config.getDailyQuestConfsByType(taskType)
    todayQuest, _ = getTodayQuest(userId)
    questInfo = getUserQuestInfoData(userId)
    update = False
    for conf in confs:
        if conf and conf["taskId"] in todayQuest:
            if isinstance(conf.get("fishPool"), list) and conf.get("fishPool") and fishPool not in conf.get("fishPool"):
                continue
            if conf.get("fpMultiple", 0) > 0 and fpMultiple < conf.get("fpMultiple", 0):
                continue
            if conf.get("gunX", 0) > 0 and gunX < conf.get("gunX", 0):
                continue
            taskId = conf["taskId"]
            targetsNum = conf.get("targetsNum")
            process, state = questInfo.get(str(taskId), [0, QuestTaskState.Normal])
            # if newValue >= targetsNum and newValue - incVlaue < targetsNum:
            if state == QuestTaskState.Normal:
                update = True
                questInfo[str(taskId)] = [process + incVlaue, state]
                if process < targetsNum <= process + incVlaue:
                    questInfo[str(taskId)] = [targetsNum, QuestTaskState.Complete]
                    quest = todayQuest[taskId]
                    _sendQuestFinished(userId, quest)
                    module_tip.addModuleTipEvent(userId, "task", taskId)
                    taskLevel = conf.get("taskLevel", 0)
                    # questData = getDailyQuestData(userId)
                    # finishedStar = questData.get("finishedStar", 0)
                    # dailyQuestRewardFinishedStars = config.getDailyQuestRewardFinishedStars()
                    # for star in dailyQuestRewardFinishedStars:
                    #     if finishedStar >= star and finishedStar - taskLevel < star:
                    #         module_tip.addModuleTipEvent(userId, "task", star)
                    #         break
                    # 发送完成任务事件
                    from newfish.entity.event import DailyTaskFinishEvent
                    from newfish.game import TGFish
                    event = DailyTaskFinishEvent(userId, FISH_GAMEID, int(conf["taskId"]), taskLevel)
                    TGFish.getEventBus().publishEvent(event)
                    bireport.reportGameEvent("BI_NFISH_GE_TASK_FINISHED", userId, FISH_GAMEID, 0,
                                             0, int(conf["taskId"]), int(taskLevel), 0, 0, [], util.getClientId(userId))
    if update:
        setUserQuestInfoData(userId, questInfo)
Пример #26
0
 def reportBiGameEvent(self, eventId, userId, roomId, tableId, roundId, detalChip, state1, state2, cardlist, tag=''):
     try:
         finalUserChip = userchip.getChip(userId)
         finalTableChip = 0
         clientId = sessiondata.getClientId(userId)
         bireport.reportGameEvent(eventId, userId, self.gameId, roomId, tableId, roundId, detalChip,
                                  state1, state2, cardlist, clientId, finalTableChip, finalUserChip)
         if ftlog.is_debug():
             ftlog.debug('tag=', tag, 'eventId=', eventId, 'userId=', userId, 'gameId=', self.gameId,
                         'roomId=', roomId, 'tableId=', tableId, 'roundId=', roundId, 'detalChip=', detalChip,
                         caller=self)
     except:
         ftlog.error(getMethodName(), 'tag=', tag, 'eventId=', eventId, 'userId=', userId, 'gameId=', self.gameId)
Пример #27
0
def reportOwnGunsAndGunSkins(event):
    """报告拥有的火炮和火炮皮肤"""
    ownGuns = gamedata.getGameAttrJson(event.userId, FISH_GAMEID,
                                       GameData.ownGunSkins, [])
    bireport.reportGameEvent("BI_NFISH_GE_ADD_GUN_ID", event.userId,
                             FISH_GAMEID, 0, 0, 0, 0, 0, 0, ownGuns,
                             util.getClientId(event.userId))
    ownGunSkinSkinsKey = GameData.ownGunSkinSkins
    ownGunSkinSkins = gamedata.getGameAttrJson(event.userId, FISH_GAMEID,
                                               ownGunSkinSkinsKey, [])
    bireport.reportGameEvent("BI_NFISH_GE_ADD_GUN_SKIN", event.userId,
                             FISH_GAMEID, 0, 0, 0, 0, 0, 0, ownGunSkinSkins,
                             util.getClientId(event.userId))
Пример #28
0
def _resetPoolAndWinCount(userId, gameId, nowLevel, poolUsed, rewardValue):
    '''
    重置奖池和获胜次数
    :param userId:
    :param gameId:
    '''
    pool = getPool(userId, gameId)
    gamedata.setGameAttrs(userId, gameId,
                          ["lotterytask_pool", "lotterytask_win"], [0, 0])
    bireport.reportGameEvent('HALL_LOTTERY_TASK_CONSUME', userId, gameId, 0, 0,
                             0, -pool, nowLevel, 0, [],
                             sessiondata.getClientId(userId), -poolUsed,
                             rewardValue)
Пример #29
0
def addUserVipExp(gameId,
                  userId,
                  toAddExp,
                  eventId,
                  intEventParam,
                  productId,
                  rmbs=-1,
                  isAddVipExp=True):
    """
    增加VIP经验值
    """
    rmbs = int(rmbs)
    if rmbs == -1 and toAddExp >= 10:
        rmbs = toAddExp / 10
    if isAddVipExp:
        hallvip.userVipSystem.addUserVipExp(gameId, userId, toAddExp, eventId,
                                            intEventParam)
    else:  # 自己处理vip升级事件.
        from hall.game import TGHall
        from hall.entity.hallvip import TYUserVipLevelUpEvent
        vipExp = hallvip.userVipSystem.getUserVip(userId).vipExp
        oldVipLevel = hallvip.vipSystem.findVipLevelByVipExp(vipExp - toAddExp)
        userVip = hallvip.userVipSystem.getUserVip(userId)
        if oldVipLevel.level != userVip.vipLevel.level:
            lv_event = TYUserVipLevelUpEvent(FISH_GAMEID, userId, oldVipLevel,
                                             userVip, [], 0, 0)
            TGHall.getEventBus().publishEvent(lv_event)
    # vip经验发生变化.
    from newfish.game import TGFish
    event = UserVipExpChangeEvent(userId, gameId, toAddExp)
    TGFish.getEventBus().publishEvent(event)
    if ftlog.is_debug():
        ftlog.debug("addUserVipExp----->event", gameId, userId, toAddExp,
                    eventId, intEventParam, rmbs, isAddVipExp)
    # 上报购买商品事件.
    loginDays = gamedata.getGameAttrInt(userId, FISH_GAMEID,
                                        GameData.loginDays)
    userLevel = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.level)
    isIn, roomId, tableId, _ = util.isInFishTable(userId)
    if isIn:
        from newfish.servers.table.rpc import table_remote
        table_remote.buyProduct(roomId, tableId, userId, intEventParam,
                                userLevel, loginDays)
    else:
        from poker.entity.biz import bireport
        userChip = userchip.getUserChipAll(userId)
        bireport.reportGameEvent("BI_NFISH_BUY_PRODUCT", userId, FISH_GAMEID,
                                 roomId, intEventParam, userLevel, 0, 0, 0, [],
                                 util.getClientId(userId), loginDays, userChip)
        # ftlog.debug("BI_NFISH_BUY_PRODUCT", userId, roomId, intEventParam, userLevel, util.getClientId(userId), userChip)
    updateUserDataByRecharge(userId, productId, rmbs)
Пример #30
0
def refreshReturnerMissionData(userId, lastLoginTime):
    """
    刷新回归豪礼数据
    """
    currTime = int(time.time())
    lastLoginTime = util.getDayStartTimestamp(lastLoginTime)
    returnerMissionConf = config.getReturnerMissionConf()
    # 判断是否激活回归豪礼
    if currTime - lastLoginTime >= returnerMissionConf["daysLost"] * 24 * 3600:
        returnerMission = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.returnerMission, {})
        lastActiveTime = util.getDayStartTimestamp(returnerMission.get("lastActiveTime", currTime))
        isActive = False
        if returnerMission:
            if currTime - lastActiveTime >= returnerMissionConf["daysBetween"] * 24 * 3600:
                isActive = True
        else:
            isActive = True
        if isActive:
            userLevel = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.level)
            vipLevel = hallvip.userVipSystem.getUserVip(userId).vipLevel.level
            vipExp = hallvip.userVipSystem.getUserVip(userId).vipExp
            returnerMission = {}
            returnerMission["lastActiveTime"] = currTime
            returnerMission["userLevel"] = userLevel
            returnerMission["vipExp"] = vipExp
            returnerMission["tasks"] = initTaskData()
            gamedata.setGameAttr(userId, FISH_GAMEID, GameData.returnerMission, json.dumps(returnerMission))
            bireport.reportGameEvent("BI_NFISH_GE_RETURNER_MISSION", userId, FISH_GAMEID, vipLevel,
                                     vipExp, userLevel, 0, 0, 0, [], util.getClientId(userId))
    returnerMission = getReturnerMissionData(userId)
    if returnerMission:
        # 解锁新任务
        lastActiveTime = util.getDayStartTimestamp(returnerMission["lastActiveTime"])
        fewDays = (datetime.fromtimestamp(currTime) - datetime.fromtimestamp(lastActiveTime)).days + 1
        fewDays = max(1, min(fewDays, len(returnerMission["tasks"])))
        # 第N天之前的任务都会解锁
        isUnlock = False
        taskIds = []
        for _index, taskConf in enumerate(config.getReturnerMissionConf("tasks")):
            if taskConf["taskId"] in returnerMission["tasks"]:
                if _index < fewDays and returnerMission["tasks"][taskConf["taskId"]]["state"] == 0:
                    returnerMission["tasks"][taskConf["taskId"]]["state"] = 1
                    isUnlock = True
                elif returnerMission["tasks"][taskConf["taskId"]]["state"] == 2:
                    taskIds.append(taskConf["taskId"])
        if isUnlock:
            gamedata.setGameAttr(userId, FISH_GAMEID, GameData.returnerMission, json.dumps(returnerMission))
        if taskIds:
            module_tip.addModuleTipEvent(userId, "returnerMission", taskIds)
    else:
        module_tip.resetModuleTipEvent(userId, "returnerMission")
Пример #31
0
 def clearTimer(self):
     """清理提示和结束的定时器"""
     super(FishGrandPrixPlayer, self).clearTimer()
     if self.grandPrixEndTimer:
         self.grandPrixEndTimer.cancel()
         self.grandPrixEndTimer = None
     if self.grandPrixTipTimer:
         self.grandPrixTipTimer.cancel()
         self.grandPrixTipTimer = None
     if self.inGameTimes:
         bireport.reportGameEvent("BI_NFISH_GRAND_PRIX_INGAMETIMES",
                                  self.userId, FISH_GAMEID, 0, 0,
                                  self.grandPrixStartTS, self.inGameTimes,
                                  0, 0, [], util.getClientId(self.userId))
Пример #32
0
def _triggerReportBIPropEvent(event):
    """统计上报BI系统"""
    propList = config.getStatisPropConf()
    mailStatisProp = reportBILogMailPropCount(event.userId)
    if not mailStatisProp:
        return
    for mailStatis in mailStatisProp:
        propId = int(mailStatis.get("name"))
        propCount = mailStatis.get("count")
        if propId not in propList:
            continue
        bireport.reportGameEvent("BI_STATISTIC_Mail_PROP", event.userId, event.gameId, 0, 0, propId, propCount, 0, 0, [], event.clientId)
        if ftlog.is_debug():
            ftlog.debug("_triggerReportBIPropEvent", "propId=", propId, "propCount=", propCount, event.userId)
Пример #33
0
def reportBILogOnLogin(userId):
    """
    首次登录上报BI数据
    """
    # 上报玩家火炮剩余天数
    timestamp = int(time.time())
    userBag = hallitem.itemSystem.loadUserAssets(userId).getUserBag()
    clientId = util.getClientId(userId)
    for mode in config.GAME_MODES:
        for itemId in config.getAllGunIds(clientId, mode):
            item = userBag.getItemByKindId(itemId)
            if item and not item.isDied(timestamp):
                bireport.reportGameEvent("BI_NFISH_GE_GUN_SKIN", userId, FISH_GAMEID, 0,
                                         0, int(itemId), item.balance(timestamp), mode, 0, [], clientId)
Пример #34
0
    def onTableGameStart(self, gameId, msg):
        if ftlog.is_debug():
            ftlog.debug("<< |msg", msg, caller=self)

        table = msg.getParam("table")

        bireport.tableStart(table.gameId, table.roomId, table.tableId,
                            table.gamePlay.gameSeq, DiFangPlayersHelper.getPlayingPlayersIds(table))

        for player in DiFangPlayersHelper.getPlayingPlayers(table):
            bireport.reportGameEvent('TABLE_START',
                                     player.userId, gameId, table.roomId, table.tableId,
                                     table.gamePlay.gameSeq,
                                     0, 0, 0, [],
                                     sessiondata.getClientId(player.userId),
                                     player.tableChips)
Пример #35
0
def ensureGameDataExists(userId, gameId, clientId):
    '''
    判定用户游戏数据是否存在, 若不存在则初始化该游戏的所有的相关游戏数据
    包括: 主游戏数据gamedata, 道具, 勋章等
    '''
    isCreate = False
    gaccount = TYGame(gameId)
    # 以游戏主数据的前2个字段为判定条件
    ukeys = gaccount.getInitDataKeys()[0:2]
    d1, d2 = gamedata.getGameAttrs(userId, gameId, ukeys)
    if d1 is None or d2 is None:
        gdkeys, gdata = gaccount.createGameData(userId, gameId)
        gdkeys.append('createTime')
        gdata.append(timestamp.formatTimeMs())
        bireport.creatGameData(gameId, userId, clientId, gdkeys, gdata)
        bireport.reportGameEvent('CREATE_GAME_DATA',
                                 userId, gameId, 0, 0, 0, 0, 0, 0, [], clientId)
        isCreate = True
    return isCreate
Пример #36
0
    def get_award(self, uid):
        if not self.checkOperative():
            return 'acitivity expired!'

        actkey = ACTIVITY_KEY.format(HALL_GAMEID, uid, self.getid())
        weekcnt, daycnt = self._get_click_cnt(uid, actkey)
        if weekcnt >= self._clientConf['config']['weeklimit'] or daycnt >= self._clientConf['config']['daylimit']:
            return 'awardcnt:({},{}) expand limitcnt!'.format(weekcnt, daycnt)

        shareid = self._serverConf["share"]
        share = hallshare.findShare(shareid)
        if not share:
            return 'share:{} not exist!'.format(shareid)

        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_DAY_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_WEEK_CNT, 1)
        daobase.executeUserCmd(uid, 'HINCRBY', actkey, self.FIELD_TOTAL_CNT, 1)
        hallshare.sendReward(HALL_GAMEID, uid, share, 'share_click')
        # 分享BI日志汇报
        clientid = sessiondata.getClientId(uid)
        bireport.reportGameEvent('SHARE_CALLBACK', uid, HALL_GAMEID, shareid, 0, 0, 0, 0, 0, [], clientid)
        if share.mail:
            message.send(HALL_GAMEID, message.MESSAGE_TYPE_SYSTEM, uid, share.mail)
        return 'ok'
Пример #37
0
def getShareReward(gameId, userId, share, shareLoc, timestamp):
    '''
    给用户发放分享奖励
    '''
    # 分享BI日志汇报
    clientId = sessiondata.getClientId(userId)
    bireport.reportGameEvent('SHARE_CALLBACK', userId, gameId, share.shareId, 0, 0, 0, 0, 0, [], clientId)

    # 记录分享次数
    gamedata.incrGameAttr(userId, HALL_GAMEID, 'shareCount', 1)
    TGHall.getEventBus().publishEvent(HallShareEvent(gameId, userId, share.shareId, shareLoc))

    # 首先处理 分享相关的通知
    notifyInfoStr = pkgamedata.getGameAttr(userId, HALL_GAMEID, 'shareInfo')
    newInfo = {}
    pkgamedata.setGameAttr(userId, HALL_GAMEID, 'shareInfo', json.dumps(newInfo))

    if notifyInfoStr:
        notifyInfo = json.loads(notifyInfoStr)
        shareId = notifyInfo.get('shareId', 0)
        if shareId == share.shareId:
            # 通知
            info = notifyInfo.get('info', '')
            module = notifyInfo.get('module', '')
            if module == hall_red_envelope.TYRedEnvelope.EVENTID:
                hall_red_envelope.TYRedEnvelopeMgr.changeRedEnvelopeState(info,
                                                                          hall_red_envelope.TYRedEnvelope.STATE_SHARED)

                from poker.entity.game.game import TYGame
                clientId = sessiondata.getClientId(userId)
                gameids = hallconf.getDaShiFenFilter(clientId)
                for gid in gameids:
                    TYGame(gid).sendTuyooRedEnvelopeCallBack(userId, clientId, info)

    # 分享奖励
    ok, rewardCount = incrRewardCount(userId, share, timestamp)
    if not ok:
        if ftlog.is_debug():
            ftlog.debug('hallshare.getShareReward already no share, check update share promote ...')
            ftlog.debug('hallshare.getShareReward fail gameId=', gameId,
                        'userId=', userId,
                        'shareId=', share.shareId,
                        'shareLoc=', shareLoc,
                        'rewardCount=', rewardCount,
                        'maxRewardCount=', share.maxRewardCount)
        return False

    assetList = sendReward(gameId, userId, share, shareLoc)
    if assetList and share.mail:
        TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskGoldRain(share.mail))

    ftlog.debug('hallshare.getShareReward ok gameId=', gameId,
                'userId=', userId,
                'shareId=', share.shareId,
                'shareLoc=', shareLoc,
                'rewardCount=', rewardCount,
                'maxRewardCount=', share.maxRewardCount,
                'reward=', [(at[0].kindId, at[1]) for at in assetList] if assetList else [])
    if share.mail:
        pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_SYSTEM, userId, share.mail)
    # udpate free & promotion_loc
    datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc'])
    return True