def loadUserBenefits(self, gameId, userId, timestamp=None): ''' 加载用户的救济金数据 @return: TYUserBenefits ''' if timestamp is None: timestamp = pktimestamp.getCurrentTimestamp() # 加载用户的救济金配置 userBenefits = self._loadUserBenefits(gameId, userId, timestamp) if ftlog.is_debug(): ftlog.debug('TYBenefitsSystemImpl.loadUserBenefits before filter gameId=', gameId, 'userId=', userBenefits.userId, 'benefits=', userBenefits.__dict__) # 矫正救济金数据 p, extTimes, extChip = self._findFirstHasChipPrivileges(gameId, userBenefits) if p: userBenefits.extTimes = extTimes userBenefits.extSendChip = extChip userBenefits.privilege = p if ftlog.is_debug(): ftlog.debug('TYBenefitsSystemImpl.loadUserBenefits after filter gameId=', gameId, 'userId=', userBenefits.userId, 'benefits=', userBenefits.__dict__, 'privilege=', p, 'leftTimes=', userBenefits.leftTimes()) return userBenefits
def initGameAfter(self): serverType = gdata.serverType() if ftlog.is_debug(): ftlog.debug("<< |gameId, serverType:", self.gameId(), serverType) if serverType in (gdata.SRV_TYPE_HTTP, gdata.SRV_TYPE_UTIL, gdata.SRV_TYPE_ROOM, gdata.SRV_TYPE_TABLE, gdata.SRV_TYPE_CENTER): TYPluginCenter.reload(self.GAME_ID) if serverType == gdata.SRV_TYPE_TABLE: for room in gdata.rooms().values(): if room.gameId != self.gameId(): continue if ftlog.is_debug(): ftlog.debug("init tables" "|gameId, serverType, roomId:", self.gameId(), serverType, room.roomId) for table in room.maptable.values(): TYPluginCenter.evmsg(table.gameId, PluginEvent.EV_AFTER_TABLE_CHILD_INIT, {'table': table, 'tableType': table.tableType})
def exchange(self, userId, gameId, clientId, userBag): if ftlog.is_debug(): ftlog.debug('HallItemAutoExchange.exchange src:', self.itemSrc, ' dst:', self.itemDst, ' ratio:', self.ratio) timestamp = pktimestamp.getCurrentTimestamp() for cond in self.conditions: if not cond.check(gameId, userId, clientId, timestamp): return from hall.entity import hallitem srcItemKind = hallitem.itemSystem.findItemKind(self.itemSrc) dstItemKind = hallitem.itemSystem.findItemKind(self.itemDst) count = userBag.calcTotalUnitsCount(srcItemKind) if ftlog.is_debug(): ftlog.debug('HallItemAutoExchange.exchange delItemKind:', srcItemKind, ' count:', count) delCount = 0 newCount = 0 while count >= self.ratio: count -= self.ratio delCount += self.ratio newCount += 1 if delCount > 0: ftlog.info('HallItemAutoExchange.exchange delItemKind:', srcItemKind, 'delCount:', delCount, 'addItemKind:', dstItemKind, 'addCount:', newCount) userBag.forceConsumeUnitsCountByKind(gameId, srcItemKind, delCount, timestamp, 'ITEM_AUTO_EXCHANGE', 0) userBag.addItemUnitsByKind(gameId, dstItemKind, newCount, timestamp, 0, 'ITEM_AUTO_EXCHANGE', 0)
def queryEnvelope(self): info = {} info['envelopeId'] = self.id info['contents'] = self.contents info['receiver'] = [] receivers = daobase.executeMixCmd('LRANGE', self.dbPrefix + self.id + self.RECEIVER, 0, -1) if receivers: for receiverJson in receivers: receiver = json.loads(receiverJson) # 补充昵称/头像/金币信息 userId = receiver['userId'] chip, name, purl = pkuserdata.getAttrs(userId, ['chip', 'name', 'purl']) if chip and name and purl: if ftlog.is_debug(): ftlog.debug('TYRedEnvelope.queryEnvelope receiver userId:', userId, ' chip:', chip, ' name:', name, ' purl:', purl) receiver['chip'] = chip receiver['name'] = name receiver['purl'] = purl info['receiver'].append(receiver) if ftlog.is_debug(): ftlog.debug('TYRedEnvelope.queryEnvelope info:', info) return info
def checkCanTriggleFiveStartRate(userId, clientId, timestamp): ver, channelName = _parseClientId(clientId) channel = _channels.get(channelName) if ftlog.is_debug(): ftlog.debug('fivestarrate.checkCanTriggleFiveStartRate userId=', userId, 'clientId=', clientId, 'timestamp=', timestamp, 'channelName=', channelName, 'channel=', channel) if not channel: return False, None clientConf = hallconf.getFiveStarClientConf(clientId) if clientConf.get('disable', 0): if ftlog.is_debug(): ftlog.debug('fivestarrate.checkCanTriggleFiveStartRate userId=', userId, 'clientId=', clientId, 'timestamp=', timestamp, 'clientConf=', clientConf) return False, channel fsRate = _loadFiveStarRate(userId, channel) if _canPopFiveStarRate(userId, ver, fsRate, timestamp): return True, channel return False, channel
def encodeHallUITemplage2(cls, gameId, userId, clientId, template): games = [] gameIds = [] pages, pageIds = cls.encodeHallPageList(gameId, userId, clientId, template.pageList) if ftlog.is_debug(): ftlog.debug('encodeHallUITemplage2 build pageIds: ', pageIds) gameIds.extend(pageIds) innerGames, innserIds = cls.encodeHallInnerGameList2(gameId, userId, clientId, template.innerGames) if ftlog.is_debug(): ftlog.debug('encodeHallUITemplage2 build innserIds: ', innserIds) gameIds.extend(innserIds) if ftlog.is_debug(): ftlog.debug('encodeHallUITemplage2 build gameIds: ', gameIds) # 去重 gameIds = list(set(gameIds)) if ftlog.is_debug(): ftlog.debug('encodeHallUITemplage2 after heavy gameIds: ', gameIds) for version in template.versionList: if version.game.gameId in gameIds: gameDict = { 'gameId': version.game.gameId, 'gameMark': version.game.gameMark, 'description': version.game.description, 'currentVer': version.conf } games.append(gameDict) return games, pages, innerGames
def getActivityList(self, gameId, userId, clientId): if ftlog.is_debug(): ftlog.debug('getActivityList.userId=', userId, 'gameId=', gameId, 'clientId=', clientId) # 活动详情list activityList = [] # 活动名称list listConfig = self._dao.getActivitiesForClient(clientId) if not listConfig: return activityList else: for actName in listConfig: # 根据活动名称构造活动详情 tempValue = self.getActState(userId, gameId, actName) ftlog.debug('getActivityList.userId=', userId, 'gameId=', gameId, 'actName=', actName, 'tempValue=', tempValue) self._getConfigForClient(actName, gameId, userId, clientId, activityList, tempValue) if ftlog.is_debug(): ftlog.debug('TYActivitySystemImpl.getActivityList result=', activityList) return activityList
def getGameInfo(cls, userId, gameId, clientId): ''' 获取 gamedta,用来在 bind_game/user_info中返回给前端 ''' if ftlog.is_debug(): ftlog.debug('<<|gameId, userId, clientId:', gameId, userId, clientId, caller=cls) # matchScores = None # if gdata.games()[gameId].RANKING_ID_MTT: # matchScores = hallranking.rankingSystem.getRankingUser(gdata.games()[gameId].RANKING_ID_MTT, userId).score # if matchScores == None: # matchScores = 0 # gameData = { # 'headUrl': userdata.getAttr(userId, 'purl'), # 'gameTime': 0, #TODO: # 'matchScores': matchScores, } # keys = ['photo', 'lastlogin', 'winChips', 'loginsum'] # values = gamedata.getGameAttrs(userId, gameId, ['photo', 'lastlogin', 'accwinchips', 'loginsum']) # gameData.update(dict(zip(keys, values))) # cls.addGameData(userId, gameId, clientId, gameData) plugin.TYPluginCenter.event(TYPluginUtils.updateMsg(cmd='EV_GET_GAME_DATA', params={'userId': userId, 'gamedata': gameData}), gameId) if ftlog.is_debug(): ftlog.debug('>>|gameId, userId, clientId, gdata:', gameId, userId, clientId, gameData, caller=cls) return gameData
def replacedDomain(urlString, replaceDict): ''' 获取宏定义对应的域名 如果没有对应的宏定义配置或者宏定义配置为空,会返回None ''' global _dominMap if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain _dominMap: ', _dominMap) for domain in _dominMap: domains = _dominMap[domain] if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain domains: ', domains, ' length:', len(domains)) if len(domains) == 0: continue # 按时间平均随机 nChoose = getIndexBySecondInDay(len(domains)) replaceDict[domain] = domains[nChoose] if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain replaceDict: ', replaceDict) if ftlog.is_debug(): ftlog.debug('halldomains.replacedDomain ', urlString, ' replaced params: ', replaceDict) return strutil.replaceParams(urlString, replaceDict)
def enterFriendTable(self, userId, gameId, clientId, ftId): """进入自建桌,插件实现具体功能""" if ftlog.is_debug(): ftlog.debug('MAJIANG enterFriendTable userId:', userId , ' gameId:', gameId , ' clientId:', clientId , ' ftId:', ftId) tableId0, roomId0 = CreateTableData.getTableIdByCreateTableNo(ftId) if ftlog.is_debug(): ftlog.debug('MAJIANG enterFriendTable ftId:', ftId , ' roomId:', roomId0 , ' tableId:', tableId0) if not tableId0 or not roomId0: from difang.majiang2.entity.util import sendPopTipMsg sendPopTipMsg(userId, '您要进入的朋友场房间不存在,请核对房间号') return config = { "type": "game", "pluginParams": { "gameType": 11, "ftId": ftId } } todotask = TodoTaskEnterGameNew(GAMEID, config) mo = MsgPack() mo.setCmd('todo_tasks') mo.setResult('gameId', gameId) mo.setResult('pluginId', GAMEID) mo.setResult('userId', userId) mo.setResult('tasks', TodoTaskHelper.encodeTodoTasks(todotask)) router.sendToUser(mo, userId)
def doWinlose(self, msg): tableId = msg.getParam('tableId', 0) if ftlog.is_debug(): ftlog.debug('TYRelaxationMatchRoom.doWinlose', 'tableId=', tableId) userWinloseList = msg.getParam('users') assert (isinstance(userWinloseList, list)) for userWinlose in userWinloseList: userId = userWinlose.get('userId', 0) seatId = userWinlose.get('seatId', 0) isWin = userWinlose.get('isWin', 0) deltaScore = userWinlose.get('deltaScore', 0) if userId > 0: if ftlog.is_debug(): ftlog.debug('TYRelaxationMatchRoom.doWinlose', 'tableId=', tableId, 'userId=', userId, 'seatId=', seatId, 'deltaScore=', deltaScore, 'isWin=', isWin) player = self.match.findPlayer(userId) self.match.winlose(player, deltaScore, isWin) # 归还桌子以及更新比赛排名 table = self.match.findTable(tableId) if table: self.match.tableController.notifyTableClearTable(table) self.match.returnTable(table)
def _enter(self, userId): ftlog.hinfo("_enter << |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) isOk, checkResult = self.checkSitCondition(userId) if not isOk: return False, checkResult if userId in self._roomUsers: return False, TYRoom.ENTER_ROOM_REASON_CONFLICT if not self.scheduler.enter(userId): return False, TYRoom.ENTER_ROOM_REASON_CONFLICT self._roomUsers.add(userId) if ftlog.is_debug(): ftlog.info("_enter add to _roomUsers.add |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) if ftlog.is_debug(): ftlog.debug(">> |roomId, userId, _roomUsersN: ", self.roomId, userId, len(self._roomUsers), caller=self) ftlog.debug(">> |roomId, userId, _roomUsers: ", self.roomId, userId, self._roomUsers, caller=self) locList = onlinedata.getOnlineLocList(userId) ftlog.debug(">> |roomId, userId, locList:", self.roomId, userId, locList) PlayerRoomDao.clear(userId, self.bigRoomId) # 防止因系统错误造成的数据遗留问题 return True, TYRoom.ENTER_ROOM_REASON_OK
def onEvHttpCommonRequest(self, gameId, msg): ''' 处理 http 消息 这个函数只运行在 HT 里。负责处理一些自己能处理的,其它的息转发给 GR, GT ''' httpRequest, httpArgs = msg.getParams('httpRequest', 'httpArgs') httpResult = msg.getResult('httpResult') for k, v in httpArgs.items(): if len(v) == 1: httpArgs[k] = v[0] if ftlog.is_debug(): ftlog.debug('httpArgs', gameId, httpArgs, caller=self) action = httpArgs.get('a') if action != 'gm': return sa = httpArgs.get('sa') if not sa: if ftlog.is_debug(): ftlog.debug('sa is None') return if sa == 'roomlist': self._do_http_gm_room_list(gameId, httpRequest, httpArgs, httpResult) elif sa == 'playingTableList': self._do_http_gm_playing_table_list(gameId, httpRequest, httpArgs, httpResult) elif sa == 'tableDetail': self._do_http_gm_table_detail(gameId, httpRequest, httpArgs, httpResult)
def getRanking(self, userId, rankingDefine): ''' @return: (TYRankingList, timestamp, rankingList) ''' timestamp = pktimestamp.getCurrentTimestamp() cacheRanking = self._cacheRankings.get(rankingDefine.rankingId) if (not cacheRanking or (timestamp - cacheRanking[1]) >= cacheRanking[0].rankingDefine.cacheTimes or pktimestamp.getDayStartTimestamp(timestamp) != pktimestamp.getDayStartTimestamp(cacheRanking[1])): cacheRanking = self._getRanking(rankingDefine, timestamp) if cacheRanking: self._cacheRankings[rankingDefine.rankingId] = cacheRanking if ftlog.is_debug(): ftlog.debug('RankTcpHandler.getRanking cache userId=', userId, 'rankingId=', rankingDefine.rankingId, 'rankingIssueNumber=', cacheRanking[0].issueNumber, 'rankingCycle=', ('[%s,%s)' % (cacheRanking[0].timeCycle.startTime, cacheRanking[0].timeCycle.endTime)), 'timestamp=', datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'), 'data=', cacheRanking[2]) else: if rankingDefine.rankingId in self._cacheRankings: del self._cacheRankings[rankingDefine.rankingId] if ftlog.is_debug(): ftlog.debug('RankTcpHandler.getRanking remove userId=', userId, 'rankingId=', rankingDefine.rankingId) return cacheRanking
def selectProduct(gameId, userId, clientId, templateName, action): template = hallconf.getChargeLeadTemplate(templateName) if not template: return None, None payOrder = template.get(action) if not payOrder: if ftlog.is_debug(): ftlog.debug('hallproductselector.selectProduct gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'templateName=', templateName, 'template=', template, 'action=', action, 'err=', 'EmptyPayOrder') return None, None if ftlog.is_debug(): ftlog.debug('hallproductselector.selectProduct gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'templateName=', templateName, 'template=', template, 'action=', action, 'payOrder=', payOrder) return hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder)
def doQuickStart(self, msg): ''' Note: 1> 每个房间一张桌子 2> 房间分为激活和非激活状态 3> 选择激活房间中人数最少的 ''' assert self.roomId == msg.getParam("roomId") userId = msg.getParam("userId") shadowRoomId = msg.getParam("shadowRoomId") tableId = msg.getParam("tableId") clientId = msg.getParam("clientId") ftlog.hinfo("doQuickStart <<", "|userId, clientId, roomId, shadowRoomId, tableId:", userId, clientId, self.roomId, shadowRoomId, tableId, caller=self) if tableId == 0: # 选择激活房间中人数最少的 shadowRoomId = self.roomDefine.shadowRoomIds[0] for rid in self.roomDefine.shadowRoomIds[1:]: if rid in self.isActive and \ len(self.roomUsers[rid]) < len(self.roomUsers[shadowRoomId]): shadowRoomId = rid break tableId = shadowRoomId * 10000 + 1 if not tableId: ftlog.error(getMethodName(), "getFreeTableId timeout", "|userId, roomId, tableId:", userId, self.roomId, tableId) return if ftlog.is_debug(): ftlog.info("after choose table", "|userId, shadowRoomId, tableId:", userId, shadowRoomId, tableId, caller=self) self.doEnter(userId) self.roomUsers[shadowRoomId].add(userId) self.userCountTotal += 1 if ftlog.is_debug(): ftlog.debug("|shadowRoomId, userId, self.roomUsers[shadowRoomId]", shadowRoomId, userId, self.roomUsers[shadowRoomId], "|self.userCountTotal:", self.userCountTotal, caller=self) # 增加active room if self.roomConf["openTableRatio"] * self.tableConf["maxSeatN"] * len(self.isActive) <= self.userCountTotal: if ftlog.is_debug(): ftlog.debug("|userId, self.roomDefine.shadowRoomIds[1:]:", userId, self.roomDefine.shadowRoomIds[1:], caller=self) for rid in self.roomDefine.shadowRoomIds[1:]: if rid not in self.isActive: self.isActive.add(rid) if ftlog.is_debug(): ftlog.debug("add active room |shadowRoomId, userId, self.roomUsers[shadowRoomId]", shadowRoomId, userId, self.roomUsers[shadowRoomId], "|self.userCountTotal, self.isActive:", self.userCountTotal, self.isActive, caller=self) break extParams = msg.getKey('params') self.sendSitReq(userId, shadowRoomId, tableId, clientId, extParams)
def flipCard(gameId, userId, clientId, roomId, paddingsCount): ''' 翻牌 @return: flippedCard, paddingsCardList ''' timestamp = pktimestamp.getCurrentTimestamp() ctx = FlipCardContext(gameId, userId, clientId, roomId) flipableCard = _flipCardPolicyTable.selectPolicy(ctx).randomCard() if ftlog.is_debug(): ftlog.debug('FlipCardService.flipCard gameId=', gameId, 'userId=', userId, 'roomId=', roomId, 'roomMinChip=', ctx.roomMinChip, 'userAllChip=', ctx.userAllChip, 'userVipLevel=', ctx.userVip.vipLevel.level, 'minBuyChip=', ctx.minBuyChip, 'flipableCard=', flipableCard) flippedCard = flipableCard.flip(ctx) if not flippedCard: ftlog.debug('FlipCardService.flipCard gameId=', gameId, 'userId=', userId, 'roomId=', roomId, 'roomMinChip=', ctx.roomMinChip, 'userAllChip=', ctx.userAllChip, 'userVipLevel=', ctx.userVip.vipLevel.level, 'minBuyChip=', ctx.minBuyChip, 'flipableCard=', flipableCard, 'err=', 'NoFlippedCard') raise FlipCardException(-1, 'System error') if isinstance(flippedCard, FlippedCardAsset): userAssets = hallitem.itemSystem.loadUserAssets(userId) userAssets.addAsset(gameId, flippedCard.assetKind.assetKindId, timestamp, 'ACTIVITY_FAN_PAI', 0) if flippedCard.assetKind.keyForChangeNotify: datachangenotify.sendDataChangeNotify(gameId, userId, flippedCard.assetKind.keyForChangeNotify) paddingsCardList = _paddingCard(ctx, paddingsCount) if ftlog.is_debug(): paddingsCardsStrs = [] for paddingsCard in paddingsCardList: paddingsCardsStrs.append(str(paddingsCard)) ftlog.debug('FlipCardService.flipCard gameId=', gameId, 'userId=', userId, 'roomId=', roomId, 'roomMinChip=', ctx.roomMinChip, 'userAllChip=', ctx.userAllChip, 'userVipLevel=', ctx.userVip.vipLevel.level, 'minBuyChip=', ctx.minBuyChip, 'flipableCard=', flipableCard, 'paddingsCards', paddingsCardsStrs) while len(paddingsCardList) < paddingsCount: paddingsCardList.append(flippedCard) return flippedCard, paddingsCardList
def findNextEmptySeat(self, seatIndex): if ftlog.is_debug(): ftlog.debug('<< |tableId, seatIndex, seats:', self.table.tableId, seatIndex, self, caller=self) nextSeatIndex = self.findNextSeat(seatIndex) while nextSeatIndex != seatIndex and not self[nextSeatIndex].isEmptySeat(): nextSeatIndex = self.findNextSeat(nextSeatIndex) if ftlog.is_debug(): ftlog.debug('>> |tableId, nextSeatIndex:', self.table.tableId, nextSeatIndex, caller=self) return nextSeatIndex
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})
def doGetSoldierInfo(userId, gameId, clientId): ''' 将小兵的配置信息进行解析,并且将需要下发的信息进行下发 获取当前的时间,判断是否在时间区间内部,只返回当前的时间区间 ''' tempTemplate = getSnatchConf() soldierInfo = {} soldierInfo['desc'] = tempTemplate.get('desc', '') soldierInfo['picUrl'] = tempTemplate.get('picUrl', '') soldierInfo['endTime'] = tempTemplate.get('endTime', '') soldierInfo['startTime'] = tempTemplate.get('startTime', '') soldierInfo['needNumber'] = tempTemplate.get('needNumber', 0) nowPeople = [] soldierInfo['issue'] = time.strftime("%Y%m%d", time.localtime()) + getIssue(False) tempNumber = getSoldierNumber() needNumber = tempTemplate.get('needNumber', 0) if tempNumber - needNumber > 0: tempNumber = needNumber soldierInfo['nowNumber'] = tempNumber mySoldier = [] allSoldier = daobase.executeMixCmd('LRANGE', CURKEY, 0, needNumber - 1) if allSoldier: sLen = len(allSoldier) if ftlog.is_debug(): ftlog.debug('hallroulette.doGetSoldierInfo allSoldier len:', sLen) for index in range(0, sLen): if ftlog.is_debug(): ftlog.debug('hallroulette.doGetSoldierInfo now soldier index:', index , ' soldier id:', allSoldier[index] , ' userId:', userId) if allSoldier[index] == userId: sId = getSoldierIdByIndex(index) mySoldier.append(sId) if allSoldier[index] not in nowPeople: nowPeople.append(allSoldier[index]) if ftlog.is_debug(): ftlog.debug('hallroulette.doGetSoldierInfo mySoldiers:', mySoldier , ' nowPeople:', nowPeople) soldierInfo['mySoldiers'] = mySoldier soldierInfo['nowPeople'] = len(nowPeople) result = {} result['soldierInfo'] = soldierInfo if ftlog.is_debug(): ftlog.debug('hallroulette.doGetSoldierInfo result:', result) return result
def appendOneActiveTable(self): if ftlog.is_debug(): ftlog.debug(">>|roomId, self.lastActiveTableId:", self.roomId, self.lastActiveTableId, caller=self) self.lastActiveTableId += 1 self._activeTables[self.lastActiveTableId] = self._hidenTables[self.lastActiveTableId] self.updateTableScore(self.lastActiveTableId % 10000, self.lastActiveTableId, force=True) # 确保最后一个activeTable评分最高 del self._hidenTables[self.lastActiveTableId] if ftlog.is_debug(): ftlog.info("addNewActiveTable <<|roomId, self.lastActiveTableId:", self.roomId, self.lastActiveTableId, caller=self)
def addPresentNum(self, gameId, userId, clientId, presentNum): activityId = self._clientConf.get("id") if not activityId: if ftlog.is_debug(): ftlog.debug("TYActivityPlayGamePresentGift.addPresentNum not find adtivityId") return if not self.checkOperative(): if ftlog.is_debug(): ftlog.info("TYActivityPlayGamePresentGift.addPersentNum activity expired:", activityId) return # 有效时间 if "dayTimeLimit" in self._serverConf: if not self._checkDayTime(): ftlog.debug("TYActivityPlayGamePresentGift.addPersentNum, dayTimeLimit not match") return # 是否可连续,1表示1天内连续、0表示可连续 accumulateType = self._serverConf["accumulateType"] # 需要领取奖励的局数 rewardNeedNum = self._serverConf["rewardNeedNum"] accumulateKey = "accumulate" accumulateValue = 1 hasRewardedKey = "hasRewarded" if accumulateType == 1: accumulateKey = "%s:%s" % (accumulateKey, time.strftime('%Y-%m-%d', time.localtime(time.time()))) hasRewardedKey = "%s:%s" % (hasRewardedKey, time.strftime('%Y-%m-%d', time.localtime(time.time()))) mustContinuous = 0 maxInterval = 0 accumulateIdentiferValue = "noidentifer" nowTimeStamp = int(time.time()) if 'accumulateMustContinuous' in self._serverConf: if self._serverConf["accumulateMustContinuous"] == 1: mustContinuous = 1 maxInterval = self._serverConf.get("accumulateMaxInterval", 300) userActivityKey = "TYActivity:%d:%d:%s" % (gameId, userId, activityId) if ftlog.is_debug(): ftlog.debug("TYActivityPlayGamePresentGift.addPresentNum:", presentNum, accumulateKey, accumulateValue, accumulateType, accumulateIdentiferValue, mustContinuous, maxInterval, userActivityKey, rewardNeedNum, nowTimeStamp, hasRewardedKey) ret = daobase.executeUserLua(userId, self.HANDLE_EVENT_SCRIPT, 11, presentNum, accumulateKey, accumulateValue, accumulateType, accumulateIdentiferValue, mustContinuous, maxInterval, userActivityKey, rewardNeedNum, nowTimeStamp, hasRewardedKey) if ftlog.is_debug(): ftlog.debug("TYActivityPlayGamePresentGift.addPresentNum executeUserLua ret:", ret)
def _initIdleTableIds(self): self.idleTableIds = [] shadowRoomIds = self.room.roomDefine.shadowRoomIds if ftlog.is_debug(): ftlog.debug("<<", self.baseLogStr(), '|shadowRoomIds=', list(shadowRoomIds)) for shadowRoomId in shadowRoomIds: for i in xrange(self.room.roomDefine.configure['gameTableCount']): self.idleTableIds.append(shadowRoomId * 10000 + i + 1) random.shuffle(self.idleTableIds) if ftlog.is_debug(): ftlog.debug("_initIdleTableIds >>", self.baseLogStr(), '|len(shadowRoomIds), len(idleTableIds):', len(shadowRoomIds), len(self.idleTableIds))
def __buildRankData(self): now = time.time() if now - self.lastBuildTime < self.BUILD_RANKING_INTERVAL: return self.lastBuildtime = now results = {'roomId': self.bigRoomId} results['matchType'] = self.room.matchPlugin.match_room_confs[self.room.bigRoomId].get("matchType", "") results['ranks'] = [] leftPlayers = [(userId, 0) for userId in daobase.executeRankCmd("LRANGE", self.room.matchPlugin.rankingKey(self.bigRoomId), 0, -1)] # 淘汰的 if ftlog.is_debug(): ftlog.debug("get leftPlayers", "|", leftPlayers, caller=self) playingPlayersWithScores = list(pairwise( daobase.executeRankCmd("ZRANGE", self.room.matchPlugin.playingRankingKey(self.bigRoomId), 0, -1, 'WITHSCORES'))) if ftlog.is_debug(): ftlog.debug("get playingPlayersWithScores", "|", playingPlayersWithScores) allPlayers = list(reversed(leftPlayers + playingPlayersWithScores)) # 1, 2, ... 最后一名 if ftlog.is_debug(): ftlog.debug("get all players", "|", allPlayers) self.userRanking = {} self.ranks = [] for i, (userId, tableChip) in enumerate(allPlayers): name, purl, photo = self.getUData(userId) rankItem = { 'id': userId, 'tableChip': tableChip, 'name': name, 'purl': purl, 'head': photo, 'rank': i + 1, } if results['matchType'] in ['hunter', 'snowball']: self.setHunterInfo(userId, rankItem) self.ranks.append(rankItem) self.userRanking[userId] = i results['totalPlayersNum'] = len(playingPlayersWithScores) results['pos'] = 1 self.rankResults = results self.rankResultsForSend = strutil.cloneData(results) self.rankResultsForSend['ranks'] = strutil.cloneData(self.ranks[:30]) # 3.6 以前版本,发30个 self.rankResultsForSend_3_6 = strutil.cloneData(results) blank = {'id': 0, 'tableChip': 0, 'name': '', 'purl': '', 'rank': 1} self.rankResultsForSend_3_6['ranks'] = strutil.cloneData([blank] + self.ranks[:30]) # 3.6 以后版本,发31个,第一个是自己
def getBestTableId(self, userId, shadowRoomId, exceptTableId=None): '''原子化从redis里获取和删除评分最高的桌子Id Return: None: tableScores 队列为空, 所有桌子都在分配座位中 ''' def getBestTableIdFromRedis(shadowRoomId): '''从redis里取出并删除一个评分最高的牌桌 ''' tableId, tableScore = 0, 0 datas = daobase.executeTableLua(shadowRoomId, 0, room_scripts.ALIAS_GET_BEST_TABLE_ID_LUA, 1, self.getTableScoresKey(shadowRoomId), 0) if datas and len(datas) == 2: tableId, tableScore = datas[0], datas[1] return tableId, tableScore if ftlog.is_debug(): ftlog.debug("<<", "|shadowRoomId, exceptTableId:", shadowRoomId, exceptTableId, caller=self) pigTables = [] tableId = 0 for _ in xrange(5): # 所有桌子有可能正在分配座位,如果取桌子失败,需要休眠后重试 if gdata.roomIdDefineMap()[shadowRoomId].tableCount == 1: tableId = shadowRoomId * 10000 + 1 tableScore = 100 else: tableId, tableScore = getBestTableIdFromRedis(shadowRoomId) # 从redis取一个牌桌 # 该牌桌被客户端指定排除了,另外再取一个牌桌 if exceptTableId and tableId and exceptTableId == tableId: tableId1, tableScore1 = getBestTableIdFromRedis(shadowRoomId) # 把之前从redis取出的牌桌加回redis self._updateTableScore(shadowRoomId, tableScore, tableId, force=True) tableId, tableScore = tableId1, tableScore1 if ftlog.is_debug(): ftlog.debug('getBestTableId shadowRoomId, tableId, tableScore=', shadowRoomId, tableId, tableScore) if tableId: if TYGame(self.gameId).isWaitPigTable(userId, self, tableId): pigTables.append([shadowRoomId, tableScore, tableId]) tableId = 0 continue else: break else: FTTasklet.getCurrentFTTasklet().sleepNb(0.2) if ftlog.is_debug(): ftlog.debug('getBestTableId pigTables=', pigTables) if pigTables: for pig in pigTables: self._updateTableScore(pig[0], pig[1], pig[2], False) return tableId
def checkReConnect(cls, userId, clientId, gameId): loc = onlinedata.checkUserLoc(userId, clientId, gameId) if ftlog.is_debug(): ftlog.debug('checkUserLoc |userId, gameId, loc:', userId, gameId, loc, caller=cls) if isinstance(loc, basestring): lgameId, lroomId, ltableId, lseatId = strutil.parseInts(*loc.split('.')) if lgameId == gameId and lroomId > 0: if ftlog.is_debug(): ftlog.debug('re-connected |userId, gameId, loc:', userId, gameId, loc, caller=cls) TYRoomMixin.querySitReq(userId, lroomId, ltableId, clientId) return True return False
def _onPlayerSignin(event): conf = hallconf.getPublicConf('match_360kp', None) if not conf or not isinstance(conf, dict): if ftlog.is_debug(): ftlog.debug('match360kp.onPlayerSignin NoConf userId=', event.userId, 'matchId=', event.matchId, 'signinParams=', event.player.signinParams, 'snsId=', event.player.snsId, 'conf=', conf) return callbackUrl = conf.get('signinCallbackUrl') if not callbackUrl: if ftlog.is_debug(): ftlog.debug('match360kp.onPlayerSignin NoCallbackUrl userId=', event.userId, 'matchId=', event.matchId, 'signinParams=', event.player.signinParams, 'snsId=', event.player.snsId, 'conf=', conf) return timestamp = pktimestamp.getCurrentTimestamp() params = getParamsByPlayer(event.player, timestamp) if not params: if ftlog.is_debug(): ftlog.debug('match360kp.onPlayerSignin NoParams userId=', event.userId, 'matchId=', event.matchId, 'signinParams=', event.player.signinParams, 'snsId=', event.player.snsId, 'conf=', conf) return sign = signin('REGIST', params) params['sign'] = sign result = webpage.webgetJson(callbackUrl, datas=params, appKey=None, timeout=conf.get('timeout', 3)) if ftlog.is_debug(): ftlog.debug('match360kp.onPlayerSignin userId=', event.userId, 'matchId=', event.matchId, 'signinParams=', event.player.signinParams, 'snsId=', event.player.snsId, 'conf=', conf, 'result=', result) if 'errno' in result: ftlog.warn('match360kp.onPlayerSignin userId=', event.userId, 'matchId=', event.matchId, 'signinParams=', event.player.signinParams, 'snsId=', event.player.snsId, 'conf=', conf, 'result=', result)
def devidePackage(self): ''' 将整体红包按照配置分成随机的份数 ''' global _redEnvelopeConfig # 划分红包 prizePool = [] for item in self.contents: for _ in range(1, item['count'] + 1): prizePool.append(item['itemId']) countTotal = len(prizePool) random.shuffle(prizePool) index = 0 while index < countTotal: # 随机获得红包的个数 count = random.randint(self.minCount, self.maxCount) if index + count >= countTotal: count = countTotal - index; if ftlog.is_debug(): ftlog.debug('count:', count) prizes = {} for i in range(0, count): # 领取红包 itemId = prizePool[index + i] if itemId in prizes: prizes[itemId] += 1 else: prizes[itemId] = 1 if ftlog.is_debug(): ftlog.debug('prizes:', prizes) # 写数据库 daobase.executeMixCmd('LPUSH', self.dbPrefix + self.id + self.PACKAGES, json.dumps(prizes)) # 记录分包信息 self.packages_his.append(prizes) index += count # 设置过期时间 daobase.executeMixCmd('expire', self.dbPrefix + self.id + self.PACKAGES, self.expiredTime) # save result to log if ftlog.is_debug(): checksJson = daobase.executeMixCmd('LRANGE', self.dbPrefix + self.id + self.PACKAGES, 0, -1) ftlog.debug('TYRedEnvelope.devidePackage packages: ', checksJson)
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))
def calcEmptySeatN(self, startSeatIndex, endSeatIndex): if ftlog.is_debug(): ftlog.debug('<< |tableId, startSeatIndex, endSeatIndex, seats:', self.table.tableId, startSeatIndex, endSeatIndex, self, caller=self) nextSeatIndex = self.findNextSeat(startSeatIndex) emptySeatN = 0 while nextSeatIndex != endSeatIndex: if self[nextSeatIndex].isEmptySeat(): emptySeatN += 1 nextSeatIndex = self.findNextSeat(nextSeatIndex) if ftlog.is_debug(): ftlog.debug('>> |tableId, emptySeatN:', self.table.tableId, emptySeatN, caller=self) return emptySeatN
def filterProductsByShelvesList(shelvesList, filters, comparator): # key=productId, value=(product, shelves) ret = [] productSet = set() for shelves in shelvesList: for product in shelves.productList: if product not in productSet and doFilter(product, filters): ret.append((product, shelves)) productSet.add(product) if ftlog.is_debug(): ftlog.debug('hallstore.filterProductsByShelvesList before sort' 'shelves=', [shelves.name for shelves in shelvesList], 'ret=', [(p.productId, s.name) for p, s in ret]) if comparator: ret.sort(cmp=lambda x, y: comparator(x[0], y[0])) return ret
def deductionRechargeBonus(self, coin): """ 扣减充值奖池 """ if self.table.typeName not in config.RECHARGE_BONUS_ROOM_TYPE: return if not self.player or not self.player.userId: return self._currRechargeBonus -= int(coin) self.decreasedRechargeBonus += int(coin) if ftlog.is_debug(): ftlog.debug("deductionRechargeBonus->", "userId =", self.player.userId, "_originRechargeBonus =", self._originRechargeBonus, "_currRechargeBonus =", self._currRechargeBonus, "decreasedRechargeBonus =", self.decreasedRechargeBonus)
def _sendHttpMessage(params, needresponse=True): if params: jsonstr, _ = webpage.webget(_serverUrl, postdata_=params, needresponse=needresponse) if ftlog.is_debug(): ftlog.debug('JiGuangPush._sendHttpMessage', 'url=', _serverUrl, 'params=', params, 'res=', jsonstr) if needresponse: try: data = strutil.loads(jsonstr) return data['code'] except Exception, e: ftlog.error('JiGuangPush._sendHttpMessageError=', e.message) return BAD_RESPONSE return None
def loadUserData(userId, rankId, issueNum): jstr = None try: key = buildUserDataKey(rankId, issueNum) jstr = daobase.executeRePlayCmd('hget', key, userId) if ftlog.is_debug(): ftlog.debug('activityScoreRank loadUserData userId=', userId, 'rankId=', rankId, 'issueNum=', issueNum, 'jstr=', jstr) if jstr: d = strutil.loads(jstr) return UserData(userId, rankId, issueNum).fromDict(d) except: ftlog.error('loadUserData userId=', userId, 'rankId=', rankId, 'issueNum=', issueNum, 'jstr=', jstr) return None
def doRoomRevival(self, roomId, userId): msg = runcmd.getMsgPack() room = gdata.rooms()[roomId] if ftlog.is_debug(): ftlog.debug('DizhuRoomTcpHandler.doRoomRevival', 'userId=', userId, 'msg=', msg, 'mode=', gdata.mode(), caller=self) if isinstance(room, DizhuRoom): room.handleMsg(msg) else: pass
def loadSubMemberStatus(userId): isYouyifuVipUser, youyifuVipMsg = userdata.getAttrs(userId, ['isYouyifuVipUser', 'youyifuVipMsg']) isSub = isYouyifuVipUser == 1 if ftlog.is_debug(): ftlog.debug('hallsubmember.loadSubMemberStatus userId=', userId, 'isYouyifuVipUser='******'youyifuVipMsg=', youyifuVipMsg) youyifuVipMsg = str(youyifuVipMsg) if youyifuVipMsg is not None else None nowDT = datetime.now() status = _loadSubMemberStatus(userId) status.isSub = isSub status.unsubDesc = youyifuVipMsg if status.isSub and not status.subDT: status.subDT = nowDT _adjustExpiresDT(status, nowDT) return status
def _addMultipleFishGroup(self): """添加倍率鱼群""" randomNum = random.randint(1, 10000) for multipleFishMap in config.getRandomMultipleFishConf( self.table.runConfig.fishPool): probb = multipleFishMap["probb"] if probb[0] <= randomNum <= probb[-1]: fishType = multipleFishMap["fishType"] allMultipleGroupIds = self.table.runConfig.allMultipleGroupIds groupId = random.choice(allMultipleGroupIds[fishType]) if ftlog.is_debug(): ftlog.debug("_addMultipleFishGroup", fishType, allMultipleGroupIds, groupId) self.table.insertFishGroup(groupId) self._setNextGroupTimer() break
def _loadCfgRobotNamesAndUrls(): global _userNames global _headUrls if _inited: conf = configure.getGameJson(HALL_GAMEID, 'robots', {}, '0') names = conf.get('names') headUrls = conf.get('headUrls') if ftlog.is_debug(): ftlog.debug('hall_robot_user._loadCfgRobotNamesAndUrls', 'names=', names, 'headUrls=', headUrls) if names: _userNames = names if headUrls: _headUrls = headUrls
def translateToMsgDictV1(msgDict): tasks = msgDict.get('tasks') if tasks: # 有tasks的只有V2, V3支持 return None msgstr = '' richTextList = msgDict.get('text', []) for richText in richTextList: text = richText.get('text') if text: msgstr += text if ftlog.is_debug(): ftlog.debug('hallled.translateToMsgDictV1 msgDict=', msgDict, 'msgstr=', msgstr) return msgstr
def frozenTentacleFish(self, frozenTime): """ 触手被冻住 """ self.frozenTime += frozenTime # 刷新触手收回动画开始和结束时间 self.retractTime = self.calcRetractTime() self.finalTime = self.calcFinalTime() stageTime = self.getCurrentStateStageTime() interval = stageTime[1] - pktimestamp.getCurrentTimestamp() if ftlog.is_debug(): ftlog.debug("frozenTentacleFish", self.frozenTime, self.retractTime, interval) self._swingTimer and self._swingTimer.cancel() self._swingTimer = FTLoopTimer(interval, 0, self._doRetract) self._swingTimer.start()
def _do_ad_info(cls, userId, gameId, clientId): msg = MsgPack() msg.setCmd('dizhu') msg.setResult('action', 'ad_info') msg.setResult('gameId', gameId) msg.setResult('userId', userId) msg.setResult('clientId', clientId) msg.setResult('leftWatchAdCount', WatchAdHelper.getUserLeftWatchAdCount(userId)) msg.setResult('adCDMinutes', WatchAdHelper.getCDMinutes()) if ftlog.is_debug(): ftlog.debug('SegmentMatchHandler.ad_info' 'userId=', userId, 'gameId=', gameId, 'clientId=', clientId, 'msg=', msg._ht) return msg
def getProbbCoefficient(self, player, fishInfo): """概率基数""" if fishInfo["type"] in [3, 21] or fishInfo["multiple"] > 1: j1 = player.matchLuckyValue / 7500.0 + 1.0 / 3 c = self._match_table_info["realPlayerCount"] k = float(4 * c) / (3 * c - 1) b = 1 - float(2 * c) / (3 * c - 1) j2 = 1 #k * min(player.rank, c) / c + b j = (j1 + j2) * 0.5 if ftlog.is_debug(): ftlog.debug("getProbbCoefficient", player, fishInfo, "luckyValue =", player.matchLuckyValue, "rank =", player.rank, "j1 =", j1, "c =", c, "k =", k, "b =", b, "j2 =", j2, "j =", j) return j return 1
def getPlayingLen(self): """由于playing 列表有未知问题,改用enterMatchTotal - rankingLen来反推,并报异常方便查错。 """ # 这种方式比分别访问3次 redis 快3倍左右。访问3次redis需要将近1秒 playingLen, rankingLen, enterMatchTotal = daobase.executeRankCmd("EVALSHA", self.getPlayinLenLuaSha, 0) if playingLen + rankingLen != enterMatchTotal: ftlog.error(getMethodName(), "playingLen + rankingLen != enterMatchTotal", "|roomId, playingLen, rankingLen:", self.roomId, playingLen, rankingLen, "|enterMatchTotal:", enterMatchTotal) if ftlog.is_debug(): ftlog.info(">>", "|roomId, playingLen, rankingLen:", self.roomId, enterMatchTotal - rankingLen, rankingLen, caller=self) return enterMatchTotal - rankingLen
def _sendTodoTaskBuyChip(cls, userId, roomId, clientId, mixId): if ftlog.is_debug(): ftlog.debug('DizhuQuickStart._sendTodoTaskBuyChip', 'userId=', userId, 'roomId=', roomId, 'clientId=', clientId, 'mixId=', mixId) bigRoomId = gdata.getBigRoomId(roomId) ctrRoomId = bigRoomId * 10000 + 1000 roomConfig = gdata.roomIdDefineMap()[ctrRoomId].configure mixConfRoomId = cls.getMixConf(roomConfig, mixId).get('roomId', 0) if roomConfig.get('isMix', 0) and mixConfRoomId: roomId = mixConfRoomId todotask = hallpopwnd.makeTodoTaskLessbuyChip(DIZHU_GAMEID, userId, clientId, roomId, minCoin=cls.getMixConf(roomConfig, mixId).get('minCoin', None)) if todotask: TodoTaskHelper.sendTodoTask(DIZHU_GAMEID, userId, todotask)
def doGetSoldierForUser(self, userId, gameId, clientId): ''' 客户端点击事件 获取用户的历史小兵信息 ''' msg = runcmd.getMsgPack() issue = msg.getParam('issue') if ftlog.is_debug(): ftlog.debug('doGetSoldierForUser.userId:', userId , ' gameId:', gameId , ' clientId:', clientId , ' issue:', issue) result, _, _ = hallroulette.doGetSoldierIdForUser(userId, gameId, clientId, issue) mo = rouletteHelper.makeRouletteQueryResponse(gameId, userId, clientId, 'issue_user', result) router.sendToUser(mo, userId)
def buyin(self, table, player, seat, continueBuyin): if not continueBuyin: player.score = table.room.roomConf['initScore'] if player.score <= 0: player.score = table.room.roomConf['initScore'] player.datas['buyinMark'] = 1 player.datas['buyinChip'] = player.score player.datas['buyinTip'] = '系统重新给您补充了积分' if ftlog.is_debug(): ftlog.debug('BuyinPolicyFree.buyin', 'roomId=', table.roomId, 'tableId=', table.tableId, 'seat=', (seat.userId, seat.seatId), 'continueBuyin=', continueBuyin, 'score=', player.score)
def _conform(self, gameId, userAssets, item, timestamp, params): from poker.entity.game.game import TYGame userId = userAssets.userId clientId = sessiondata.getClientId(userId) dashifen = TYGame(self.gameId).getDaShiFen(userId, clientId) level = dashifen.get('level', 0) if dashifen else 0 if ftlog.is_debug(): ftlog.debug('ItemActionConditionGameDashifenLevel._conform gameId=', gameId, 'userId=', userId, 'clientId=', clientId, 'selfGameId=', self.gameId, 'dashifen=', dashifen, 'level=', level, 'minLevel=', self.minLevel, 'maxLevel=', self.maxLevel) return (self.minLevel == -1 or level >= self.minLevel) \ and (self.maxLevel == -1 or level < self.maxLevel)
def loadUserRankInfo(userId, rankId): jstr = None try: key = buildUserRankInfoKey(userId) jstr = daobase.executeRePlayCmd('hget', key, rankId) if ftlog.is_debug(): ftlog.debug('loadUserRankInfo userId=', userId, 'rankId=', rankId, 'jstr=', jstr) if jstr: d = strutil.loads(jstr) return UserRankInfo(userId, rankId).fromDict(d) except: ftlog.error('loadUserRankInfo userId=', userId, 'rankId=', rankId, 'jstr=', jstr) return UserRankInfo(userId, rankId)
def consumeAssets(gameId, userId, contentItems, eventId, intEventParam): if ftlog.is_debug(): ftlog.debug('consumeAssets gameId=', gameId, 'userId=', userId, 'contentItems=', contentItems, 'eventId=', eventId, 'intEventParam=', intEventParam) try: contentItems = decodeContentItems(contentItems) userAssets = hallitem.itemSystem.loadUserAssets(userId) assetList = userAssets.consumeContentItemList( gameId, contentItems, True, pktimestamp.getCurrentTimestamp(), eventId, intEventParam) datachangenotify.sendDataChangeNotify( gameId, userId, TYAssetUtils.getChangeDataNames(assetList)) return None, 0 except TYAssetNotEnoughException, e: return e.assetKind.kindId, e.required - e.actually
def _refreshLuckyBonusRankData(event): """ 刷新玩家幸运榜,七日幸运榜 """ if ftlog.is_debug(): ftlog.debug("_refreshLuckyBonusRankData", event.coinNum) if not event.coinNum: return # 今日榜 rankClass = _getRankingClass(RankType.TodayLucky, event.userId, CLIENTID_ROBOT) rankClass.refreshRankingData(event) # 七日榜 rankClass = _getRankingClass(RankType.WeekLucky, event.userId, CLIENTID_ROBOT) rankClass.refreshRankingData(event)
def onTableGameStart(self, gameId, msg): if ftlog.is_debug(): ftlog.debug("<< |msg", msg, caller=self) table = msg.getParam("table") bireport.tableStart(table.gameId, table.roomId, table.tableId, table.gamePlay.gameSeq, DiFangPlayersHelper.getPlayingPlayersIds(table)) for player in DiFangPlayersHelper.getPlayingPlayers(table): bireport.reportGameEvent('TABLE_START', player.userId, gameId, table.roomId, table.tableId, table.gamePlay.gameSeq, 0, 0, 0, [], sessiondata.getClientId(player.userId), player.tableChips)
def addFriend(cls, userId, userList): '''添加好友''' friendList = cls.getUserFriendList(userId) changed = False for uId in userList: if uId not in friendList and uId != userId: changed = True friendList.append(uId) if ftlog.is_debug(): ftlog.debug('dizhu_friend.FriendHelper.addFriend', 'userId=', userId, 'userList=', userList, 'changed=', changed, 'friendList=', friendList) if changed: daobase.executeUserCmd(userId, 'SET', cls.buildFriendKey(userId), strutil.dumps(friendList))
def enterFriendTable(userId, gameId, clientId, ftId): """进入自建桌""" if ftlog.is_debug(): ftlog.debug('hall_friend_table.enterFriendTable userId:', userId, ' pluginId:', gameId, ' clientId:', clientId, ' ftId:', ftId) pluginId = queryFriendTable(ftId) if not pluginId: TodoTaskHelper.sendTodoTask(HALL_GAMEID, userId, TodoTaskPopTip(ROOM_NOT_EXIST['info'])) responseEnterFriendTable(userId, ROOM_NOT_EXIST) return ftlog.info('hall_friend_table.enterFriendTable userId:', userId, ' lead to pluginId:', pluginId) pluginId = int(pluginId) TYGame(pluginId).enterFriendTable(userId, gameId, clientId, ftId) responseEnterFriendTable(userId, ENTER_FRIEND_OK)
def doDeleteMail(userId, mailIds, mailSenderType): """ 执行删除邮件并发送消息 """ message = MsgPack() message.setCmd("fishMailDelete") message.setResult("gameId", FISH_GAMEID) message.setResult("userId", userId) code = deleteMail(userId, mailIds, mailSenderType) message.setResult("code", code) mails = getAllMail(userId).get(mailSenderType, []) message.setResult("mailType", mailSenderType) message.setResult("mails", mails) router.sendToUser(message, userId) if ftlog.is_debug(): ftlog.debug("doDeleteMail, userId =", userId, "mailIds =", mailIds, "mailSenderType =", mailSenderType, "code =", code)
def _processStartNextGame(self): ''' 不同游戏牌桌子处理开始下一局游戏逻辑, 默认2秒后检查开局 ''' if ftlog.is_debug(): ftlog.debug(self._baseLogStr("<<"), "|gameSeq, gameRoudN:", self.gamePlay.gameSeq, self.selectedRoomOptions["gameRoundN"], caller=self) if self.gamePlay.gameSeq >= self.selectedRoomOptions["gameRoundN"]: self._applyAdjustTablePlayers() return self._resetTableConf()
def _getInfoFromTxt(behaviourConf): try: curDate = datetime.datetime.now().strftime('%Y-%m-%d') fileName = 'dizhu/behaviour/ddz_prediction_%s.txt' % curDate fileName = os.path.join(gdata.pathWebroot(), fileName) ret = os.path.isfile(fileName) if not ret: ftlog.warn('dizhu_user_behaviour.file_not_exist', 'fileName=', fileName, 'ret=', ret) return False index = 0 with open(fileName) as fileObject: for line in fileObject: index += 1 if not line: break infos = line.split('\t') userId = infos[0] status = infos[1].split('\n')[0] try: userId = int(userId) except ValueError: ftlog.warn('dizhu_user_behaviour.ValueError userId=', userId) continue if not _saveUserToRedis(userId, status, behaviourConf): continue if ftlog.is_debug(): ftlog.debug('dizhu_user_behaviour.DIZHU_BEHAVIOUR_GROUP', 'userId=', userId, 'state=', status) # 1000行sleep 0.1秒 if index >= 1000: index = 0 FTTasklet.getCurrentFTTasklet().sleepNb(0.1) ftlog.info('dizhu_user_behaviour.fileLoadOver fileName=', fileName) except Exception, e: ftlog.warn('dizhu_user_behaviour.loadConf. error=', str(e)) return False
def reloadConf(self, conf): taskUnitMap = {} task_unit_types = set() taskKindMap = {} taskUnitDictList = conf.get('taskUnits', []) if len(taskUnitDictList) == 0: return for taskUnitDict in taskUnitDictList: taskUnit = TYTaskUnit( self._task_kind_pool_cls).decodeFromDict(taskUnitDict) if taskUnit.taskUnitId in taskUnitMap: raise TYTaskConfException( taskUnitDict, 'Duplicate taskUnit gameId=%s %s' % (self.gameId, taskUnit.taskUnitId)) for taskKind in taskUnit.taskKindMap.values(): if taskKind.kindId in taskKindMap: raise TYTaskConfException( taskUnitDict, 'Duplicate taskKind gameId=%s %s' % (self.gameId, taskKind.kindId)) taskKindMap[taskKind.kindId] = taskKind taskUnitMap[taskUnit.taskUnitId] = taskUnit task_unit_types.add(taskUnit.typeid) taskUnit._taskSystem = self taskUnit._subTaskSystem = self._subTaskSystemMap.get( taskUnit.typeid) for task_unit_type in self._subTaskSystemMap.iterkeys(): # 检查所有的子任务系统是否配置了taskUnit if task_unit_type not in task_unit_types: raise TYTaskConfException( conf, 'Not found task_unit_type %s' % task_unit_type) self._unregisterEvents() self._taskUnitMap = taskUnitMap self._taskKindMap = taskKindMap for taskunit in taskUnitMap.itervalues(): sub_sys = self._subTaskSystemMap.get(taskunit.typeid) if sub_sys: sub_sys.onTaskUnitLoaded(taskunit) self._registerEvents() self._loaded = True if ftlog.is_debug(): ftlog.debug('TYTaskSystemImpl.reloadConf successed units=', self._taskUnitMap.keys(), 'kindIds=', self._taskKindMap.keys(), 'subTaskSystem=', self._subTaskSystemMap.keys())
def _onGameRoundOver(self, event): if ftlog.is_debug(): ftlog.debug('ReplayTable._onGameRoundOver', 'tableId=', event.table.tableId, 'seats=', [(s.userId, s.seatId) for s in event.table.seats]) seatWinloseDetails = [] for sst in event.gameResult.seatStatements: skillInfo = sst.skillscoreInfo seatWinloseDetails.append( SeatWinloseDetail( { 'score': skillInfo['score'], 'level': skillInfo['level'], 'premax': skillInfo['premaxscore'], 'curmax': skillInfo['curmaxscore'], 'add': skillInfo['addScore'] }, sst.seat.status.totalMulti, sst.winStreak, sst.delta, sst.final)) gslams = [] seatIndex = 0 for index, seat in enumerate(event.table.seats): if event.gameResult.gameRound.dizhuSeat == seat: seatIndex = index gslams.append(seat.player.mixConf.get('tableConf').get('gslam')) winloseDetail = WinloseDetail( event.gameResult.gameRound.result, event.gameResult.gameRound.bombCount, event.gameResult.gameRound.isChuntian, event.gameResult.gameRound.showMulti, event.gameResult.gameRound.baseCardMulti, event.gameResult.gameRound.rangpaiMulti, event.gameResult.gameRound.callMulti, event.gameResult.gameRound.totalMulti, 1 if event.gameResult.gameRound.result == GameRound.RESULT_DIZHU_WIN else 0, 1 if event.gameResult.slam else 0, gslams[seatIndex], seatWinloseDetails) # 这里已地主视角 复写replay gameRound self._curRound.roomName = self.names[seatIndex] self._curRound.grab = self.grabs[seatIndex] self._curRound.roomMulti = self.roomMutils[seatIndex] self._curRound.roomFee = self.roomFees[seatIndex] self._curRound.gameWinlose(winloseDetail) self._curRound.gameOverTimestamp = pktimestamp.getCurrentTimestamp() self._clearReplayRound()
def sendMinigameInfo(roomId, userId, mode): """ 发送小游戏信息 """ bigRoomId, _ = util.getBigRoomId(roomId) subkey = "%s_%d" % (bigRoomId, mode) mgType = config.getSuperBossCommonConf().get(str(subkey), {}).get("mgType", "") key = "%s_%d" % (mgType, mode) mo = MsgPack() mo.setCmd("superboss_minigame_info") mo.setResult("gameId", FISH_GAMEID) mo.setResult("userId", userId) mo.setResult("roomId", roomId) mo.setResult("mode", mode) mo.setResult("type", mgType) data = {} if mgType in MINIGAME_TYPE_LIST: conf = config.getSuperBossMiniGameConf() superbossPlayedTimes = weakdata.getDayFishData(userId, WeakData.superbossMGPlayedTimes, {}) playedTimes = superbossPlayedTimes.get(key, 0) vipLevel = hallvip.userVipSystem.getUserVip(userId).vipLevel.level maxTimesList = conf.get("info", {}).get(key, {}).get("maxTimes", []) maxTimes = maxTimesList[vipLevel] if maxTimesList and len(maxTimesList) > vipLevel else 0 remainTimes = max(0, maxTimes - playedTimes) if maxTimes >= 0 else -1 currencyList = conf.get("info", {}).get(key, {}).get("currencyList", []) items = config.rwcopy(conf.get("game", {}).get(key, [])) gunLevelVal = util.getGunLevelVal(userId, config.MULTIPLE_MODE) lang = util.getLanguage(userId) itemsinfo = [] for item in items: if gunLevelVal >= item["level"]: item["des"] = config.getMultiLangTextConf(item["des"], lang=lang) if item["des"] else "" itemsinfo.append(item) if mgType == "box": for iteminfo in itemsinfo: rewards = iteminfo["rewards"] groupIdx = util.selectIdxByWeight([int(reward.keys()[0]) for reward in rewards]) iteminfo["rewards"] = rewards[groupIdx].values()[0] iteminfo["groupIdx"] = groupIdx mo.setResult("showItemsList", currencyList) data = {"remainTimes": remainTimes, "items": itemsinfo} else: ftlog.warn("minigame, type error, userId =", userId, "roomId =", roomId, "mode =", mode, "mgType =", mgType) mo.setResult("data", data) router.sendToUser(mo, userId) if ftlog.is_debug(): ftlog.debug("minigame, userId =", userId, "mode =", mode, "mo =", mo)
def _decodeFromDictImpl(self, d): self._open = d.get('open') if not isinstance(self._open, int): raise TYBizConfException(d, 'ActivityChristmas.open must be int') self._mail = d.get('mail') if self._mail and not isstring(self._mail): raise TYBizConfException(d, 'ActivityChristmas.mail must be string') self._collectItemList = d.get('collectItems') if not isinstance(self._collectItemList, dict): raise TYBizConfException(d, 'ActivityChristmas.collectItems must be dict') self._tips = d.get('tips') if self._tips and not isstring(self._tips): raise TYBizConfException(d, 'ActivityChristmas.tips must be string') self._rewards = d.get('rewards') if not isinstance(self._rewards, list): raise TYBizConfException(d, 'ActivityChristmas.rewards must be list') self._roomList = d.get('roomList') if not isinstance(self._roomList, list): raise TYBizConfException(d, 'ActivityChristmas.roomList must be list') timeStr = d.get('dayOpenTime') if timeStr: try: self._dayOpenTime = datetime.strptime(timeStr, '%H:%M').time() except: raise TYBizConfException(d, 'ActivityChristmas.dayOpenTime must be time str') timeStr = d.get('dayCloseTime') if timeStr: try: self._dayCloseTime = datetime.strptime(timeStr, '%H:%M').time() except: raise TYBizConfException(d, 'ActivityChristmas.dayCloseTime must be time str') if ftlog.is_debug(): ftlog.debug('ActivityChristmas inited. typeId=', self.TYPE_ID, 'rewards=', self._rewards, 'open=', self._open, 'time=', self._dayOpenTime, self._dayCloseTime, 'active=', self.checkActivityActive()) return self