Exemple #1
0
    def getChouJiangReward(self, gameId, userId, clientId):
        from dizhu.activities.choujiang_360 import ChouJiang360
        status = 0
        all_count = 0
        get_count = 0
        tip = ''
        ecode = 0
        try:
            data = gamedata.getGameAttrJson(userId, gameId,
                                            ChouJiang360.attr_act, {})
            if data:
                if data["get_count"] < data["current_count"]:
                    tip = self.sendReward(gameId, userId, clientId,
                                          TYContentItem('item:4147', 1),
                                          'HUI_YUAN_360', 0)
                    tip = ''.join([tip, ' 请去背包查收'])
                    data["get_count"] += 1

                all_count = data["all_count"]
                get_count = data["get_count"]

                status = int(data["get_count"] < data["current_count"])

                gamedata.setGameAttr(userId, gameId, ChouJiang360.attr_act,
                                     json.dumps(data))
        except:
            ftlog.exception()
            tip = "领取失败"
            ecode = 1

        return tip, ecode, status, all_count, get_count
Exemple #2
0
    def doGetInviteRewardAll(cls, userId):
        status = loadStatus(userId)
        inviteeRewardList = status.inviteeRewardList
        rewardsList = []
        bigReward = None
        save = False
        for index, rewardState in enumerate(inviteeRewardList):
            if rewardState.rewardState == REWARD_STATE_IDEAL:
                rewardState.rewardState = REWARD_STATE_RECEIVED
                save = True
                r = getSimpleInviteRewardByIndex(index)
                if r:
                    rewardsList.append(r)
        if rewardsList:
            contentItems = TYContentItem.decodeList(rewardsList)
            assetList = dizhu_util.sendRewardItems(userId, contentItems, '', 'DIZHU_QIANDAO_REWARD', 0)

        if len(inviteeRewardList) >= len(getSimpleInviteRewardsConf()):
            bigReward = getSimpleInviteBigReward(userId)
            if bigReward:
                contentItems = TYContentItem.decodeList([bigReward])
                assetList = dizhu_util.sendRewardItems(userId, contentItems, '', 'DIZHU_QIANDAO_REWARD', 0)
                if bigReward.get('itemId') == 'user:coupon':
                    TGHall.getEventBus().publishEvent(UserCouponReceiveEvent(9999, userId, bigReward['count'],
                                                                         user_coupon_details.USER_COUPON_INVITE))
                status.bigRewardState = REWARD_STATE_RECEIVED
                save = True
                conf = getSimpleInviteConf()
                if conf.get('switch'):
                    gamedata.setGameAttr(userId, DIZHU_GAMEID, 'firstBigRewards', 1)
        if save:
            saveStatus(status)
        return rewardsList, bigReward
def saveStatus(status):
    '''
    保存数据
    '''
    d = status.encodeToDict({})
    jstr = json.dumps(d)
    gamedata.setGameAttr(status.userId, HALL_GAMEID, 'simple_invite', jstr)
Exemple #4
0
def _onTableWinlose(event):
    status = gamedata.getGameAttrJson(event.userId, DIZHU_GAMEID,
                                      'item.win.progress', {})
    if ftlog.is_debug():
        ftlog.debug('dizhuredenvelope._onTableWinlose userId=', event.userId,
                    'status=', status)
    if event.winlose.isWin:
        changed = False
        roomConf = gdata.getRoomConfigure(event.roomId)
        playMode = roomConf.get('playMode')
        for itemConf in _itemConfList:
            if not itemConf['playModes'] or playMode in itemConf['playModes']:
                changed = True
                itemId = str(itemConf['itemId'])
                winTimes = itemConf['winTimes']
                progress = status.get(itemId, 0) + 1
                status[itemId] = progress
                if progress >= winTimes:
                    flagName = 'item.open.flag:%s' % (itemId)
                    gamedata.setnxGameAttr(event.userId, HALL_GAMEID, flagName,
                                           1)
        if changed:
            gamedata.setGameAttr(event.userId, DIZHU_GAMEID,
                                 'item.win.progress', strutil.dumps(status))
        if ftlog.is_debug():
            ftlog.debug('dizhuredenvelope._onTableWinlose userId=',
                        event.userId, 'status=', status, 'changed=', changed)
Exemple #5
0
    def onGameRoundFinish(cls, event):
        banConf = cls.getMatchBanConf()
        if not banConf.get("open"):
            return

        if ftlog.is_debug():
            ftlog.debug('BanHelper.onGameRoundFinish',
                        'tableId=', event.table.tableId,
                        'seats=', [(s.userId, s.seatId, s.status.isPunish, s.player.isQuit) for s in event.table.seats])
        for seat in event.table.seats:
            if hasattr(seat.player, 'mixId') and seat.player.mixId:
                roomId = int(seat.player.mixId)
            else:
                roomId = event.table.bigRoomId

            if seat.status.isTuoguan and not seat.player.isQuit and roomId in banConf.get('fromRooms', []):
                matchTuoguan = gamedata.getGameAttr(seat.userId, DIZHU_GAMEID, 'matchTuoguanCount')
                matchTuoguan = strutil.loads(matchTuoguan) if matchTuoguan else {}

                # 自然日清零
                currentTimestamp = pktimestamp.getCurrentTimestamp()
                if not pktimestamp.is_same_day(currentTimestamp, matchTuoguan.get('expired', pktimestamp.getCurrentTimestamp())):
                    matchTuoguan['expired'] = pktimestamp.getCurrentTimestamp()
                    matchTuoguan['count'] = 0

                if matchTuoguan.get('count'):
                    matchTuoguan['count'] += 1
                else:
                    matchTuoguan['count'] = 1

                banTime = cls.getTuoguanBanTime(matchTuoguan['count'], banConf)
                if banTime:
                    matchTuoguan['expired'] = banTime * 60 + pktimestamp.getCurrentTimestamp()
                gamedata.setGameAttr(seat.userId, DIZHU_GAMEID, 'matchTuoguanCount', strutil.dumps(matchTuoguan))
Exemple #6
0
 def saveRecord(cls, gameId, userId, matchId, record, mixId=None):
     if ftlog.is_debug():
         ftlog.debug('MatchRecord.saveRecord gameId=', gameId, 'userId=',
                     userId, 'matchId=', matchId, 'record=',
                     json.dumps(record.toDict()), 'mixId=', mixId)
     gamedata.setGameAttr(userId, gameId, cls.__buildField(matchId, mixId),
                          json.dumps(record.toDict()))
Exemple #7
0
 def _triggerEnterTableEvent(self, event):
     tableId = event.tableId
     userId = event.userId
     if tableId in self._allTableDict:
         self._allPlayerDict[userId] = tableId
         self._allTableSeatDict[tableId].add(userId)
         if ftlog.is_debug():
             ftlog.debug("_triggerEnterTableEvent", self._allPlayerDict)
     import time
     from poker.util import strutil
     from newfish.entity.task.task_system_user import RedState
     from newfish.entity.config import FISH_GAMEID
     from newfish.entity.redis_keys import GameData
     newbie7DayGiftData = gamedata.getGameAttrJson(
         userId, FISH_GAMEID, GameData.newbie7DayGiftData)  # 新手7日礼包数据
     if isinstance(newbie7DayGiftData,
                   list) and len(newbie7DayGiftData) == 2:
         return
     redState = gamedata.getGameAttrInt(userId, FISH_GAMEID,
                                        GameData.redState)  # 新手任务状态
     if redState < RedState.Complete:
         gamedata.setGameAttr(
             userId, FISH_GAMEID, GameData.newbie7DayGiftData,
             strutil.dumps(
                 [util.getDayStartTimestamp(int(time.time())), []]))
def loginByInvited(userId, shareUserId, isNewPlayer):
    """
    :param userId: 被邀请人
    :param shareUserId: 分享者(邀请人)
    :param isNewPlayer: 是否为新用户
    """
    isCanInvite = config.getCommonValueByKey("canInvite")
    isInvite = weakdata.getDayFishData(userId, "isInvited", 0)
    if not isCanInvite or isInvite:
        return False
    userdata.checkUserData(shareUserId)
    if isNewPlayer:
        from newfish.game import TGFish
        from newfish.entity.event import AddInvitedNewUserEvent
        # 存储邀请人信息
        from hall.entity import hallvip
        from newfish.entity.redis_keys import GameData
        shareUserVip = int(hallvip.userVipSystem.getUserVip(shareUserId).vipLevel.level)
        inviterInfo = {
            "userId": shareUserId, "inviteTime": int(time.time()), "vip": shareUserVip
        }
        gamedata.setGameAttr(userId, FISH_GAMEID, GameData.inviterInfo, json.dumps(inviterInfo))
        saveKey = "inviteNewPlayers"
        actionType = NewPlayerAction
        event = AddInvitedNewUserEvent(shareUserId, FISH_GAMEID, userId)
        TGFish.getEventBus().publishEvent(event)
    else:
        saveKey = "recallPlayers"
        actionType = RecallPlayerAction
    user_rpc.addInviteNum(shareUserId, userId, actionType, saveKey, isNewPlayer)
    return True
