示例#1
0
def loadStatus(userId, timestamp):
    '''
    加载用户推广状态
    麻将先于大厅做过邀请有礼,从麻将merge数据
    '''
    d = None
    status = None
    try:
        # 优先迁移跑胡子的配置
        ftlog.debug('hall_simple_invite.loadStatus try load from paohuzi...')
        d = gamedata.getGameAttrJson(userId, 21, NeituiguangSimpleStatus.OLD_KEY)
        gamedata.delGameAttr(userId, 21, NeituiguangSimpleStatus.OLD_KEY)
        if not d:
            # 其次迁移麻将的配置
            ftlog.debug('hall_simple_invite.loadStatus try load from majiang...')
            d = gamedata.getGameAttrJson(userId, 7, NeituiguangSimpleStatus.OLD_KEY)
            gamedata.delGameAttr(userId, 7, NeituiguangSimpleStatus.OLD_KEY)

        if not d:
            # 使用大厅数据
            ftlog.debug('hall_simple_invite.loadStatus try load from hall at last...')
            d = gamedata.getGameAttrJson(userId, HALL_GAMEID, NeituiguangSimpleStatus.NEW_KEY)

        ftlog.debug('hall_simple_invite.loadStatus status:', d)
        if d:
            status = NeituiguangSimpleStatus(userId, timestamp).decodeFromDict(d)
    except:
        ftlog.error('invite.loadStatus userId=', userId, 'd=', d)

    if not status:
        status = NeituiguangSimpleStatus(userId, timestamp)

    return status
示例#2
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))
示例#3
0
 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
示例#4
0
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)
示例#5
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)
示例#6
0
def changeGunSkin(userId, gunId, skinId, mode):
    """
    切换火炮皮肤
    """
    if ftlog.is_debug():
        ftlog.debug("changeGunSkin, userId =", userId, "gunId =", gunId,
                    "skinId =", skinId, "mode =", mode)
    mo = MsgPack()
    mo.setCmd("gun_change_skin")
    mo.setResult("gameId", FISH_GAMEID)
    mo.setResult("userId", userId)
    mo.setResult("gunId", gunId)
    mo.setResult("skinId", skinId)
    mo.setResult("gameMode", mode)
    clientId = util.getClientId(userId)
    skins = config.getGunConf(gunId, clientId, mode=mode).get("skins")
    ownGunSkinSkinsKey = GameData.ownGunSkinSkins
    ownGunSkinSkins = gamedata.getGameAttrJson(userId, FISH_GAMEID,
                                               ownGunSkinSkinsKey, [])
    if skinId not in ownGunSkinSkins and skinId != skins[0]:
        mo.setResult("code", 1)  # 未获得
        router.sendToUser(mo, userId)
        return False
    if skinId not in skins:
        mo.setResult("code", 2)  # 皮肤不在该火炮下属的皮肤列表中
        router.sendToUser(mo, userId)
        return False
    equipGunSkin(userId, gunId, skinId, mode)
    mo.setResult("code", 0)
    router.sendToUser(mo, userId)
    return True
示例#7
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)
示例#8
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
示例#9
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)
示例#10
0
 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)])
示例#11
0
 def refreshOdds(self):
     """
     刷新动态概率数据
     """
     if self.table.typeName not in config.DYNAMIC_ODDS_ROOM_TYPE:
         return
     if not self.player or not self.player.userId:
         return
     if self.isProtectMode():
         return
     data = gamedata.getGameAttrJson(self.player.userId, FISH_GAMEID,
                                     GameData.dynamicOdds, {})
     oddsData = data.get(str(self.fishPool), [])
     if oddsData:
         self.loadDynamicOddsData(oddsData[WAVE_ID])
         self.waveIndex = oddsData[WAVE_INDEX]
         self.computeTargetCoins(oddsData[WAVE_RADIX])
         self.refreshTargetCoin()
         self.waveCoin = oddsData[WAVE_COIN]
     else:
         waveId = 6
         self.resetOdds(waveId)
     if ftlog.is_debug():
         ftlog.debug("DynamicOdds->refreshOdds->", "userId =",
                     self.player.userId, "chip =", self.chip, "waveId =",
                     self.waveId, "waveIndex =", self.waveIndex,
                     "targetCoins =", self.targetCoins, "waveCoin =",
                     self.waveCoin)
