def calcUserScore(userId, rankingDefine, playCount, chipDelta, winStreak, vipLevel): ''' 根据参数计算积分 ''' score = chipDelta * rankingDefine.exchangeRate if playCount >= rankingDefine.playCounts: score *= rankingDefine.playCountsDecayRate # 月卡加成 monthCardPlus = 0 if rankingDefine.monthCardItem and UserBag.isHaveAssets( userId, rankingDefine.monthCardItem) and chipDelta > 0: monthCardPlus = rankingDefine.monthCardPlus # 荣耀月卡加成 honorCardPlus = 0 if rankingDefine.honorCardItem and UserBag.isHaveAssets( userId, rankingDefine.honorCardItem) and chipDelta > 0: honorCardPlus = rankingDefine.honorCardPlus if chipDelta > 0: winsPlusRate = rankingDefine.winsPlusRate if winStreak > 1 else 0 vipPlusRate = rankingDefine.findVipPlusRate(vipLevel) score *= (1 + vipPlusRate + winsPlusRate + monthCardPlus + honorCardPlus) return int(round(score))
def sendRewardToUser(self, userId, mail, intActId, charged_rmb): ftlog.debug('GiftboxEntry.sendRewardToUser:begin', 'userId=', userId, 'mail=', mail, 'charged_rmb=', charged_rmb) # 将礼包道具消耗掉, ok = UserBag.consumeAssetsIfEnough(userId, self._itemId, 1, 'ACTIVITY_REWARD', DIZHU_GAMEID, intActId) if not ok: ftlog.debug('GiftboxEntry.sendRewardToUser:consumeitem', 'userId=', userId, 'ok=', ok) return False if mail and self._reward.get('desc'): desc = self._reward.get('desc') mail = strutil.replaceParams(mail, {'rewardContent':desc}) else: mail = None UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, self._reward, 'ACTIVITY_REWARD', mail, intActId) ftlog.info('GiftboxEntry:sendRewardToUser:'******'gameId=', DIZHU_GAMEID, 'userId=', userId, 'itemId=', self._itemId, 'charged_rmb=', charged_rmb, 'reward=', self._reward) return True
def sendToUser(self, userId): ''' 返回实际发送的数量 ''' itemId = self.reward.get('itemId') desc = self.reward.get('desc') bottom = self.reward.get('bottom') avg = self.reward.get('avg') top = self.reward.get('top') lteprob= self.reward.get('lteprob') if random.random() <= lteprob: count = random.randrange(bottom, avg + 1) else: count = random.randrange(avg, top + 1) assets = {'itemId':itemId, 'count':count} ftlog.debug('RandomRewardHandler.sendToUser', 'userId=', userId, 'self.reward=', self.reward, 'assets=', assets) desc = strutil.replaceParams(desc, {'count':count}) mail = strutil.replaceParams(self.mail, {'assets_reward_desc':desc}) UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, assets, WishingWell.EVENT_ID, mail) return count
def onUserLogin(cls, event): ftlog.debug("SkillLevelGift.onUserLogin: event=", event) # gameId = 6 userId = event.userId clientId = sessiondata.getClientId(userId) gameId = strutil.getGameIdFromHallClientId(clientId) ddzconf = cls.getDdzActivityConf() mapkey = "SkillLevelGift" + ddzconf.get("start", "") if gameId != DIZHU_GAMEID: return toggle = ddzconf.get("toggle", False) ftlog.debug("SkillLevelGift.onUserLogin: userId=", userId, "open_toggle=", toggle) if not toggle: return isFirst = Redis.isFirst(userId, mapkey) ftlog.debug("SkillLevelGift.onUserLogin: userId=", userId, "isFirst=", isFirst) if not isFirst: return # 发放道具 mail = ddzconf.get("mail", "") assets = ddzconf.get("assets") UserBag.sendAssetsToUser(gameId, userId, assets, 'DDZ_ATC_SKILLLEVEL_GIFT', mail) ftlog.debug("SkillLevelGift.onUserLogin: userId=", userId, "send assets=", assets, "mail=", mail)
def sendPrizeToUser(self, userId, prizeList, mail): counter = 0 for prize in prizeList: prizeContent = hallitem.buildContent(prize['itemId'], prize['count'], True) mailmessage = strutil.replaceParams(mail, {'prizeContent': prizeContent}) UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, prize, 'ACT_TABLE_REPLAY_RANKING_PRIZE', mailmessage, 0) ftlog.info('TableReplayRanking.sendPrizeToUser', 'userId=', userId, 'prize=', prize) counter += prize['count'] return counter
def getPray(cls, userId, foodId): ''' 获取奖励 ''' food = cls.getFood(foodId) if not food: return None, None if not cls.consumeExpenses(userId, food): ftlog.warn('WorshipHelper.getPray', 'userId=', userId, 'foodId=', foodId, 'userChip=', userchip.getChip(userId), 'consumeChip=', food.chip) payOrder = { "contains": { "count": userchip.getChip(userId), "itemId": "user:chip" }, "shelves": [ "lessbuychip" ] } clientId = sessiondata.getClientId(userId) product, _shelves = hallstore.findProductByPayOrder(DIZHU_GAMEID, userId, clientId, payOrder) if not product: Alert.sendNormalAlert(DIZHU_GAMEID, userId, '金币不足', '金币不足了, 请去充值吧', None, None) return None, None buyType = '' orderShow = TodoTaskOrderShow.makeByProduct('金币不足', '', product, buyType) orderShow.setParam('sub_action_btn_text', '确定') mo = TodoTaskHelper.makeTodoTaskMsg(DIZHU_GAMEID, userId, orderShow) router.sendToUser(mo, userId) return None, None # 更新用户花费 cls.updateUserCost(userId, food.chip) # 拜到的奖励 prayChip = food.choiceReward() UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, {'itemId': 'user:chip', 'count': prayChip}, 'DDZ_WORSHIP_SYSTEM') # 保存的消息 msg = cls.getMessageByFoodId(foodId) cls.pushRecord(strutil.dumps({ 'userId': userId, 'msg': msg, 'chip': prayChip, 'costChip': food.chip, })) return {'chip': prayChip, 'msg': msg, 'costChip': food.chip}, userchip.getChip(userId)
def sendPrizeToUser(self, userId): if ftlog.is_debug(): ftlog.debug('TableShareRecorder.sendPrizeToUser', 'userId=', userId, 'prizeList=', self.prizeList) for prize in self.prizeList: prizeContent = hallitem.buildContent(prize['itemId'], prize['count'], True) mail = strutil.replaceParams(self.mail, {'prizeContent': prizeContent}) UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, prize, 'ACTIVITY_REWARD', mail, self.intActId) ftlog.info('TableShareRecorder.sendPrizeToUser', 'userId=', userId, 'prize=', prize)
def addRewardToUser(self, userId, rewardDict): """ 发送奖励, 发送email """ mail = None reward = TYContentItem.decodeFromDict(rewardDict) UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, { 'itemId': reward.assetKindId, 'count': reward.count }, 'DDZ_RED_ENVELOPE_BOMB', mail=mail)
def sendToUser(self, userId): ''' 返回实际发送的数量 ''' count = self.reward.get('count') desc = self.reward.get('desc') ftlog.debug('FixedRewardHandler.sendToUser', 'userId=', userId, 'self.reward=', self.reward, 'desc=', desc) mail = strutil.replaceParams(self.mail, {'assets_reward_desc':desc}) UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, self.reward, WishingWell.EVENT_ID, mail) return count
def onUserLuckyDraw(cls, userId, roomId): ''' 热身系统:抽奖处理 ''' ftlog.debug('WarmUpSystem.onUserLuckyDraw', 'userId=', userId, 'roomId=', roomId) global warmupLotteryPool if not warmupLotteryPool: warmupLotteryPool = WarmUpSystemLotteryPool() ftlog.debug('WarmUpSystem.onUserLuckyDraw', 'userId=', userId, 'warmupLotteryPool.prizeList=', warmupLotteryPool.lotteryPool.prizeList) ## 处理抽奖花费不足 if not WarmUpSystemHelper.checkAssetsEnough(userId): return {'success':False, 'mychip': UserInfo.getChip(userId)} ## 处理抽奖CD if not CountingTimer.checkCooldownFinish(userId): return {'success':False, 'mychip': UserInfo.getChip(userId)} ## 消耗抽奖花费 if not WarmUpSystemHelper.consumeLuckyDrawExpenses(userId): return {'success':False, 'mychip': UserInfo.getChip(userId)} chooseItemConfigure = warmupLotteryPool.randomGetPoolItem() ftlog.debug('WarmUpSystem.onUserLuckyDraw', 'userId=', userId, 'chooseItemConfigure=', chooseItemConfigure) ## 重置CD时间 CountingTimer.resetCounting(userId) ## 抽奖未抽中 chooseitemId = chooseItemConfigure.get('itemId') if not chooseitemId or len(chooseitemId) <= 0: return WarmUpSystemHelper.buildSuccessMessagePack(userId, chooseItemConfigure) ## 发送抽奖奖励 prizeMail = WarmUpSystemHelper.buildLuckyDrawMailMessage(chooseItemConfigure, roomId) UserBag.sendAssetsToUser(6, userId, chooseItemConfigure, BIEVENT_ID, prizeMail) ## 添加消息到抽奖记录中 LuckyDrawRecorder.pushRecord(LuckyDrawRecorder.buildRecord(userId, chooseItemConfigure)) return WarmUpSystemHelper.buildSuccessMessagePack(userId, chooseItemConfigure)
def consumeExpenses(cls, userId, food): ''' 消耗抽奖花费 ''' ftlog.info('WorshipHelper.consumeExpenses', 'userId=', userId, 'food=', food.toDict()) return UserBag.consumeAssetsIfEnough(userId, 'user:chip', food.chip, 'DDZ_WORSHIP_SYSTEM')
def getRewardInfo(cls, userId, scoreActivity): rewardInfo = scoreActivity.getUserRewardInfo( userId, scoreActivity.actId) if scoreActivity else None if ftlog.is_debug(): ftlog.debug('activityGetRewardInfo userId=', userId, 'rankId=', scoreActivity.actId, 'rewardInfo=', rewardInfo) luckyCardCount = UserBag.getAssetsCount(userId, 'item:4167') return {'rewardInfo': rewardInfo, 'luckyCardCount': luckyCardCount}
def consumeExpenses(cls, userId, item): ''' 消耗抽奖花费 ''' expensesItemId = item.assetKindId expensesItemCount = item.count ftlog.info('FishHelper.consumeExpenses', 'userId=', userId, 'itemId=', expensesItemId, 'count=', expensesItemCount) return UserBag.consumeAssetsIfEnough(userId, expensesItemId, expensesItemCount, 'DDZ_FISHING_SYSTEM')
def onUserLogin(cls, event): ftlog.debug("ItemSender.onUserLogin: event=", event) userId = event.userId dizhuconf = cls.getDdzActivityConf() if not Tool.isGameDdz(userId): return if cls.isOutdate(): ftlog.debug("ItemSender.onUserLogin: userId=", userId, "isOutdate=", True) return # 若clientId不支持,则返回 isSupport = cls.isClientIdSupport( userId, dizhuconf.get('supportContainClientIdOr', [])) ftlog.debug("ItemSender.onUserLogin: userId=", userId, "isSupport=", isSupport) if not isSupport: return isFirst = Redis.isFirst(userId, cls.getUniqueKey()) ftlog.debug("ItemSender.onUserLogin: userId=", userId, "isFirst=", isFirst) if not isFirst: return # 发放道具 ftlog.debug("ItemSender.onUserLogin: userId=", userId, "ddzconf=", dizhuconf) mail = dizhuconf.get("mail") assets = dizhuconf.get("assets") if not assets: return UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, assets, 'DDZ_ATC_ITEM_SENDER', mail) ftlog.debug("ItemSender.onUserLogin: userId=", userId, "send assets=", assets, "mail=", mail)
def sendPrizeToUser(self, activityGameId, userId, prize, mail): prizeContent = hallitem.buildContent(prize['itemId'], prize['count'], True) mailmessage = strutil.replaceParams(mail, {'prizeContent': prizeContent}) _, addcount, _ = UserBag.sendAssetsToUser(activityGameId, userId, prize, self.EVENT_ID, mailmessage, 0) if ftlog.is_debug(): ftlog.debug('LuckyMoneyNew.sendPrizeToUser', 'activityGameId=', activityGameId, 'userId=', userId, 'prize=', prize, 'addcount=', addcount) return addcount
def sendingRewardOnceIfNeed(cls, userId): ftlog.debug('BindingPhoneHandler.sendingRewardOnceIfNeed:start', 'userId=', userId, 'isOutdate=', cls.isOutdate()) if cls.isOutdate(): return None ## 是否在clientId集合中 dizhuconf = cls.getActivityConfig() clientIdList = dizhuconf.get('clientIdList', []) clientId = sessiondata.getClientId(userId) ftlog.debug('BindingPhoneHandler.sendingRewardOnceIfNeed:clientId', 'userId=', userId, 'clientId=', clientId, 'ok=', clientId in clientIdList) if clientId not in clientIdList: return None ## 是否是第一次领取 isFirst = Redis.isFirst(userId, cls.getFieldKey()) ftlog.debug('BindingPhoneHandler.sendingRewardOnceIfNeed:isFirst', 'userId=', userId, 'isFirst=', isFirst) if not isFirst: return None ## 发放奖励 mail = dizhuconf.get('mail') assetsList = dizhuconf.get('assets') ftlog.debug('BindingPhoneHandler.sendingRewardOnceIfNeed:send', 'userId=', userId, 'dizhuconf=', dizhuconf) if not assetsList: return None UserBag.sendAssetsListToUser(DIZHU_GAMEID, userId, assetsList, cls.EVENT_ID, mail, cls.ACTIVITY_ID) ftlog.debug('BindingPhoneHandler.sendingRewardOnceIfNeed:end', 'userId=', userId, 'assetsList=', assetsList, 'mail=', mail) return None
def sendRewardToUser(self, userId, mail, intActId, key): reward = self._reward if mail and reward.get('desc'): rewardContent = reward.get('desc') mail = strutil.replaceParams(mail, {'rewardContent': rewardContent}) else: mail = None UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, reward, 'ACTIVITY_REWARD', mail, intActId) # 记录发放过的道具 rewardItemId = reward.get('itemId') actmodel = ActivityModel() actmodel.loadModel(userId, key) actmodel.itemSendMap[rewardItemId] = 1 actmodel.saveModel(userId, key) ftlog.info('VipGiftEntry.sendRewardToUser:'******'userId=', userId, 'viplevel=', self.getVipLevel(userId), 'reward=', reward, 'itemSendMap=', actmodel.itemSendMap) return True
def consumeLuckyDrawExpenses(cls, userId): ''' 消耗抽奖花费 :return 费用不足返回False ''' conf = getWarmupSystemConfig() consumeAssets = conf.get('expensesAssets', {}) expensesItemId = consumeAssets.get('itemId') expensesItemCount = consumeAssets.get('count', 0) ftlog.debug('WarmUpSystemHelper.consumeLuckyDrawExpenses', 'userId=', userId, 'itemId=', expensesItemId, 'count=', expensesItemCount) return UserBag.consumeAssetsIfEnough(userId, expensesItemId, expensesItemCount, BIEVENT_ID)
def _checkHasEnoughQuickSigninItem(self, userId, fee): # 检查参物品数量 from dizhu.activities.toolbox import UserBag quickSigninItem = UserBag.getAssetsCount(userId, fee.assetKindId) if ftlog.is_debug(): ftlog.debug('DizhuCtrlRoomArenaMatch._do_room__quicksignin_item', 'gameId=', self.gameId, 'userId=', userId, 'itemKind=', fee.assetKindId, 'itemCount=', fee.count, 'quickSigninItemRemaining=', quickSigninItem) if not quickSigninItem or quickSigninItem < fee.count: return 0 return 1
def _creditTypeSendRewardsIfNeed(cls, userId): ''' 积分发奖类型,当积分达到发奖值后,自动发奖(仅供积分发奖类型使用:"rewardsType": "credit") ''' actconf = DumplingsUtil.getActivityConf() isRanking = Tool.dictGet(actconf, 'config.activate.rewardsType', 'credit') == 'ranking' if isRanking: return rediskey = cls.getRedisKey() mail = Tool.dictGet(actconf, 'config.activate.mail') reward = Tool.dictGet(actconf, 'config.activate.credit.rewards') jsondict = Redis.readJson(userId, rediskey) helper = CreditRewardHelper(userId, reward) reachedlist = helper.getReachedConfList() # 达到发奖条件的所有奖励配置的list getlist = jsondict.get('getlist', []) # 已经领取的奖励list,使用score字段记录,score字段值不可重复 for item in reachedlist: for assets in item.get('items'): if item['score'] not in getlist: getlist.append(item['score']) ranking_num = cls.getRankingWithUserId(userId) mailstr = strutil.replaceParams(mail, { 'assets': item.get('desc'), 'ranking_num': ranking_num }) UserBag.sendAssetsToUser(6, userId, assets, 'DDZ_ACT_DUMPLINGS', mailstr) # 记录奖励已经领取 jsondict['getlist'] = getlist Redis.writeJson(userId, rediskey, jsondict) ftlog.debug("DumplingsUtil.creditTypeSendRewardsIfNeed: userId=", userId, "jsondict=", jsondict)
def checkMatchRank(cls, userId, matchId, rank): matchId = gdata.getBigRoomId(matchId) lottery_conf = dizhuconf.getMatchLotteryConf() lottery_switch = lottery_conf.get('open') if not lottery_switch: return False # 钻石数量为0触发 user_diamond = userdata.getAttrInt(userId, 'diamond') if user_diamond != 0: return False # 身上没有任何报名券 触发 discount_conf = lottery_conf.get('discountItem', []) if not discount_conf: return False for discountItem in discount_conf: itemId = discountItem.get('itemId') userHaveAssetsCount = UserBag.getAssetsCount(userId, itemId) if userHaveAssetsCount != 0: return False match_conf = lottery_conf.get('matchList', {}).get(str(matchId), []) if not match_conf: return False for conf in match_conf: beginRank = conf['beginRank'] endRank = conf['endRank'] if beginRank <= rank <= endRank: if ftlog.is_debug(): ftlog.debug('checkMatchRank userId=', userId, 'matchId=', matchId, 'return True') return True # 若是客户端请求则需要验证排名信息 # histories = MatchHistoryHandler.getMatchHistory(userId, recordId, 1, mixId) # for history in histories: # recordRank = history.get('rank') # if rank != recordRank: # return False # timestamp = history.get('timestamp') # currtimestamp = pktimestamp.getCurrentTimestamp() # if (currtimestamp - timestamp) > 300: # return False if ftlog.is_debug(): ftlog.debug('checkMatchRank userId=', userId, 'matchId=', matchId, 'return False') return False
def checkCondition(self, userId, charged_rmb): ftlog.debug('GiftboxEntry.checkCondition:begin', 'userId=', userId, 'charged_rmb=', charged_rmb, 'itemId=', self._itemId) if not UserBag.isHaveAssets(userId, self._itemId, DIZHU_GAMEID): ftlog.debug('GiftboxEntry.checkCondition:', 'userId=', userId, 'item not found') return False if charged_rmb < self._rmb: ftlog.debug('GiftboxEntry.checkCondition:', 'userId=', userId, 'charged_rmb < rmblimit') return False return True
def buildFeesList(cls, userId, fees): ret = [] # 返回付费列表[{type,desc,selected,img},{...}] # 不用写单位的道具类型集合 notNeedUnit = set(['user:chip', 'user:exp', 'user:charm', 'ddz:master.score']); for fee in fees: assetKind = hallitem.itemSystem.findAssetKind(fee.assetKindId) if fee.count > 0 and assetKind: desc = '' if fee.assetKindId in notNeedUnit: desc = str(fee.count) + assetKind.displayName else: desc = str(fee.count) + assetKind.units + assetKind.displayName from dizhu.activities.toolbox import UserBag myCount = UserBag.getAssetsCount(userId, fee.assetKindId) ret.append({'type':fee.assetKindId, 'desc':desc, 'img':assetKind.pic, 'selected':False, 'fulfilled':1 if myCount >= fee.count else 0}) return ret
def handleRequestPutting(self, model, userId, poolItem): ''' 投入资本 :param userId: :return: ''' clientconf = strutil.deepcopy(self._clientConf) serverconf = self._serverConf uniquekey = Utility.buildUniqueKey(serverconf) ftlog.debug('WishingWell.handleRequestPutting:start', 'userId=', userId, 'model=', model.dict()) ## 判断许愿池投入按钮是否过期 if Utility.isPutIntoButtonOutdate(clientconf): return Utility.buildError(Tool.dictGet(clientconf, 'config.wishingOverError')) ## 许愿消耗费用 expensesConfig = poolItem.get('expenses') expensesItemId = expensesConfig.get('itemId', 'user:chip') expensesItemCount = expensesConfig.get('count', 0) ftlog.debug('WishingWell.handleRequestPutting:consume', 'userId=', userId, 'poolItem=', poolItem, 'expensesItemId=', expensesItemId, 'expensesItemCount=', expensesItemCount) if not UserBag.consumeAssetsIfEnough(userId, expensesItemId, expensesItemCount, self.EVENT_ID): ## 费用不足 return Utility.buildError(Tool.dictGet(clientconf, 'config.expensesNotEnoughError')) ## 更新Model model.isAlreadyPutted = True ## 重置计时,重新开始计时 model.resetingCounterToCurrentTimestamp() model.dumpsToRedis(userId, uniquekey) ftlog.info('WishingWell.handleRequestPutting, ', 'userId', userId, 'poolstepindex', model.poolStepIndex, 'model=', model.dict()) response = self.getActivityUserStatus(userId, model) puttingSuccess = Tool.dictGet(clientconf, 'config.puttingSuccess') if puttingSuccess and len(puttingSuccess) > 0: response['message'] = puttingSuccess response['operate'] = 'putting' return response
def getFeesDiscount(userId, rooms): # 折扣报名比赛 取玩家背包中的物品确认是否有折扣 for room in rooms: matchCondition = room.get('matchCondition', {}) discountItems = matchCondition.get('discountItems') if discountItems: for item in discountItems: itemId = item.get('itemId') userHaveAssetsCount = UserBag.getAssetsCount(userId, itemId) if userHaveAssetsCount > 0: discount = item.get('discount', 1) desc = item.get('desc', "") room['signupFee']['desc'] = desc room['signupFee']['saledesc'] = item.get('oldPrice', "") room['signupFee']['sale'] = int(float(discount) * 10) room['entry'] = desc room['hasOtherDiscount'] = True break return rooms
def checkAssetsEnough(cls, userId): ''' 检测抽奖需要的花费是否足够 ''' conf = getWarmupSystemConfig() consumeAssets = conf.get('expensesAssets', {}) requireItemId = consumeAssets.get('itemId') requireItemCount = consumeAssets.get('count', 0) if not requireItemId: return False userHaveAssetsCount = UserBag.getAssetsCount(userId, requireItemId) ftlog.debug('WarmUpSystemHelper.checkAssetsEnough', 'userId=', userId, 'consumeAssets=', consumeAssets, 'userHaveAssetsCount=', userHaveAssetsCount) return userHaveAssetsCount >= requireItemCount
def changeSignInFees(userId, matchId, fees): matchId = gdata.getBigRoomId(matchId) lottery_conf = dizhuconf.getMatchLotteryConf() discountItems = lottery_conf.get('discountItem') changedItemId = None ftlog.debug('changeSignInFees userId=', userId, 'matchId=', matchId, 'fees before=', fees) for discount in discountItems: discountList = discount.get('discountList', []) if matchId in discountList: itemId = discount.get('itemId', '') discountPoint = discount.get('discount', '') if UserBag.getAssetsCount(userId, itemId) > 0: for fee in fees: if fee.get('itemId', '') == ASSET_DIAMOND_KIND_ID: fee['count'] = int(discountPoint * fee['count'] /10) saveMatchLotteryInfo(userId, [{'itemId':itemId, 'matchId':matchId}]) fees.append({'itemId':itemId, 'count':1}) changedItemId = fee.get('itemId', '') break break ftlog.debug('changeSignInFees userId=', userId, 'fees=', fees) return fees, changedItemId
def get(self, userId, gameId, clientId, activityId, bankId): ''' {'isOK': True, 'nowTime': 1452161428.0, 'nextTime': 1452218400.0, 'hasGet': False, 'isRemain': True, 'tip': tip} ''' clientconf = self._clientConf #检测是否过期 if not self.checkOperative(): tip = Tool.dictGet(clientconf, "config.activate.outdateTip") return {"isOK": False, "tip": tip} #活动已经过期 nowstamp = Tool.datetimeToTimestamp(datetime.now()) rconf = {"isOK": True, "nowTime": nowstamp} timeservices = ConfigDatabase.getTimeServices(bankId) next_timepoint = timeservices.getFirstUnreachedDatetime() if next_timepoint: rconf["nextTime"] = Tool.datetimeToTimestamp(next_timepoint) arrive_timepoint = timeservices.getLastlyReachedDatetime() if not arrive_timepoint: #未达到领取时间 tip = Tool.dictGet(clientconf, "config.activate.cannotGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf current_issue = timeservices.getIssueNumber(arrive_timepoint) isget = LuckyPacketHelper.isUserGet(bankId, userId, current_issue) if isget: # 已经领取了 tip = Tool.dictGet(clientconf, "config.activate.alreadyGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf isvip = (UserInfo.getVipLevel(userId) > 0) iteminfo = LuckyPacketHelper.getPacket(bankId, current_issue, isvip) ftlog.debug("TYActivityDdzRedEnvelope.get: userId", userId, " iteminfo=", iteminfo, "isvip=", isvip) if not iteminfo: tip = Tool.dictGet(clientconf, "config.activate.emptyGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf itemId = iteminfo.get('itemId') itemCount = iteminfo.get('count', 0) itemDesc = self.getItemDesc(clientconf, iteminfo) iteminfo["itemDesc"] = itemDesc # 构造邮箱信息 assetsdict = {"assets": itemDesc, "count": str(itemCount)} mail = Tool.dictGet(clientconf, "config.mail") mail = strutil.replaceParams(mail, assetsdict) # 发送奖励和邮箱信息 assets = {'itemId': itemId, 'count': itemCount} UserBag.sendAssetsToUser(6, userId, assets, 'DDZ_ACT_REDENVELOPE', mail) # 发送LED的(条件满足) itemconf = self.getItemConf(clientconf, iteminfo) ok = self.sendLedIfNeed(userId, itemconf, itemCount) ftlog.debug("TYActivityDdzRedEnvelope.get: sendLed-> userId=", userId, " ok=", ok) # 记录领取物品 assets.update({"itemDesc": itemconf.get('desc')}) LuckyPacketHelper.setUserGet(bankId, userId, current_issue, iteminfo) # 日志记录领取 ftlog.debug("TYActivityDdzRedEnvelope:Get, ", "userId", userId, "gettime", str(datetime.now()), "assets", iteminfo.get("itemId"), "count", iteminfo.get("count"), "desc", iteminfo.get("itemDesc"), "detail", iteminfo) # 构造协议信息 itemtip = Tool.dictGet(clientconf, "config.activate.itemGetTip") itemtip = strutil.replaceParams(itemtip, assetsdict) rconf.update({ "isOK": True, "itemDesc": itemDesc, "itemCount": itemCount, "tip": itemtip }) ftlog.debug("LuckyPacket.get: userId=", userId, " itemconf=", itemconf, "arrive_timepoint=", str(arrive_timepoint), "rconf=", rconf) return rconf
def get(self, userId, gameId, clientId, activityId): ''' {'isOK': True, 'nowTime': 1452161428.0, 'nextTime': 1452218400.0, 'hasGet': False, 'isRemain': True, 'tip': tip} ''' clientconf = self._clientConf serverconf = self._serverConf dataWrapper = self._dataWrapper timelist = Tool.dictGet(clientconf, "config.activate.timeList") startdate = serverconf.get("start") enddate = serverconf.get("end") #检测是否过期 if not self.checkOperative(): tip = Tool.dictGet(clientconf, "config.activate.outdateTip") return {"isOK": False, "tip": tip} #活动已经过期 nowstamp = Tool.datetimeToTimestamp(datetime.now()) rconf = {"isOK": True, "nowTime": nowstamp} arrive_timepoint = dataWrapper.getLastestTimePoint(timelist, startdate) next_timepoint = dataWrapper.getNextTimePoint(timelist, enddate) if next_timepoint: # 若存在下一个时间点 rconf["nextTime"] = Tool.datetimeToTimestamp(next_timepoint) if not arrive_timepoint: #未达到领取时间 tip = Tool.dictGet(clientconf, "config.activate.cannotGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf has_get = dataWrapper.hasGet(userId, arrive_timepoint) # 是否已经领取 ftlog.debug("TYActivityDdzRedEnvelope.get: userId", userId, " has_get=", has_get) if has_get: # 已经领取了 tip = Tool.dictGet(clientconf, "config.activate.alreadyGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf isvip = (UserInfo.getVipLevel(userId) > 0) result = daobase.executeMixLua(_REDIS_LUA_GET_NAME, 2, isvip, random.randint(1, 10000000)) ftlog.debug("TYActivityDdzRedEnvelope.get: userId", userId, " result=", result, "isvip=", isvip) if not result: tip = Tool.dictGet(clientconf, "config.activate.emptyGetTip") rconf.update({"isOK": False, "tip": tip}) return rconf # 领取红包的结果 result_count = result[1] # 领取红包项的配置 itemconf = _redenvelopeWrapper.getItemConfigWithPath(result[0]) result_name = str(itemconf.get('desc')) # 构造邮箱信息 assetsdict = {"assets": result_name, "count": str(result_count)} mail = Tool.dictGet(clientconf, "config.mail") mail = strutil.replaceParams(mail, assetsdict) # 发送奖励和邮箱信息 assets = {'itemId': itemconf.get("itemId"), 'count': result_count} UserBag.sendAssetsToUser(6, userId, assets, 'DDZ_ACT_REDENVELOPE', mail) # 发送LED的(条件满足) ok = self.sendLedIfNeed(userId, itemconf, result_count) ftlog.debug("TYActivityDdzRedEnvelope.get: sendLed-> userId=", userId, " ok=", ok) # 记录领取物品 assets.update({"itemDesc": itemconf.get('desc')}) dataWrapper.markGet(userId, arrive_timepoint, assets) # 日志记录领取 ftlog.debug("TYActivityDdzRedEnvelope:Get, ", "userId", userId, "gettime", str(datetime.now()), "assets", assets.get("itemId"), "count", assets.get("count"), "desc", assets.get("itemDesc"), "detail", assets) # 构造协议信息 itemtip = Tool.dictGet(clientconf, "config.activate.itemGetTip") itemtip = strutil.replaceParams(itemtip, assetsdict) rconf.update({ "isOK": True, "itemDesc": result_name, "itemCount": result_count, "tip": itemtip }) ftlog.debug("TYActivityDdzRedEnvelope.get: userId=", userId, " itemconf=", itemconf, "arrive_timepoint=", str(arrive_timepoint), "rconf=", rconf) return rconf
def getFishReward(cls, userId, baitId): # 钓到没钓到标志 rewardCount = 0 record = '' fishPic = '' couponFishPic = '' exchangeDes = '' deltaChip = 0 deltaCouponCount = 0 # 检查用户Id, baitId 是否匹配, 获取 bait 消费金币 userName = str(userdata.getAttrs(userId, ['name'])[0]) bait = cls.getBait(baitId) consumeChip = bait.chip if bait else 0 if not consumeChip or not cls.consumeExpenses( userId, TYContentItem.decodeFromDict({ 'itemId': 'user:chip', 'count': consumeChip })): ftlog.warn('FishHelper.getFishReward', 'userId=', userId, 'baitId=', baitId, 'userChip=', userchip.getChip(userId), 'consumeChip=', consumeChip) payOrder = { "contains": { "count": userchip.getChip(userId), "itemId": "user:chip" }, "shelves": ["lessbuychip"] } clientId = sessiondata.getClientId(userId) product, _shelves = hallstore.findProductByPayOrder( DIZHU_GAMEID, userId, clientId, payOrder) if not product: Alert.sendNormalAlert(DIZHU_GAMEID, userId, '金币不足', '金币不足了, 请去充值吧', None, None) return buyType = '' orderShow = TodoTaskOrderShow.makeByProduct( '金币不足', '', product, buyType) orderShow.setParam('sub_action_btn_text', '确定') mo = TodoTaskHelper.makeTodoTaskMsg(DIZHU_GAMEID, userId, orderShow) router.sendToUser(mo, userId) return # 随机获得珍珠, 存入数据库 couponFish = cls.getCouponFishList()[0] # 判断鱼饵有没有奖券鱼的配置 item = dizhu_util.getItemByWeight( bait.couponFishRewards) if bait.couponFishRewards else None couponCount = item.count if item else 0 count = loadUserFishingCount(userId, couponFish.id) if couponCount: assetKind = hallitem.itemSystem.findAssetKind('user:coupon') couponCount = couponCount * 1.0 / assetKind.displayRate couponCount = int(couponCount) if couponCount.is_integer( ) else round(couponCount, 2) rewardCount += 1 count += 1 couponFishPic = couponFish.pic if count >= couponFish.needNum: count = 0 # 发送奖券 dictionary = { 'zhenzhu_count': couponFish.needNum, 'coupon_count': couponCount } record = json.dumps( cls.getRealUserMail(cls.getMail(couponFish, True, False), dictionary)) exchangeDes = json.dumps( cls.getRealUserMail(cls.getMail(couponFish, True, True), dictionary)) dictionary2 = { 'user_name': userName, 'zhenzhu_count': couponFish.needNum, 'coupon_count': couponCount } record2 = json.dumps( cls.getRealUserMail(cls.getMail(couponFish, False, True), dictionary2)) saveUserFishingCount(userId, couponFish.id, count) UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, { 'itemId': item.assetKindId, 'count': item.count }, 'DDZ_FISHING_SYSTEM') deltaCouponCount = item.count cls.pushRecord(record2) if ftlog.is_debug(): ftlog.debug('FishHelper.getFishReward coupon exchangeDes', 'userId=', userId, 'fishId=', couponFish.id, 'exchangeDes=', exchangeDes) else: # 获得一个奖券鱼 dictionary = { 'zhenzhu_count': couponFish.needNum, 'coupon_count': couponCount } record = json.dumps( cls.getRealUserMail(cls.getMail(couponFish, True, False), dictionary)) dictionary2 = { 'user_name': userName, 'zhenzhu_count': couponFish.needNum, 'coupon_count': couponCount } record2 = json.dumps( cls.getRealUserMail(cls.getMail(couponFish, False, False), dictionary2)) saveUserFishingCount(userId, couponFish.id, count) cls.pushRecord(record2) if ftlog.is_debug(): ftlog.debug('FishHelper.getFishReward coupon', 'userId=', userId, 'fishId=', couponFish.id, 'record=', record) # 随机获取金币奖励,对应bait下普通鱼 userBaits = filter(lambda x: x.id == baitId, _fishingConf.baits) fish = userBaits[0].choiceFish() if fish.id: # 钓到鱼了 reward = fish.choiceReward() chip = reward.count if chip: rewardCount += 1 bigFish = cls.getSuperFishList()[0] bigReward = dizhu_util.getItemByWeight( bait.superFishRewards) if bait.superFishRewards else None if bigReward and bigReward.count and fish.id == bait.fishList[ -1].id: # roll 大鱼的机会 fish = bigFish chip = bigReward.count fishPic = fish.pic dictionary = { 'random_message': cls.getMessageByFishId(fish.id), 'fish_name': fish.name, 'chip_count': chip } if rewardCount == 2: record = json.dumps( cls.getRealUserMail(cls.getCombinationMail(), dictionary)) else: record = json.dumps( cls.getRealUserMail(cls.getMail(fish, True), dictionary)) dictionary2 = { 'user_name': userName, 'fish_name': fish.name, 'chip_count': chip, 'random_message': cls.getMessageByFishId(fish.id) } record2 = json.dumps( cls.getRealUserMail(cls.getMail(fish, False), dictionary2)) UserBag.sendAssetsToUser(DIZHU_GAMEID, userId, { 'itemId': 'user:chip', 'count': chip }, 'DDZ_FISHING_SYSTEM') cls.pushRecord(record2) deltaChip = chip if ftlog.is_debug(): ftlog.debug('FishHelper.getFishReward', 'userId=', userId, 'fishId=', fish.id, 'record=', record) return { 'rewardCount': rewardCount, 'desc': json.loads(record) if rewardCount and record else cls.getailureMail(), 'couponFishPic': couponFishPic, 'fishPic': fishPic, 'exchangeDes': json.loads(exchangeDes) if exchangeDes else '', 'finalCouponCount': userdata.getAttr(userId, 'coupon'), 'finalChip': userchip.getChip(userId), 'couponFishCount': count, 'deltaChip': deltaChip, 'deltaCouponCount': deltaCouponCount }