Exemple #9
0
 def getFriendListPrize(cls, userId, friendId, gameId):
     '''
     rpc
     '''
     friendlist = gamedata.getGameAttr(userId, gameId,
                                       cls.attrname_invitedfriendlist)
     if not friendlist:
         return [0, 0]
     friendlist = json.loads(friendlist)
     chipget = 0
     couponget = 0
     index = 0
     if friendId == -1:
         for i in friendlist:
             index += 1
             if i['state'] == 0:
                 chipget += 1
                 i['state'] = 1
                 if index % 5 == 0:
                     couponget += 1
     else:
         for i in friendlist:
             index += 1
             if i['userId'] == friendId and i['state'] == 0:
                 chipget += 1
                 i['state'] = 1
                 if index % 5 == 0:
                     couponget += 1
     gamedata.setGameAttr(userId, gameId, cls.attrname_invitedfriendlist,
                          json.dumps(friendlist))
     return [chipget, couponget]
 def addGiftData(self, giftId):
     """
     使礼包变为可领取状态并添加礼包数据
     """
     code = 1
     mode = util.getGiftDTestMode(self.userId)
     giftConf = config.getGiftAbcTestConf(self.clientId)
     bankruptGiftInfo = gamedata.getGameAttrJson(self.userId, FISH_GAMEID,
                                                 GameData.bankruptGiftInfo)
     isValid = False
     if bankruptGiftInfo:
         fishPool, grade, nextGrade = bankruptGiftInfo
         buyTimes = self._getBuyTimes(fishPool)
         # 检查礼包是否存在以及购买次数.
         giftAbcTestConf = giftConf.get("data", {})
         giftListConf = giftAbcTestConf.get(str(fishPool), {}).get(
             grade, {}).get("giftList", {}).get(mode, [])
         if 0 <= buyTimes < len(giftListConf):
             if str(giftId) == str(giftListConf[buyTimes]):
                 isValid = True
             else:
                 ListConf2 = giftAbcTestConf.get(str(fishPool), {}).get(
                     nextGrade, {}).get("giftList", {}).get(mode, [])
                 if str(giftId) == str(ListConf2[buyTimes]):
                     # 后续会用这个数据做上一次购买的档位记录,所以在这里进行修改
                     bankruptGiftInfo[1] = bankruptGiftInfo[2]
                     gamedata.setGameAttr(self.userId, FISH_GAMEID,
                                          GameData.bankruptGiftInfo,
                                          json.dumps(bankruptGiftInfo))
                     isValid = True
     if isValid:
         self.addToAvailableGift(giftId)
         code = 0
     return code
 def refreshRechargeOdds(self):
     """
     刷新充值概率数据
     """
     if self.table.typeName not in config.RECHARGE_BONUS_ROOM_TYPE:
         return
     if not self.player or not self.player.userId:
         return
     if self._originRechargeBonus <= 0:
         self._originRechargeBonus = gamedata.getGameAttrInt(
             self.player.userId, FISH_GAMEID, GameData.rechargeBonus)
         self._currRechargeBonus = self._originRechargeBonus
     else:
         newestBonus = gamedata.getGameAttrInt(self.player.userId,
                                               FISH_GAMEID,
                                               GameData.rechargeBonus)
         self._currRechargeBonus += newestBonus - self._originRechargeBonus
         self._originRechargeBonus = self._currRechargeBonus
         gamedata.setGameAttr(self.player.userId, FISH_GAMEID,
                              GameData.rechargeBonus,
                              self._currRechargeBonus)
         ftlog.info("refreshRechargeOdds->", "userId =", self.player.userId,
                    "newestBonus =", newestBonus, "_originRechargeBonus =",
                    self._originRechargeBonus, "_currRechargeBonus =",
                    self._currRechargeBonus)
     # 更新额外充值奖池,先按照额外充值奖池增加前的数据结算当前的扣除额外奖池,然后更新额外奖池和扣除奖池的数据.
     _orginExtraRechargeBonus = self._orginExtraRechargeBonus
     util.decreaseExtraceRechargeBonus(
         self.player.userId,
         min(_orginExtraRechargeBonus, self.decreasedRechargeBonus))
     self.decreasedRechargeBonus = 0
     self._orginExtraRechargeBonus = gamedata.getGameAttrInt(
         self.player.userId, FISH_GAMEID, GameData.extraRechargePool)
Exemple #12
0
 def saveScoreInfo(self, rankingId, userId, scoreInfo):
     '''
     保存用户的scoreInfo
     '''
     field = 'ranking.info:%s' % (rankingId)
     jstr = json.dumps({'score': scoreInfo.score, 'issueNumber': scoreInfo.issueNumber})
     pkgamedata.setGameAttr(userId, 9999, field, jstr)
 def saveDynamicOddsData(self):
     """
     保存动态概率配置数据
     """
     if not self.player or not self.player.userId:
         return
     if self.table.typeName not in config.RECHARGE_BONUS_ROOM_TYPE:
         return
     gamedata.setGameAttr(self.player.userId, FISH_GAMEID,
                          GameData.rechargeBonus, self._currRechargeBonus)
     util.decreaseExtraceRechargeBonus(self.player.userId,
                                       self.decreasedRechargeBonus)
     self.decreasedRechargeBonus = 0
     if self.isProtectMode():
         return
     if self.table.typeName not in config.DYNAMIC_ODDS_ROOM_TYPE:
         return
     if self.waveId:
         oddsData = gamedata.getGameAttrJson(self.player.userId,
                                             FISH_GAMEID,
                                             GameData.dynamicOdds, {})
         oddsData[str(self.fishPool)] = [
             self.waveId, self.waveIndex, self.waveRadix, self.waveCoin
         ]
         gamedata.setGameAttr(self.player.userId, FISH_GAMEID,
                              GameData.dynamicOdds, json.dumps(oddsData))
         ftlog.info("saveDynamicOddsData->", "userId =", self.player.userId,
                    "_originRechargeBonus =", self._originRechargeBonus,
                    "_currRechargeBonus =", self._currRechargeBonus,
                    "oddsData =", oddsData[str(self.fishPool)])
Exemple #14
0
 def getFriendListPrize(cls, userId, friendId, gameId):
     '''
     rpc
     '''
     friendlist = gamedata.getGameAttr(userId, gameId, cls.attrname_invitedfriendlist)
     if not friendlist:
         return [0, 0]
     friendlist = json.loads(friendlist)
     chipget = 0
     couponget = 0
     index = 0
     if friendId == -1:
         for i in friendlist:
             index += 1
             if i['state'] == 0:
                 chipget += 1
                 i['state'] = 1
                 if index % 5 == 0:
                     couponget += 1
     else:
         for i in friendlist:
             index += 1
             if i['userId'] == friendId and i['state'] == 0:
                 chipget += 1
                 i['state'] = 1
                 if index % 5 == 0:
                     couponget += 1
     gamedata.setGameAttr(userId, gameId, cls.attrname_invitedfriendlist, json.dumps(friendlist))
     return [chipget, couponget]
Exemple #15
0
    def addfriend(cls, userId, friendId, gameId, prize, numlimit):
        '''
        rpc
        '''
        if not cls.friendNumLimit(userId, gameId, numlimit):
            return -1
        friend = {'userId': friendId, 'state': 0}
        friendlist = gamedata.getGameAttr(userId, gameId, cls.attrname_invitedfriendlist)
        if not friendlist:
            friendlist = []
        else:
            friendlist = json.loads(friendlist)

        existed = False
        for f in friendlist:
            if f['userId'] == friendId:
                existed = True
                break

        if existed:
            return -1
        else:
            friendlist.append(friend)
            gamedata.setGameAttr(userId, gameId, cls.attrname_invitedfriendlist, json.dumps(friendlist))
            gamedata.incrGameAttr(userId, gameId, cls.attrname_failchip, prize["CHIP"])
            gamedata.incrGameAttr(userId, gameId, cls.attrname_invitedfriendnum, 1)
            friendnum = len(friendlist)
            if friendnum % 5 == 0:
                gamedata.incrGameAttr(userId, gameId, cls.attrname_failcoupon, prize["COUPON"])

            return friendnum
Exemple #16
0
def loginGame(userId, gameId, clientId, iscreate, isdayfirst):
    """ 用户登录一个游戏, 游戏自己做一些其他的业务或数据处理
    """
    ftlog.debug('userId =', userId, 'gameId =', gameId, 'clientId =', clientId,
                'iscreate =', iscreate, 'isdayfirst =', isdayfirst)
    if isdayfirst:
        gamedata.setGameAttr(userId, gameId, "day_play_game_count", 0)