示例#12
0
def getTipValue(userId, moduleTip):
    """
    获取数据库的值
    """
    value = gamedata.getGameAttrJson(userId, FISH_GAMEID,
                                     _buildModuleTipKey(moduleTip), [])
    return value
示例#13
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())), []]))
示例#14
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
示例#15
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()
示例#16
0
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
示例#17
0
def getRoomMinigame(roomId, userId):
    """
    获取小游戏数据
    """
    bigRoomId, _ = util.getBigRoomId(roomId)
    miniGameData = gamedata.getGameAttrJson(userId, FISH_GAMEID, "miniGame",
                                            {})
    return miniGameData.get(str(bigRoomId))
示例#18
0
    def start(self):
        """
        触发美人鱼的馈赠
        """
        data = gamedata.getGameAttrJson(self.player.userId, FISH_GAMEID,
                                        "miniGame", {})
        roomData = data.get(str(self.bigRoomId))
        playTimes = data.get("history", {}).get(str(self.miniGameId), 0)
        reward = []
        # 第一次触发
        if playTimes == 0:
            reward.append(random.choice([1, 2]))
            tmp = []
            if reward[0] == 1:
                tmp.extend([1] * 2)
                tmp.extend([2] * 3)
            else:
                tmp.extend([2] * 2)
                tmp.extend([1] * 3)
            tmp.append(3)
            random.shuffle(tmp)
            reward.extend(tmp)
            reward.append(3)
        else:
            highP = self.highRewardProbb[1] - self.highRewardProbb[0]
            lowP = self.lowRewardProbb[1] - self.lowRewardProbb[0]
            m = lowP / highP
            m = 1 if m < 1 else m
            rand0 = random.randint(1, m + 1)
            if rand0 == 1:
                reward.append(1)
            else:
                reward.append(2)

            for i in range(11):
                randomx = random.randint(1, 100)
                if self.highRewardProbb[0] <= randomx <= self.highRewardProbb[
                        1]:
                    reward.append(1)
                elif self.lowRewardProbb[0] <= randomx <= self.lowRewardProbb[
                        1]:
                    reward.append(2)
                else:
                    reward.append(3)
        roomData["current"] = {
            "cardId": self.miniGameId,
            "reward": reward,
            "locs": []
        }
        if "history" not in data:
            data["history"] = {}
        if str(self.miniGameId) not in data["history"]:
            data["history"][str(self.miniGameId)] = 0
        data["history"][str(self.miniGameId)] += 1
        data[str(self.bigRoomId)] = roomData
        gamedata.setGameAttr(self.player.userId, FISH_GAMEID, "miniGame",
                             json.dumps(data))
        return {"reward": reward, "multi": roomData.get("multi", 0)}
示例#19
0
def _getContinuousDay(userId, giftId):
    """持续购买的天数"""
    _checkContinuosPurchase(userId, giftId)
    giftId = str(giftId)
    purchaseData = gamedata.getGameAttrJson(userId, FISH_GAMEID,
                                            GameData.continuousPurchase,
                                            {})  # 每日礼包连续购买记录
    continuousDay = purchaseData.get(giftId, [0, 0])[1]
    return continuousDay
示例#20
0
def _isBought(userId, giftId):
    """
    礼包是否已购买
    """
    giftId = int(giftId)
    boughtGift = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.buyLevelGift, [])
    if giftId in boughtGift:
        return 1
    return 0
示例#21
0
def _dealMail(userId, mailIds, mailSenderType):
    """
    领取邮件奖励
    :param mailType: 1为表示系统邮件,为2表示其他邮件
    """
    code = 0
    rewards = []
    curTime = int(time.time())
    _key = GameData.mailInfos if mailSenderType == MailSenderType.MT_SYS else GameData.userMailInfos
    mailInfos = gamedata.getGameAttrJson(userId, FISH_GAMEID, _key, [])
    commonRewards = []
    chestRewards = []
    try:
        for _mailInfo in mailInfos:
            expireTime = _mailInfo.get("expireTime")
            # 过期邮件不可领取.
            if expireTime and expireTime + 10 < curTime:
                continue
            if (not mailIds or _mailInfo["id"] in mailIds) and _mailInfo["state"] == MailState.Default:
                eventId = "BI_NFISH_MAIL_REWARDS"
                intEventParam = int(_mailInfo["type"])
                param0 = None
                if _mailInfo["type"] == MailRewardType.Present:
                    eventId = "ACCEPT_PRESENT_ITEM"
                    intEventParam = _mailInfo["userId"]
                elif _mailInfo["type"] in [MailRewardType.StarRank, MailRewardType.RobberyRank, MailRewardType.PoseidonRank]:
                    eventId = "BI_NFISH_RANKING_REWARDS"
                elif _mailInfo["type"] == MailRewardType.InviteReward:
                    param0 = _mailInfo["userId"]
                elif _mailInfo["type"] == MailRewardType.MatchReward:
                    eventId = "MATCH_REWARD"
                elif _mailInfo["type"] == MailRewardType.TreasureReward:
                    eventId = "BI_NFISH_TREASURE_REWARDS"
                elif _mailInfo["type"] == MailRewardType.FishCanReturn:
                    eventId = "BI_NFISH_FISH_CAN_RETURN"

                commonReward = []
                chestReward = []
                if _mailInfo["reward"]:
                    commonReward, chestReward, totalRewards = _getAllRewardInfo(userId, _mailInfo["reward"])
                    code = util.addRewards(userId, totalRewards, eventId, intEventParam, param01=param0)
                if code == 0:
                    _mailInfo["state"] = MailState.Received
                    commonRewards.extend(commonReward)
                    chestRewards.extend(chestReward)
                    # rewards.append({"commonReward": commonRewards, "chestRewards": chestRewards})
                elif code == 4:  # 没有奖励
                    code = 0
                    _mailInfo["state"] = MailState.Received
        rewards.append({"commonReward": commonRewards, "chestRewards": chestRewards})
    except Exception as e:
        ftlog.error("_dealMail error", userId, mailIds, mailSenderType, e)
    if ftlog.is_debug():
        ftlog.debug("_dealMail=====>userId =", userId, "rewards =", rewards, "mailSenderType =", mailSenderType)
    gamedata.setGameAttr(userId, FISH_GAMEID, _key, json.dumps(mailInfos))
    return code, rewards
示例#22
0
def _loadSubMemberStatus(userId):
    try:
        d = gamedata.getGameAttrJson(userId, HALL_GAMEID, 'submember', {})
        subDT = _decodeDT(d.get('subTime', -1))
        deliveryDT = _decodeDT(d.get('deliveryTime', -1))
        expiresDT = _decodeDT(d.get('expiresTime', -1))
        return SubMemberStatus(False, subDT, deliveryDT, None, expiresDT)
    except:
        ftlog.error()
        return SubMemberStatus(False, None, None, None, None)
示例#23
0
    def doRoomSigIn(self, roomId, userId, signinParams):
        msg = runcmd.getMsgPack()
        if ftlog.is_debug():
            ftlog.debug('msg=', msg, 'mode=', gdata.mode(), caller=self)
        if not signinParams and gdata.enableTestHtml():
            room = gdata.rooms()[roomId]
            signinParams = gamedata.getGameAttrJson(userId, room.gameId,
                                                    'test.signinParams')

        gdata.rooms()[roomId].doSignin(userId, signinParams)
示例#24
0
def _loadSubMemberStatus(userId):
    try:
        d = gamedata.getGameAttrJson(userId, HALL_GAMEID, 'submember', {})
        subDT = _decodeDT(d.get('subTime', -1))
        deliveryDT = _decodeDT(d.get('deliveryTime', -1))
        expiresDT = _decodeDT(d.get('expiresTime', -1))
        return SubMemberStatus(False, subDT, deliveryDT, None, expiresDT)
    except:
        ftlog.error()
        return SubMemberStatus(False, None, None, None, None)
示例#25
0
文件: room.py 项目: zhaozw/hall37
    def doRoomSigIn(self, roomId, userId, signinParams):
        msg = runcmd.getMsgPack()
        if ftlog.is_debug():
            ftlog.debug('msg=', msg, 'mode=', gdata.mode(),
                        caller=self)
        if not signinParams and gdata.enableTestHtml():
            room = gdata.rooms()[roomId]
            signinParams = gamedata.getGameAttrJson(userId, room.gameId, 'test.signinParams')

        gdata.rooms()[roomId].doSignin(userId, signinParams)