Exemple #17
0
def setNewbie7Day(userId):
    """
    设置新手八日礼包数据
    """
    ts = int(time.time())
    gamedata.setGameAttr(userId, FISH_GAMEID, GameData.newbie7DayGiftData,
                         strutil.dumps([util.getDayStartTimestamp(ts), []]))
Exemple #18
0
def sendIdentifyReward(userId):
    """
    实名认证领奖
    """
    mo = MsgPack()
    mo.setCmd("id_card_identify_reward")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    identifyReward = []
    if ftlog.is_debug():
        ftlog.debug("user_system.sendIdentifyReward IN",
                    "userId=", userId)
    try:
        rewarded = gamedata.getGameAttrInt(userId, FISH_GAMEID, GameData.idCardRewarded)
        if rewarded:
            code = 1
        else:
            idCardReward = config.getCommonValueByKey("idCardReward", [])
            if ftlog.is_debug():
                ftlog.debug("user_system.sendIdentifyReward send reward",
                            "userId=", userId,
                            "idCardReward=", idCardReward)
            code = util.addRewards(userId, idCardReward, "BI_NFISH_NEW_USER_REWARDS")
            if code == 0:
                identifyReward = idCardReward
                gamedata.setGameAttr(userId, FISH_GAMEID, GameData.idCardRewarded, 1)
    except Exception as e:
        ftlog.error("user_system.sendIdentifyReward error", e,
                    "userId=", userId)
        code = 3
    mo.setResult("code", code)
    mo.setResult("reward", identifyReward)
    router.sendToUser(mo, userId)
Exemple #19
0
    def sendBenefits(self, gameId, userId, timestamp=None):
        '''
        发放救济金
        @return: isSend(True/False), TYUserBenefits
        '''
        if timestamp is None:
            timestamp = pktimestamp.getCurrentTimestamp()
        chip = pkuserchip.getUserChipAll(userId)
        if chip < self._minChip:
            # 用户金币低于指定数目时,发放救济金
            userBenefits = self.loadUserBenefits(gameId, userId, timestamp)
            if not userBenefits.hasLeftTimes():  # 没有剩余次数,弹分享引导
                oldtime = gamedata.getGameAttr(userId, HALL_GAMEID, 'relief_share_date')
                if not oldtime or datetime.fromtimestamp(oldtime).date() < datetime.fromtimestamp(timestamp).date():
                    # 每天最多弹一次
                    gamedata.setGameAttr(userId, HALL_GAMEID, 'relief_share_date', timestamp)
                    shareId = hallshare.getShareId('Relieffund', userId, gameId)
                    share = hallshare.findShare(shareId)
                    if share:
                        task = share.buildTodotask(gameId, userId, 'Relieffund')
                        TodoTaskHelper.sendTodoTask(gameId, userId, task)
                return False, userBenefits

            # 发放救济金
            userBenefits.times += 1
            self._benefitsDao.saveUserBenefitsData(userId, TYUserBenefitsData(userBenefits.times, timestamp))
            self._sendBenefits(gameId, userBenefits)
            # 通知用户金币刷新
            datachangenotify.sendDataChangeNotify(gameId, userId, ['udata'])
            return True, userBenefits
        return False, self.loadUserBenefits(gameId, userId, timestamp)
def getReturnerReward(userId, clientId, taskId):
    """
    领取回归豪礼
    """
    rewards = None
    returnerMission = getReturnerMissionData(userId)
    if returnerMission:
        for taskConf in config.getReturnerMissionConf("tasks"):
            if taskConf["taskId"] == taskId and taskId in returnerMission["tasks"]:
                if returnerMission["tasks"][taskId]["state"] == 2:
                    rewards = buildTaskRewards(taskConf["rewards"], returnerMission["userLevel"], returnerMission["vipExp"])
                    returnerMission["tasks"][taskId]["state"] = 3
                    break
    mo = MsgPack()
    mo.setCmd("returner_reward")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("taskId", taskId)
    mo.setResult("code", 0 if rewards else 1)
    if rewards:
        util.addRewards(userId, rewards, "BI_NFISH_RETURNER_REWARDS", int(taskId))
        gamedata.setGameAttr(userId, FISH_GAMEID, GameData.returnerMission, json.dumps(returnerMission))
        module_tip.cancelModuleTipEvent(userId, "returnerMission", taskId)
        mo.setResult("rewards", rewards)
    router.sendToUser(mo, userId)
Exemple #21
0
def triggerUserLoginEvent(event):
    """
    用户登录事件
    """
    userId = event.userId
    clientId = event.clientId
    currSectionId = gamedata.getGameAttr(userId, FISH_GAMEID,
                                         GameData.currSectionId)
    if not currSectionId:
        currSectionId = int(
            config.getMainQuestSectionConf(clientId).keys()[0])  # 初始化第一章第一节
        gamedata.setGameAttr(userId, FISH_GAMEID, GameData.currSectionId,
                             currSectionId)
        sectionConf = config.getMainQuestSectionConf(clientId, currSectionId)
        gamedata.setGameAttr(userId, FISH_GAMEID, GameData.mainQuestDisplay,
                             sectionConf["display"])
    isIn, _, _, _ = util.isInFishTable(userId)
    if not isIn:
        # setQuestTypeData(userId, QuestType.HoldCoin, userchip.getChip(userId))
        # setQuestTypeData(userId, QuestType.HoldGoldBullet, util.balanceItem(userId, config.GOLD_BULLET_KINDID))
        setQuestTypeData(userId, QuestType.UserLevelUp,
                         gamedata.getGameAttrInt(userId, FISH_GAMEID,
                                                 GameData.level))  # 用户等级
        setQuestTypeData(userId, QuestType.LevelUp,
                         util.getGunX(
                             gamedata.getGameAttrInt(userId, FISH_GAMEID,
                                                     GameData.gunLevel_m),
                             config.MULTIPLE_MODE))  # 皮肤炮等级
        setQuestTypeData(
            userId, QuestType.AchievementLevel,
            gamedata.getGameAttrInt(userId, FISH_GAMEID,
                                    GameData.achievementLevel))  # 荣耀任务等级
        refreshHigherSkillLevel(userId)  # 技能达到16级以上的任务
    refreshQuestModuleTip(userId, clientId)
Exemple #22
0
def saveMySkin(model):
    d = model.toDict()
    gamedata.setGameAttr(model.userId, DIZHU_GAMEID, 'table.skin',
                         strutil.dumps(d))
    if ftlog.is_debug():
        ftlog.debug('saveMySkin userId=', model.userId, 'model=',
                    model.toDict())
Exemple #23
0
    def getDay30Reward(self, gameId, userId, clientId):
        from dizhu.activities.login30_360 import Login30
        status = 0
        all_count = 0
        get_count = 0
        tip = ''
        ecode = 0
        try:
            conf = dizhuconf.getActivityConf("huiyuan_360")
            data = gamedata.getGameAttrJson(userId, gameId, Login30.attr_act,
                                            {})
            if data:
                if data["get_count"] != data["current_count"]:
                    reward = conf.get("login30", [])[data["current_count"] - 1]
                    contentItem = TYContentItem.decodeFromDict(reward)
                    tip = self.sendReward(gameId, userId, clientId,
                                          contentItem, 'HUI_YUAN_360', 0)
                    data["get_count"] = data["current_count"]

                all_count = data["all_count"]
                get_count = data["get_count"]

                status = int(data["get_count"] < data["current_count"])

                gamedata.setGameAttr(userId, gameId, Login30.attr_act,
                                     json.dumps(data))
        except:
            ftlog.exception()
            tip = "领取失败"
            ecode = 1

        return tip, ecode, status, all_count, get_count
Exemple #24
0
def loginGame(userId, gameId, clientId, iscreate, isdayfirst):
    """ 用户登录一个游戏, 游戏自己做一些其他的业务或数据处理
    """
    ftlog.debug('userId =', userId, 'gameId =', gameId, 'clientId =', clientId,
                'iscreate =', iscreate, 'isdayfirst =', isdayfirst)
    if isdayfirst:
        gamedata.setGameAttr(userId, gameId, "day_play_game_count", 0)
 def catchFish(self, fId, fishConf, fpMultiple, gunX):
     """
     判断是否给轮盘充能
     :param fId: 鱼的id
     :param fishConf: 鱼的配置
     :param fpMultiple: 1、2、3、4、5
     :param gunX: 炮倍
     """
     level = str(self.getEnergyIdx()[0])
     if not self._enable(level, fpMultiple):
         return
     pwData = self._getData(level, fpMultiple)
     if pwData[PWValueSlot.
               STATE] != PWState.NOT_SPIN and not self.isEnergyStorageMode:
         return
     val = fishConf.get("prizeWheelValue", 0) * fpMultiple * gunX
     if ftlog.is_debug():
         ftlog.debug("lpw_catch_fish, userId =", self.userId, "level =",
                     level, "val =", val, fpMultiple, gunX)
     if not val:
         return
     number = gamedata.getGameAttrInt(
         self.userId, FISH_GAMEID, GameData.levelPrizeWheelCatchFishNumber)
     number += 1
     gamedata.setGameAttr(self.userId, FISH_GAMEID,
                          GameData.levelPrizeWheelCatchFishNumber, number)
     if pwData[PWValueSlot.SPINTIMES] >= self.maxSpinTimes:
         return
     if self._addEnergy(level, fpMultiple, int(val)):
         self.sendEnergyProgress(0, fpMultiple, self.roomId, val,
                                 fId)  # 传0表示刷新当前最大的段位,因为会越级
 def saveTableRecord(cls, tableRecordInfo, gameId):
     #add by taoxc
     ftlog.debug('createTableRecord.saveTableRecord tableRecordInfo:', tableRecordInfo, 'gameId:', gameId)
     #保存用户数据
     for userId, playerRecordInfo in tableRecordInfo.items():
         recordKey = cls._getTableRecordKey(gameId, userId)
         ftlog.debug('createTableRecord.saveTableRecord recordKey:', recordKey)
         #通过recordKey获取当前玩家的战绩记录数据,如果超过最大存储则进行删除处理(同时删除对应的内容)
         userRecordKeys = gamedata.getGameAttr(userId, gameId, recordKey)
         if not userRecordKeys:
             userRecordKeys = []
             ftlog.debug('createTableRecord.saveTableRecord recordKey content is null')
         else:
             userRecordKeys = json.loads(userRecordKeys)
             ftlog.debug('createTableRecord.saveTableRecord recordKey content:', userRecordKeys)
             
         if len(userRecordKeys) >= cls._user_record_count:
             #删除最早的记录(附带删除内容)
             lastestKey = userRecordKeys.pop(0)
             daobase.executeRePlayCmd('DEL', lastestKey)
             ftlog.debug('createTableRecord.saveTableRecord recordKey len > ', cls._user_record_count, ' delete key:', lastestKey)
             
         recordContentKey = cls._getTableRecordContentKey(gameId, userId)
         userRecordKeys.append(recordContentKey)
         #保存KEY
         gamedata.setGameAttr(userId, gameId, recordKey, json.dumps(userRecordKeys))
         #保存内容
         daobase.executeRePlayCmd('SET', recordContentKey, json.dumps(playerRecordInfo))
         ftlog.debug('createTableRecord.saveTableRecord save keys:', userRecordKeys, ' save content:', playerRecordInfo)
Exemple #27
0
def _triggerProductBuyEvent(event):
    """
    处理商品购买事件
    """
    userId = event.userId
    productId = event.productId
    rechargeConf = config.getRechargePoolConf(productId)
    if rechargeConf:
        # 第一次购买指定奖池金币,之后随机
        rechargeCountDict = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.rechargeCount, {})
        rechargeCountDict[productId] = rechargeCountDict.setdefault(productId, 0) + 1
        gamedata.setGameAttr(userId, FISH_GAMEID, GameData.rechargeCount, json.dumps(rechargeCountDict))
        rechargeBonus = 0
        if rechargeCountDict[productId] == 1:
            rechargeBonus += int(rechargeConf["bonuses"][2]["bonus"])
        else:
            randInt = random.randint(1, 10000)
            for bonusConf in rechargeConf["bonuses"]:
                probb = bonusConf["probb"]
                if probb[0] <= randInt <= probb[1]:
                    rechargeBonus += int(bonusConf["bonus"])
        # 增加充值奖池
        final = util.incrUserRechargeBonus(userId, int(rechargeBonus))
        ftlog.info("_triggerProductBuyEvent->userId =", userId,
                   "productId =", productId,
                   "rechargeBonus =", rechargeBonus,
                   "finalRechargeBonus =", final, event.buyCount)
def _sendMailBySender(senderUserId, receiverUserId, type, reward=None, desc=None, title=None):
    """
    添加邮件到发件人发件箱
    :param senderUserId: 发件人
    :param receiverUserId: 收件人
    :param type: 邮件类型
    :param reward: 附件奖励
    :param desc: 邮件内容
    :param title: 标题
    """
    curTime = int(time.time())
    desc = desc or ""
    reward = reward or []
    title = title or ""
    mailOutId = gamedata.incrGameAttr(senderUserId, FISH_GAMEID, GameData.outMailId, 1)
    mailOutInfos = gamedata.getGameAttrJson(senderUserId, FISH_GAMEID, GameData.outMailInfos, [])
    receiverUserName = util.getNickname(receiverUserId)
    mailOutInfos.insert(0, {
        "id": mailOutId,
        "userId": receiverUserId,
        "time": curTime,
        "name": receiverUserName,
        "reward": reward,
        "type": type,
        "desc": desc,
        "title": title
    })
    mailOutInfos = _removeOutMailExpData(mailOutInfos, MAX_OUT_MAIL_COUNT)
    gamedata.setGameAttr(senderUserId, FISH_GAMEID, GameData.outMailInfos, json.dumps(mailOutInfos))
    if type == MailRewardType.Present:
        lang = util.getLanguage(senderUserId)
        message = config.getMultiLangTextConf("ID_PRESENT_TO_OTHER_MSG", lang=lang)
        message = message.format(receiverUserName, receiverUserId, util.buildRewardsDesc(reward, lang))
        GameMsg.sendPrivate(FISH_GAMEID, senderUserId, 0, message)
Exemple #29
0
 def doPromoteCodeCheck(cls, gameId, userId, clientId, action, promoteCode):
     '''
     验证兑换码ID,有效则获取用户手机绑定信息,若绑定手机,则发送奖励,并更新用户状态。若未绑定手机,则更新用户状态,返回未绑定手机code
     '''
     conf = hallconf.getNeiTuiGuangConf(clientId)
     if not conf:
         ftlog.error('neituiguang doGetUserState conf not found gameId=', gameId, 'userId=', userId, 'clientId=',
                     clientId, 'action=', action)
         return
     mo = MsgPack()
     userstate = gamedata.getGameAttr(userId, gameId, cls.attrname_state)
     if userstate == 2:
         NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, '已经领奖成功', mo)
     else:
         promoteCode = cls.intPromoteCode(promoteCode)
         if promoteCode == -1 or userId == promoteCode:
             NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo)
         else:
             userdata.checkUserData(promoteCode)
             createTime = userdata.getAttr(promoteCode, 'createTime')
             if createTime == None:
                 NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo)
             else:
                 olduser = cls.isOldUser(promoteCode, gameId, createTime, conf)
                 if not olduser:
                     NeiTuiGuangProtocolBuilder.buildBasicInfo(1, action, cls.getprize(gameId, 1, conf), mo)
                 else:
                     gamedata.setGameAttr(userId, gameId, cls.attrname_promotecode, promoteCode)  # 记录兑换码
                     gamedata.setGameAttr(userId, gameId, cls.attrname_state, 1)  # 已输入兑换码
                     bindmobile = userdata.getAttr(userId, 'bindMobile')
                     if cls.bindOk(bindmobile):
                         NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, '验证成功', mo)
                     else:
                         NeiTuiGuangProtocolBuilder.buildBasicInfo(2, action, cls.getprize(gameId, 2, conf), mo)
         return mo
Exemple #30
0
def addShareInvitedUserId(shareUserId, invitedUserId, isNewUser=False):
    """
    添加分享邀请人信息
    :param shareUserId: 分享卡片的分享者
    :param invitedUserId: 点击卡片的被邀请者
    :param isNewUser: 是否为新用户
    """
    inviteCount = weakdata.getDayFishData(shareUserId, "inviteCount", 0)
    if inviteCount < config.getCommonValueByKey("inviteLimitCount", 99999):
        if not isNewUser:
            inviteOldUserCount = weakdata.getDayFishData(shareUserId, "inviteOldUserCount", 0)
            if inviteOldUserCount > config.getCommonValueByKey("inviteLimitOldCount", 99999):
                return
            weakdata.incrDayFishData(shareUserId, "inviteOldUserCount", 1)
        inviteList = gamedata.getGameAttrJson(shareUserId, FISH_GAMEID, GameData.inviteList, [])
        inviteId = gamedata.incrGameAttr(shareUserId, FISH_GAMEID, GameData.inviteId, 1)
        inviteData = {
            "inviteId": inviteId,
            "userId": invitedUserId,
            "inviteTime": int(time.time()),
            "isNewUser": isNewUser,
            "isAppUser": 1 if util.isAppClient(invitedUserId) else 0
        }
        inviteList.append(inviteData)
        gamedata.setGameAttr(shareUserId, FISH_GAMEID, GameData.inviteList, json.dumps(inviteList))
        weakdata.incrDayFishData(shareUserId, "inviteCount", 1)
        module_tip.addModuleTipEvent(shareUserId, "invite", inviteId)
        getShareTaskInfo(shareUserId)
        from newfish.game import TGFish
        from newfish.entity.event import InvitedFinishEvent
        event = InvitedFinishEvent(shareUserId, FISH_GAMEID)
        TGFish.getEventBus().publishEvent(event)