示例#26
0
 def loadUserBenefitsData(self, userId):
     '''
     加载用户救济金配置
     '''
     try:
         d = gamedata.getGameAttrJson(userId, 9999, 'benefits')
         if d:
             return TYUserBenefitsData(d['times'], d['ut'])
     except:
         ftlog.error()
     return None
示例#27
0
 def loadUserBenefitsData(self, userId):
     '''
     加载用户救济金配置
     '''
     try:
         d = gamedata.getGameAttrJson(userId, 9999, 'benefits')
         if d:
             return TYUserBenefitsData(d['times'], d['ut'])
     except:
         ftlog.error()
     return None
示例#28
0
def addGunSkin(userId, skinId, mode):
    """
    添加火炮皮肤
    """
    ownGunSkinSkinsKey = GameData.ownGunSkinSkins
    ownGunSkinSkins = gamedata.getGameAttrJson(userId, FISH_GAMEID,
                                               ownGunSkinSkinsKey, [])
    if skinId not in ownGunSkinSkins:
        ownGunSkinSkins.append(skinId)
        gamedata.setGameAttr(userId, FISH_GAMEID, ownGunSkinSkinsKey,
                             json.dumps(ownGunSkinSkins))
示例#29
0
def refreshInviteData(userId):
    """
    刷新邀请数据
    """
    inviteList = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.inviteList, [])
    for _, inviteData in enumerate(inviteList[:]):
        if inviteData.get("receiveTime"):
            if util.getDayStartTimestamp(inviteData["receiveTime"]) != util.getDayStartTimestamp(int(time.time())):
                inviteList.remove(inviteData)
    gamedata.setGameAttr(userId, FISH_GAMEID, GameData.inviteList, json.dumps(inviteList))
    return inviteList
示例#30
0
def getAllOutVipHelpMail(userId):
    """
    获取发件(赠送)记录
    """
    mailInfos = gamedata.getGameAttrJson(userId, FISH_GAMEID, GameData.outMailInfos, [])
    tempMail = []
    for index, value in enumerate(mailInfos):
        if value["type"] == MailRewardType.Present:
            tempMail.append(value)
    tempMail = _removeOutMailExpData(tempMail, MAIL_DISPLAY_COUNT)
    return tempMail
示例#31
0
def getAllMail(userId):
    """
    获取收件箱所有邮件
    """
    tempMail = {}
    for _mt in MAIL_SENDER_TYPE_LIST:
        _key = GameData.mailInfos if _mt == MailSenderType.MT_SYS else GameData.userMailInfos
        mailInfos = gamedata.getGameAttrJson(userId, FISH_GAMEID, _key, [])
        tempMail[_mt] = _removeMailExpData(mailInfos, MAIL_DISPLAY_COUNT)
        _dealTips(userId, tempMail[_mt], _mt)
    return tempMail
示例#32
0
 def loadScoreInfo(self, rankingId, userId):
     '''
     获取用户的scoreInfo
     '''
     try:
         field = 'ranking.info:%s' % (rankingId)
         d = pkgamedata.getGameAttrJson(userId, 9999, field)
         if d:
             return TYRankingUserScoreInfo(d['score'], d['issueNumber'])
     except:
         ftlog.error()
     return None
示例#33
0
 def loadScoreInfo(self, rankingId, userId):
     '''
     获取用户的scoreInfo
     '''
     try:
         field = 'ranking.info:%s' % (rankingId)
         d = pkgamedata.getGameAttrJson(userId, 9999, field)
         if d:
             return TYRankingUserScoreInfo(d['score'], d['issueNumber'])
     except:
         ftlog.error()
     return None
示例#34
0
 def readJson(cls, userId, key, gameId=6):
     '''
     从Reids的gametable中读取内容,并且将读出的内容作为json处理
     :param key 用于hashmap存储内容的key,必须唯一
     :param gameId 存储在redis中的位置,默认存在game:6下
     :return 返回从JSON解析的对象
     '''
     data = gamedata.getGameAttrJson(userId, gameId, key)
     # ftlog.debug('Redis.readJson: userId=', userId, 'gameId=' , gameId, 'key=', key, ('data(%s)=' % type(data)), data)
     if data == None:
         return {}
     return data