Exemple #31
0
def recordRoomType(userId, typeName):
    """
    记录上次游戏房间类型
    """
    if typeName in [config.FISH_NORMAL, config.FISH_FRIEND]:
        gamedata.setGameAttr(userId, FISH_GAMEID, GameData.lastRoomType, typeName)
    return typeName
def addProgress(userId, taskLevel):
    """
    增加任务进度
    """
    taskIds = []
    returnerMission = getReturnerMissionData(userId)
    if returnerMission:
        # 未解锁的任务进度为最后一个已解锁的任务进度
        notUnlockedProgress = 0
        for taskConf in config.getReturnerMissionConf("tasks"):
            if taskConf["taskId"] in returnerMission["tasks"]:
                taskData = returnerMission["tasks"][taskConf["taskId"]]
                if taskData["state"] == 1:
                    taskData["progress"] += taskLevel
                    taskData["progress"] = min(taskData["progress"], taskConf["value"])
                    notUnlockedProgress = taskData["progress"]
                    if taskData["progress"] >= taskConf["value"]:
                        taskData["state"] = 2
                        taskData["progress"] = taskConf["value"]
                elif taskData["state"] == 0:
                    taskData["progress"] = max(taskData["progress"], notUnlockedProgress)
                if taskData["state"] == 2:
                    taskIds.append(taskConf["taskId"])
        gamedata.setGameAttr(userId, FISH_GAMEID, GameData.returnerMission, json.dumps(returnerMission))
    taskIds and module_tip.addModuleTipEvent(userId, "returnerMission", taskIds)
Exemple #33
0
def getGlobal(gameId, userId, pageNo=1):
    """
    已废弃,待删除
    取得当前用户的全局未读私信的内容
    """
    maxMsgId = daobase.executeMixCmd('HGET', 'msg',
                                     'msg.id.max.' + str(gameId))
    readMaxId = gamedata.getGameAttrs(userId, gameId, 'msg.id.global')
    rediskey = 'msg:' + str(gameId)

    maxMsgId, readMaxId = strutil.parseInts(maxMsgId, readMaxId)
    msglist = []
    maxId = readMaxId
    if pageNo < 1:
        pageNo = 1
    lstart = (pageNo - 1) * 20
    lend = lstart + 20 - 1
    datas = daobase.executeMixCmd('LRANGE', rediskey, lstart, lend)
    count = 0
    if datas:
        for msgstr in datas:
            msg = strutil.loads(msgstr, ignoreException=True)
            if msg:
                maxId = max(maxId, msg['id'])
                msglist.append(msg)
                count += 1
    if maxId > readMaxId:
        gamedata.setGameAttr(userId, gameId, 'msg.id.global', maxId)
    return {
        'count': count,
        'maxId': maxMsgId,
        'readId': readMaxId,
        'pageNo': pageNo,
        'list': msglist
    }
Exemple #34
0
    def handleEvent(cls, event):
        try:
            gameId = 6
            userId = event.userId
            conf = dizhuconf.getActivityConf("huiyuan_360")

            if not cls.clientCheck(gameId, userId, conf):
                return

            if not cls.dateCheck(gameId, userId, conf):
                return

            data = gamedata.getGameAttrJson(userId, gameId, cls.attr_act, {})
            now = datetime.now()
            now_day = '%d%02d%02d' % (now.year, now.month, now.day)

            choujiang_round = conf.get("choujiang_round", [])

            if isinstance(event, EventUserLogin):
                if (not data) or (now_day != data["date"]):
                    data = {
                        "round": 0,
                        "date": now_day,
                        "all_count": len(choujiang_round),
                        "current_count": 0,
                        "get_count": 0
                    }
            else:
                if not data:
                    data = {
                        "round": 1,
                        "date": now_day,
                        "all_count": len(choujiang_round),
                        "current_count": 0,
                        "get_count": 0
                    }
                else:
                    if now_day == data["date"]:
                        data["round"] += 1
                        if data["round"] in choujiang_round:
                            data["current_count"] += 1
                    else:
                        data = {
                            "round": 1,
                            "date": now_day,
                            "all_count": len(choujiang_round),
                            "current_count": 0,
                            "get_count": 0
                        }
                        if data["round"] in choujiang_round:
                            data["current_count"] += 1

            ftlog.debug("choujiang360 gameId=", gameId, "userId=", userId,
                        "data=", data)
            gamedata.setGameAttr(userId, gameId, cls.attr_act,
                                 json.dumps(data))

        except:
            ftlog.exception()
def sendGrandPrizeReward(roomId, tableId, userId, fId, coinCount, level,
                         seatId, fpMultiple):
    """
    发放巨奖奖励
    """
    try:
        rewards = [{"name": config.CHIP_KINDID, "count": coinCount}]
        room = gdata.rooms()[roomId]
        table = room.maptable[tableId]
        player = table.getPlayer(userId)

        msg = MsgPack()
        msg.setCmd("getGrandPrizeRewards")
        msg.setResult("gameId", FISH_GAMEID)
        msg.setResult("userId", userId)
        msg.setResult("fId", fId)
        msg.setResult("rewards", rewards)
        msg.setResult("level", level)
        msg.setResult("seatId", seatId)
        msg.setResult("fpMultiple", fpMultiple)
        GameMsg.sendMsg(msg, table.getBroadcastUids())

        if player:
            for bigRoomId in config.getGrandPrizeConf().get("roomIds", []):
                player.fireCost[str(bigRoomId)] = 0
            name = player.name
            player.addTableChip(coinCount, "BI_NFISH_GRAND_PRIZE")
            player.totalGainChip += coinCount
            # 深海巨奖触发幸运降临
            table.checkBigPrize(player,
                                coinCount // fpMultiple,
                                coinCount,
                                fpMultiple,
                                isGrandPriz=True)
        else:
            from poker.entity.dao import gamedata
            from newfish.entity.redis_keys import GameData
            fireCost = gamedata.getGameAttrJson(userId, FISH_GAMEID,
                                                GameData.fireCost, {})
            for bigRoomId in config.getGrandPrizeConf().get("roomIds", []):
                fireCost[str(bigRoomId)] = 0
            gamedata.setGameAttr(userId, FISH_GAMEID, GameData.fireCost,
                                 json.dumps(fireCost))
            name = util.getNickname(userId)
            util.addRewards(userId, rewards, "BI_NFISH_GRAND_PRIZE", roomId)

        leds = [
            "ID_LED_GRAND_PRIZE_1", "ID_LED_GRAND_PRIZE_2",
            "ID_LED_GRAND_PRIZE_3"
        ]
        if len(leds) > level >= 0:
            lang = util.getLanguage(userId)
            msg = config.getMultiLangTextConf(leds[level], lang=lang) % \
                  (name, config.getMultiLangTextConf(table.runConfig.title, lang=lang), util.formatScore(coinCount, lang=lang))
            user_rpc.sendLed(FISH_GAMEID, msg, id=leds[level], lang=lang)
    except Exception as e:
        ftlog.error("sendGrandPrizeReward", roomId, tableId, userId, fId,
                    coinCount, traceback.format_exc())
    return 0
Exemple #36
0
 def saveVipGiftStatus(self, userId, vipGiftStatus):
     '''
     保存用户VIP礼包状态
     @param userId: 哪个用户
     @param vipGiftStatus: 用户VIP礼包状态
     '''
     jstr = json.dumps(vipGiftStatus.giftStateMap)
     pkgamedata.setGameAttr(userId, 9999, 'vip.gift.states', jstr)
Exemple #37
0
 def saveVipGiftStatus(self, userId, vipGiftStatus):
     '''
     保存用户VIP礼包状态
     @param userId: 哪个用户
     @param vipGiftStatus: 用户VIP礼包状态
     '''
     jstr = json.dumps(vipGiftStatus.giftStateMap)
     pkgamedata.setGameAttr(userId, 9999, 'vip.gift.states', jstr)
Exemple #38
0
def updateHistoryClientIdsIfNeed(userId, gameId, numClientId):
    clientIds = getHistoryClientIds(userId, gameId)
    if not clientIds or clientIds[-1] != numClientId:
        clientIds.append(numClientId)
        if len(clientIds) > 2:
            clientIds = clientIds[-2:]
        jstr = strutil.dumps(clientIds)
        gamedata.setGameAttr(userId, gameId, 'hisClientIds', jstr)