示例#35
0
文件: hallvip.py 项目: zhaozw/hall37
 def loadVipGiftStatus(self, userId):
     '''
     加载用户VIP礼包状态
     @param userId: 哪个用户
     @return: TYUserVipGiftStatusData
     '''
     status = TYUserVipGiftStatusData()
     d = pkgamedata.getGameAttrJson(userId, 9999, 'vip.gift.states')
     if d:
         for level, state in d.iteritems():
             status.giftStateMap[int(level)] = state
     return status
示例#36
0
 def loadVipGiftStatus(self, userId):
     '''
     加载用户VIP礼包状态
     @param userId: 哪个用户
     @return: TYUserVipGiftStatusData
     '''
     status = TYUserVipGiftStatusData()
     d = pkgamedata.getGameAttrJson(userId, 9999, 'vip.gift.states')
     if d:
         for level, state in d.iteritems():
             status.giftStateMap[int(level)] = state
     return status
示例#37
0
文件: room.py 项目: zhaozw/hall37
 def signinNextMatch(self, gameId, userId):
     """报名下一场比赛
     """
     msg = runcmd.getMsgPack()
     roomId = msg.getParam('room_id', 0)
     ctlRoomIds = [bigRoomId * 10000 + 1000 for bigRoomId in gdata.gameIdBigRoomidsMap()[gameId]]
     if roomId in ctlRoomIds:
         room = gdata.rooms()[roomId]
         if room:
             signinParams = gamedata.getGameAttrJson(userId, room.gameId, 'test.signinParams')
             room.doSignin(userId, signinParams)
         else:
             ftlog.info('=======signinNextMatch==Trace==', roomId, userId)
示例#38
0
def loadStatus(userId, timestamp):
    '''
    加载用户推广状态
    '''
    d = status = None
    try:
        d = gamedata.getGameAttrJson(userId, HALL_GAMEID, 'neituiguang')
        if d:
            status = NeituiguangStatus(userId, timestamp).decodeFromDict(d)
    except:
        ftlog.error('neiguituan.loadStatus userId=', userId,
                    'd=', d)
    if not status:
        status = NeituiguangStatus(userId, timestamp)
    return _adjustStatus(status)
示例#39
0
    def _getSelectedRoomOptions(self, userId, gameId):

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

        if not self._checkUserLastSelectedCustomRoomConfVer(userId, gameId):
            return difangConf.getCustomRoomConf(gameId, 'defaultSelectedOptions')

        selectedRoomOptions = gamedata.getGameAttrJson(userId, gameId, "selectedRoomOptions")
        if not selectedRoomOptions:  # 新加玩法类型
            return difangConf.getCustomRoomConf(gameId, 'defaultSelectedOptions')

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

        return selectedRoomOptions
示例#40
0
def _loadStatus(userId):
    try:
        d = gamedata.getGameAttrJson(userId, HALL_GAMEID, 'monthCheckin')
        if d:
            status = MonthCheckinStatus(userId, strToDate(d['ut']))
            for datestr in d.get('cl', []):
                dateobj = strToDate(datestr)
                status.addCheckinDate(dateobj)
            for datestr in d.get('scl', []):
                dateobj = strToDate(datestr)
                status.addSupplementCheckinDate(dateobj)
            for days in d.get('rdl', []):
                status.addRewardDays(int(days))
            status.gotDaysRewardSet = set(d.get('rdl', []))
            return status
    except:
        ftlog.error()
    return None
示例#41
0
def antiCheatWithTodayTime(userId):
    todoayTime = pkgamedata.getGameAttrJson(userId, HALL_GAMEID, 'todaytime', {})
    dayCount = 0
    totalTime = 0
    for (_, value) in todoayTime.items():
        totalTime += value
        dayCount += 1

    if ftlog.is_debug():
        ftlog.debug('antiCheatWithTodayTime userId =', userId, ' daysWithRecord = ', dayCount,
                    ' gameTimeInDaysWithRecord = ', totalTime)

    cheatDays = hallconf._getHallPublic('cheatDays')
    cheatGameTime = hallconf._getHallPublic('gameTime')
    if ftlog.is_debug():
        ftlog.debug('antiCheatWithTodayTime cheatDays = ', cheatDays, ' cheatGameTime = ', cheatGameTime)

    if dayCount >= cheatDays and totalTime < cheatGameTime:
        return True
    else:
        return False
示例#42
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)