Exemple #39
0
    def onRoomCreateCustomTable(self, gameId, msg):
        '''在GR处理自建桌逻辑
        '''
        if ftlog.is_debug():
            ftlog.debug("<< |msg", msg, caller=self)

        userId = msg.getParam("userId")
        selectedRoomOptions = msg.getParam("selectedRoomOptions")
        if not selectedRoomOptions:
            return
        customConfVer = msg.getParam("customConfVer")
        if customConfVer != difangConf.getCustomRoomConf(gameId, 'ver'):
            ftlog.warn("onRoomCreateCustomTable confVer error! |msg:", msg, caller=self)
            return
        gameRoundN = selectedRoomOptions.get("gameRoundN")
        if not gameRoundN:
            return
        roomId = msg.getParam("roomId")
        room = gdata.rooms()[roomId]
        clientId = msg.getParam("clientId")

        needRoomCardN = difangConf.getCustomRoomConf(gameId, 'roomCardNCost').get(str(gameRoundN), -1)
        if needRoomCardN == -1:
            tips = difangConf.getCustomRoomConf(difangConf.GAME_ID, 'err_tips')
            tip = tips[self.CREATE_CUSTOM_TABLE_ERR_NO_NOT_ALLOW]
            TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(tip, True))
            ftlog.warn("onRoomCreateCustomTable get needRoomCardN error! |msg:", msg, caller=self)
            self.sendGameCreateCustomTableRes(0, userId)
            return

        if ftlog.is_debug():
            ftlog.debug("|userId, gameId, customConfVer, gameRoundN, needRoomCardN:",
                        userId, gameId, customConfVer, gameRoundN, needRoomCardN, caller=self)

        if needRoomCardN > 0 and not self.isCardEnough(gameId, userId, needRoomCardN, clientId):
            tips = difangConf.getCustomRoomConf(difangConf.GAME_ID, 'err_tips')
            tip = tips[self.CREATE_CUSTOM_TABLE_ERR_NO_NOT_ENOUGH]
            TodoTaskHelper.sendTodoTask(gameId, userId, TodoTaskShowInfo(tip, True))
            self.sendGameCreateCustomTableRes(0, userId)
            return

        tableId = room.getIdleTableId()
        if not tableId:
            ftlog.error("there are no idle tables!", "|userId, roomId:", userId, room.roomId)
            return

        ftId = self.assignFriendTableId(gameId, tableId)

        ftlog.info("onRoomCreateCustomTable |userId, tableId, ftId:", userId, tableId, ftId, caller=self)
        self.sendGameCreateCustomTableRes(ftId, userId)
        gamedata.setGameAttr(userId, gameId, "selectedRoomOptions", json.dumps(selectedRoomOptions))
        gamedata.setGameAttr(userId, gameId, "customConfVer", customConfVer)

        shadowRoomId = tableId / 10000
        room.querySitReq(userId, shadowRoomId, tableId, clientId,
                         extParams={"selectedRoomOptions": selectedRoomOptions, "ftId": ftId})
Exemple #40
0
def _saveSubMemberStatus(userId, status):
    d = {}
    if status.subDT:
        d['subTime'] = int(time.mktime(status.subDT.timetuple()))
    if status.deliveryDT:
        d['deliveryTime'] = int(time.mktime(status.deliveryDT.timetuple()))
    if status.expiresDT:
        d['expiresTime'] = int(time.mktime(status.expiresDT.timetuple()))
    jstr = json.dumps(d)
    gamedata.setGameAttr(userId, HALL_GAMEID, 'submember', jstr)
    def _doExchange(self, userId, gameId, clientId, activityId, excode):
        if len(excode) != 16 and len(excode) != 5 and len(excode) != 18:
            self.sendTodoTask(gameId, userId, "兑换码错误!")
            return {"exchangeInfo": "兑换码错误!"}
        if len(excode) == 5:
            rdskey = activityId
        else:
            excode = excode.upper()
            rdskey = excode[0:6]
        ftlog.debug('this exchange rdskey = ', rdskey,
                    'this exchange clientId = ', clientId)
        result_, errdes_, unique_ = self.__commonCheck(rdskey, clientId)
        if result_ != 0:
            self.sendTodoTask(gameId, userId, errdes_)
            return {"exchangeInfo": errdes_}
        result_, errdes_ = self.__exchange(rdskey, userId, excode, unique_)
        if result_ != 0:
            self.sendTodoTask(gameId, userId, errdes_)
            return {"exchangeInfo": errdes_}
        _rewards = self.__getReward(rdskey, userId, gameId, activityId, excode)

        if len(excode) == 18:
            # 将用户Id和推广人Id进行绑定
            common_ = daobase.executeMixCmd('HGET', 'excodeinfo:' + rdskey, 'common')
            try:
                common_ = json.loads(common_)
            except:
                return {}
            nowPromoteId = pkgamedata.getGameAttr(userId, gameId, 'promoteId') or 0
            ftlog.debug('__getReward.userId=', userId,
                        'gameId=', gameId,
                        'common_=', common_,
                        'nowPromoteId=', nowPromoteId)
            if int(nowPromoteId) <= 0 and int(userId) != int(common_.get('promoteId', 0)):
                pkgamedata.setGameAttr(userId, gameId, 'promoteId', common_.get('promoteId', 0))

        resultInfo = '恭喜您兑换成功,获得:' + _rewards
        self.sendTodoTask(gameId, userId, resultInfo)
        # 兑换码使用成功,记录在用户里
        messageUser = daobase.executeMixCmd('HGET', 'userID:' + str(userId), 'common')
        if isinstance(messageUser, (str, unicode)):
            messageUser = json.loads(messageUser)
        else:
            messageUser = {}
        if 'excode' not in messageUser:
            messageUser = {
                'userId': userId,
                'excode': [excode],
                'time': [datetime.now().strftime('%Y-%m-%d %H:%M:%S')]
            }
        else:
            messageUser['excode'].append(excode)
            messageUser['time'].append(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        daobase.executeMixCmd('HSET', 'userID:' + str(userId), 'common', json.dumps(messageUser))
        return {"exchangeInfo": resultInfo}
Exemple #42
0
    def setNotifyInfo(self, userId, notifyInfo, module):
        info = {}
        info['shareId'] = self.shareId
        info['info'] = notifyInfo
        info['module'] = module

        infoStr = json.dumps(info)
        if ftlog.is_debug():
            ftlog.debug('HallShare.setNotifyInfo : ', infoStr)

        pkgamedata.setGameAttr(userId, HALL_GAMEID, 'shareInfo', infoStr)
Exemple #43
0
    def saveCustomTableRecordInfos(self, table):
        '''将房间所有牌局记录索引存入redis
        '''
        if table.gamePlay.gameSeq == 0:
            return

        playerInfos = []
        for player in DiFangPlayersHelper.getSitPlayers(table):
            playerInfo = {}
            playerInfo['userId'] = player.userId
            playerInfo['name'] = player.name
            playerInfo['tableChips'] = player.tableChips
            playerInfos.append(playerInfo)

        if ftlog.is_debug():
            ftlog.debug("playerInfos:", playerInfos, caller=self)

        record = {}
        record["ftId"] = table.ftId
        record["gameSeq"] = table.gamePlay.gameSeq
        record['tableRecordInfos'] = table.tableRecordInfos
        record['playerInfos'] = playerInfos
        # timestamp = pktimestamp.getCurrentTimestamp()
        # record['time'] = pktimestamp.timestamp2timeStr(timestamp) # 使用的UTC时区
        record['time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        for player in DiFangPlayersHelper.getSitPlayers(table):
            if player.tableChips > 0:
                record["res"] = "win"
            elif player.tableChips == 0:
                record["res"] = "drawn"
            else:
                record["res"] = "lose"

            if ftlog.is_debug():
                ftlog.debug("|tableId, userId, record:", table.tableId, player.userId, record, caller=self)

            records = gamedata.getGameAttr(player.userId, table.gameId, "customTableRecords")
            if records:
                records = json.loads(records)
            else:
                records = []
            records.insert(0, record)

            if len(records) > 10:
                del records[-1]

            if ftlog.is_debug():
                ftlog.debug("|tableId, userId, records:", table.tableId, player.userId, records, caller=self)

            gamedata.setGameAttr(player.userId, table.gameId, "customTableRecords", json.dumps(records))
Exemple #44
0
def _saveStatus(status):
    d = {
        'ut': dateToStr(status.curDate),
        'cl': [dateToStr(d) for d in status.checkinDateList],
        'scl': [dateToStr(d) for d in status.supplementCheckinDateList],
        'rdl': status.rewardDaysList
    }
    jstr = json.dumps(d)
    ftlog.debug('_saveStatus ut =', d['ut']
                , 'cl =', d['cl']
                , 'scl =', d['scl']
                , 'rdl =', d['rdl'])
    gamedata.setGameAttr(status.userId, HALL_GAMEID, 'monthCheckin', jstr)
    gamedata.setGameAttr(status.userId, HALL_GAMEID, 'checkinVer', 1)
Exemple #45
0
 def countGame(self):
     for player in DiFangPlayersHelper.getPlayingPlayers(self):
         userId = player.userId
         # play_game_count
         playGameCount = gamedata.getGameAttr(userId, self.gameId, 'play_game_count')
         if not playGameCount:
             playGameCount = 0
         playGameCount += 1
         gamedata.setGameAttr(userId, self.gameId, 'play_game_count', playGameCount)
         ftlog.info("countGame userId=", userId, "play_game_count=", playGameCount)
         # win_game_count
         if self.gamePlay.pot.allwinchips[player.seatIndex] > 0:
             winGameCount = gamedata.getGameAttr(userId, self.gameId, 'win_game_count')
             if not winGameCount:
                 winGameCount = 0
             winGameCount += 1
             gamedata.setGameAttr(userId, self.gameId, 'win_game_count', winGameCount)
             ftlog.info("countGame userId=", userId, "win_game_count=", winGameCount)
Exemple #46
0
 def dosendChipToUser(self, userId, gameId, clientId):
     # 添加绑定
     nowBindPone = gamedata.getGameAttr(userId, gameId, 'bindReward1')
     if not nowBindPone or nowBindPone < 1:
         gamedata.setGameAttr(userId, gameId, 'bindReward1', 1)
     else:
         from poker.entity.biz.exceptions import TYBizException
         raise TYBizException(-1, '重复绑定')
     # 发金币
     ftlog.info('cmd game action bindPhone userId =', userId)
     from poker.entity.dao import userchip, daoconst
     userchip.incrChip(userId, gameId, 10000, daoconst.CHIP_NOT_ENOUGH_OP_MODE_CLEAR_ZERO, 'BIND_PHONE', 0, clientId)
     datachangenotify.sendDataChangeNotify(gameId, userId, 'chip')
     # 消息推送
     from poker.entity.biz.message import message
     msg = '恭喜您绑定手机成功,赠送您10000金币'
     message.send(gameId, message.MESSAGE_TYPE_PRIVATE, userId, msg)
     # 更新小红点
     datachangenotify.sendDataChangeNotify(gameId, userId, ['free', 'promotion_loc'])
     TGHall.getEventBus().publishEvent(UserBindPhoneEvent(userId, gameId))
Exemple #47
0
 def saveRecord(cls, gameId, userId, matchId, record):
     gamedata.setGameAttr(userId, gameId, cls.__buildField(matchId), json.dumps(record.toDict()))
Exemple #48
0
def saveStatus(status):
    d = status.encodeToDict({})
    jstr = json.dumps(d)
    gamedata.setGameAttr(status.userId, HALL_GAMEID, NeituiguangSimpleStatus.NEW_KEY, jstr)
Exemple #49
0
 def userStateRoute(cls, gameId, userId, userstate, attr):
     if userstate == 1:
         gamedata.setGameAttr(userId, gameId, cls.attrname_state, 2)
         return 0
     else:
         return -1
Exemple #50
0
 def doCancelCodeCheck(cls, gameId, userId, clientId, action):
     mo = MsgPack()
     state = 2
     gamedata.setGameAttr(userId, gameId, cls.attrname_state, state)
     NeiTuiGuangProtocolBuilder.buildBasicInfo(0, action, '取消成功', mo)
     return mo
Exemple #51
0
def _saveStatus(status):
    d = status.encodeToDict({})
    jstr = json.dumps(d)
    gamedata.setGameAttr(status.userId, HALL_GAMEID, 'neituiguang', jstr)
Exemple #52
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
Exemple #53
0
def setTipCount(userId, tipModuleName, count, gameId):
    tipModule = findTipModule(tipModuleName)
    if not tipModule:
        ftlog.error("not find tipModule:", tipModuleName)
        return
    pkgamedata.setGameAttr(userId, 9999, _buildModuleTipKey(tipModule, gameId, userId), count)
Exemple #54
0
    def doCreateTable(self, userId, gameId, clientId, roomId0, tableId0, playMode):
        """
        房主创建牌桌
        """
        if not playMode:
            ftlog.error('game_handler, cat not create table without playMode...')

        loc = onlinedata.checkUserLoc(userId, clientId, gameId)
        lgameId, lroomId, ltableId, lseatId = loc.split('.')
        lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId)
        if lgameId > 0 and lroomId > 0 and ltableId > 0 and lseatId >= 0:
            ftlog.warn('create_table error, user in table', lgameId, lroomId, ltableId, lseatId)
            sendPopTipMsg(userId, "请稍候,正在进桌...")
            config = {
                "type": "quickstart",
                "pluginParams": {
                    "roomId": lroomId,
                    "tableId": ltableId,
                    "seatId": lseatId
                }
            }
            todotask = TodoTaskEnterGameNew(lgameId, config)
            mo = MsgPack()
            mo.setCmd('todo_tasks')
            mo.setResult('gameId', gameId)
            mo.setResult('pluginId', lgameId)
            mo.setResult('userId', userId)
            mo.setResult('tasks', TodoTaskHelper.encodeTodoTasks(todotask))
            router.sendToUser(mo, userId)
        elif self._canEnterGame(userId, gameId):
            # 保存建桌时间戳
            gamedata.setGameAttr(userId, gameId, 'createTableTime', pktimestamp.getCurrentTimestamp())

            msg = runcmd.getMsgPack()
            itemParams = msg.getParam("itemParams")
            # cardCount为总局数
            if "cardCount" in itemParams:
                cardCountId = itemParams.get('cardCount', 0)
                cardCountConfig = majiang_conf.getCreateTableConfig(gameId, playMode, 'cardCount', cardCountId)
                fangka_count = cardCountConfig.get('fangka_count', 1)
                ftlog.debug('MajiangCreateTable.create_table fangka_count:', fangka_count)

                playerCount = 4
                playerTypeId = itemParams.get('playerType', 1)
                if playerTypeId:
                    playerTypeConfig = majiang_conf.getCreateTableConfig(gameId, playMode, 'playerType', playerTypeId)
                    playerCount = playerTypeConfig.get('count', 4)
                    ftlog.debug('MajiangCreateTable.create_table playerCount:', playerCount)

                msg.setParam('isCreateTable', 1)  # 标记创建的桌子是 自建桌
                from poker.entity.game.rooms.room import TYRoom
                roomId, checkResult = MajiangCreateTable._chooseCreateRoom(userId, gameId, playMode, playerCount)
                ftlog.debug('MajiangCreateTable._chooseCreateRoom roomId:', roomId, ' checkResult:', checkResult)

                if checkResult == TYRoom.ENTER_ROOM_REASON_OK:
                    msg = runcmd.getMsgPack()
                    msg.setCmdAction("room", "create_table")
                    msg.setParam("roomId", roomId)
                    msg.setParam("itemParams", itemParams)
                    msg.setParam('needFangka', fangka_count)
                    ftlog.debug('MajiangCreateTable._chooseCreateRoom send message to room:', msg)

                    router.sendRoomServer(msg, roomId)
                else:
                    sendPopTipMsg(userId, "暂时无法创建请稍后重试")
            else:
                sendPopTipMsg(userId, "暂时无法创建请稍后重试")

            if router.isQuery():
                mo = runcmd.newOkMsgPack(1)
                router.responseQurery(mo, '', str(userId))
        else:
            ftlog.info('majiang2 game_handler, ignore enter game request...')
Exemple #55
0
def SetData(user_id, key, value):
    """
    保存数据到指定用户
    """
    gamedata.setGameAttr(user_id, __GAME_ID, key, value)
    return value
Exemple #56
0
def _onOrderDelivery(event):
    from hall.entity import hallitem
    nowDT = datetime.now()
    order = event.orderDeliveryResult.order

    if ((_conf.startDT and nowDT < _conf.startDT)
        or (_conf.endDT and nowDT >= _conf.endDT)):
        if ftlog.is_debug():
            ftlog.debug('buy_send_gift._onOrderDelivery outofTime userId=', event.userId,
                        'orderId=', order.orderId,
                        'productId=', order.productId,
                        'nowDT=', nowDT.strftime('%Y-%m-%d %H:%M:%S'),
                        'startDT=', _conf.startDT.strftime('%Y-%m-%d %H:%M:%S'),
                        'endDT=', _conf.endDT.strftime('%Y-%m-%d %H:%M:%S'))
        return

    giftConf = _conf.findGiftConf(order.productId)
    if not giftConf:
        if ftlog.is_debug():
            ftlog.debug('buy_send_gift._onOrderDelivery noGiftConf userId=', event.userId,
                        'orderId=', order.orderId,
                        'productId=', order.productId,
                        'orderClientId=', order.clientId)
        return

    hallGameId = strutil.getGameIdFromHallClientId(order.clientId)
    if hallGameId not in giftConf.gameIds:
        if ftlog.is_debug():
            ftlog.debug('buy_send_gift._onOrderDelivery notInGameIds userId=', event.userId,
                        'orderId=', order.orderId,
                        'productId=', order.productId,
                        'giftConf=', giftConf.conf,
                        'orderClientId=', order.clientId,
                        'hallGameId=', hallGameId,
                        'gameIds=', giftConf.gameIds)
        return

    count = 0
    if giftConf.maxCount >= 0:
        limitD = gamedata.getGameAttrJson(order.userId, hallGameId, 'act.buy_send_gift', {})
        count = limitD.get(order.productId, 0)
        if count + 1 > giftConf.maxCount:
            ftlog.info('buy_send_gift._onOrderDelivery overLimit userId=', event.userId,
                       'orderId=', order.orderId,
                       'productId=', order.productId,
                       'giftConf=', giftConf.conf if giftConf else None,
                       'orderClientId=', order.clientId,
                       'count=', count,
                       'maxCount=', giftConf.maxCount)
            return
        count += 1
        limitD[order.productId] = count
        gamedata.setGameAttr(order.userId, hallGameId, 'act.buy_send_gift', strutil.dumps(limitD))

    assetList = None
    if giftConf.giftContent:
        userAssets = hallitem.itemSystem.loadUserAssets(order.userId)
        # def sendContent(self, gameId, content, count, ignoreUnknown, timestamp, eventId, intEventParam):
        assetList = userAssets.sendContent(hallGameId, giftConf.giftContent, 1,
                                           True, pktimestamp.getCurrentTimestamp(),
                                           'ACTIVITY_REWARD',
                                           10043)
    changedDataNames = TYAssetUtils.getChangeDataNames(assetList) if assetList else set()

    contentStr = TYAssetUtils.buildContentsString(assetList) if assetList else ''
    if giftConf.mail:
        mail = strutil.replaceParams(giftConf.mail, {'gotContent': contentStr, 'price': order.product.price})
        message.send(hallGameId, message.MESSAGE_TYPE_SYSTEM, order.userId, mail)
        changedDataNames.add('message')
    if changedDataNames:
        datachangenotify.sendDataChangeNotify(HALL_GAMEID, order.userId, changedDataNames)
    ftlog.info('buy_send_gift._onOrderDelivery sendGift userId=', event.userId,
               'orderId=', order.orderId,
               'productId=', order.productId,
               'giftConf=', giftConf.conf if giftConf else None,
               'orderClientId=', order.clientId,
               'count=', count,
               'maxCount=', giftConf.maxCount,
               'assetList=', [(a[0].kindId, a[1]) for a in assetList] if assetList else None)
Exemple #57
0
    def doCreateTable(self, userId, gameId, clientId, roomId0, tableId0, playMode, hasRobot = 0):
        
        #临时硬编码,解决91晃晃提审问题
        if gameId==791 and playMode=="queshou-lianjiang" and clientId=="IOS_3.901_weixin.appStore,weixinPay.0-hall791.queshou.iostsljmj":
            hasRobot=1
	if gameId == 790 and playMode == 'luosihu-luosihuts' and clientId=="IOS_3.901_weixin.appStore,weixinPay.0-hall790.laodao.iostsxjmj":
	    hasRobot=1
        """房主创建牌桌"""
        if not playMode:
            ftlog.error('game_handler, cat not create table without playMode...')
        
        loc = onlinedata.checkUserLoc(userId, clientId, gameId)
        lgameId, lroomId, ltableId, lseatId = loc.split('.')
        lgameId, lroomId, ltableId, lseatId = strutil.parseInts(lgameId, lroomId, ltableId, lseatId)
        if lgameId > 0 and lroomId > 0 and ltableId > 0 and lseatId >=0:
            ftlog.warn('create_table error, user in table',lgameId, lroomId, ltableId, lseatId)
            sendPopTipMsg(userId, "请稍候,正在进桌...")
            config = {
                      "type":"quickstart",
                      "pluginParams": {
                          "roomId": lroomId,
                          "tableId": ltableId,
                          "seatId": lseatId
                          }
                      }
            todotask = TodoTaskEnterGameNew(lgameId, config)
            mo = MsgPack()
            mo.setCmd('todo_tasks')
            mo.setResult('gameId', gameId)
            mo.setResult('pluginId', lgameId)
            mo.setResult('userId', userId)
            mo.setResult('tasks', TodoTaskHelper.encodeTodoTasks(todotask))
            router.sendToUser(mo, userId)
        elif self._canEnterGame(userId, gameId):
            # 保存建桌时间戳
            gamedata.setGameAttr(userId, gameId, 'createTableTime', pktimestamp.getCurrentTimestamp())
            
            msg = runcmd.getMsgPack()
            itemParams = msg.getParam("itemParams")
            
            playerCount = 4
            playerTypeId = itemParams.get(MFTDefine.PLAYER_TYPE, 1)
            playerTypeConfig = majiang_conf.getCreateTableConfig(gameId, playMode, MFTDefine.PLAYER_TYPE, playerTypeId)
            if not playerTypeConfig:
                sendPopTipMsg(userId, '人数配置有误,请稍后重试')
                return
            
            playerCount = playerTypeConfig.get('count', 4)
            ftlog.debug('MajiangCreateTable.create_table playerCount:', playerCount)
            cardCountKey = playerTypeConfig.get(MFTDefine.CARD_COUNT, MFTDefine.CARD_COUNT)

            cardCountId = itemParams.get(cardCountKey, 0)
            cardCountConfig = majiang_conf.getCreateTableConfig(gameId, playMode, cardCountKey, cardCountId)
            if not cardCountConfig:
                sendPopTipMsg(userId, '房卡配置有误,请稍后重试')
                return
            
            if hasRobot == 1 and 'hasRobot' in cardCountConfig:
                cardCountConfig = cardCountConfig.get('hasRobot', {})
                ftlog.debug('MajiangCreateTable.create_table hasRobot == 1:')
            fangka_count = cardCountConfig.get('fangka_count', 1)
            ftlog.debug('MajiangCreateTable.create_table fangka_count:', fangka_count
                        , ' cardCountConfig:', cardCountConfig)
            
            msg.setParam('isCreateTable', 1) #标记创建的桌子是 自建桌
            from poker.entity.game.rooms.room import TYRoom
            '''
            根据五个因素筛选合适的房间
            1)gameId         游戏ID
            2)playMode       游戏玩法
            3)playerCount    玩家个数
            4)hasRobot       是否有机器人
            5)itemId         房卡道具
            '''
            itemId = hall_fangka.queryFangKaItem(gameId, userId, clientId)
            if itemId:
                ftlog.debug('MajiangCreateTable._chooseCreateRoom fangKa itemId:', itemId)
            roomId, checkResult = MajiangCreateTable._chooseCreateRoom(userId, gameId, playMode, playerCount, hasRobot, itemId)
            ftlog.debug('MajiangCreateTable._chooseCreateRoom roomId:', roomId, ' checkResult:', checkResult)

            if checkResult==TYRoom.ENTER_ROOM_REASON_OK:
                msg = runcmd.getMsgPack()
                msg.setCmdAction("room", "create_table")
                msg.setParam("roomId", roomId)
                msg.setParam("itemParams", itemParams)
                msg.setParam('needFangka', fangka_count)
                ftlog.debug('MajiangCreateTable._chooseCreateRoom send message to room:', msg)

                router.sendRoomServer(msg, roomId)
            else:
                sendPopTipMsg(userId, "暂时无法创建请稍后重试")
                
            if router.isQuery() :
                mo = runcmd.newOkMsgPack(1)
                router.responseQurery(mo, '', str(userId))
        else:
            ftlog.info('majiang2 game_handler, ignore enter game request...')
Exemple #58
0
def _saveFiveStarRate(userId, fsRate):
    d = {'ver': fsRate.rateVersion, 'rateTime': fsRate.rateTime, 'popTime': fsRate.popTime}
    jstr = json.dumps(d)
    field = 'fivestar.%s' % (fsRate.channel['name'])
    gamedata.setGameAttr(userId, HALL_GAMEID, field, jstr)
Exemple #59
0
 def saveUserBenefitsData(self, userId, benefitsData):
     '''
     保存用户救济金配置
     '''
     jstr = json.dumps({'times': benefitsData.times, 'ut': benefitsData.updateTime})
     gamedata.setGameAttr(userId, 9999, 'benefits', jstr)