Beispiel #1
0
def getTableSmilesInfo(bigRoomId, vipLevel):
    infos = configure.getGameJson(DIZHU_GAMEID, 'table.smilies', {},
                                  configure.DEFAULT_CLIENT_ID)
    template = infos.get('rooms', {}).get(str(bigRoomId), '')
    ftlog.debug('bigRoomId=', bigRoomId, 'template=', template, 'infos=',
                infos)
    vips = getattr(infos, '_vips_', None)
    if not vips:
        vips = {}
        setattr(infos, '_vips_', vips)
        viplist = infos.get('vip_special', [])
        templates = infos.get('templates', {})
        for k, v in templates.items():
            vips[k] = [[0, strutil.cloneData(v)]]
            for x in viplist:
                level = x['level']
                rate = x['rate'] + 1
                v = strutil.cloneData(v)
                for _, sv in v.items():
                    sv['self_charm'] = int(sv['self_charm'] * rate)
                vips[k].append([level, v])
                ftlog.debug('vips[k][level]->', k, level, v)
            vips[k].sort(key=lambda x: x[0], reverse=True)

    ftlog.debug('vips=', vips)
    confs = vips.get(template)
    if not confs:
        return {}
    if vipLevel > 0:
        for conf in confs:
            if vipLevel >= conf[0]:
                return conf[1]
    return confs[-1][1]
Beispiel #2
0
 def _resetTableConf(self):
     if ftlog.is_debug():
         ftlog.debug('<< |self.configChanged:', self.configChanged, caller=self)
     if self.configChanged:
         runconf = strutil.cloneData(self.room.roomConf)
         runconf.update(strutil.cloneData(self.config))  # config 即 tableConf
         self._runConfig = runconf
         self._initTableConf()
         self.configChanged = 0
         if ftlog.is_debug():
             ftlog.debug('>> |self._runConfig:', self._runConfig, caller=self)
Beispiel #3
0
    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个,第一个是自己
Beispiel #4
0
def sendBigMatchBackToListTodoTask(userid, gameId, cache = False, direct=True):
    """比赛结算界面返回按钮返回时  
    """
    from majiang2.entity.todotasks_builder.todotasks_builder import MahjongTodoTaskBuilder
    msg = "比赛已结束,点击离开按钮返回比赛列表"
    task = MahjongTodoTaskBuilder.dict_general_box(userid, msg, cache)
    retTask = strutil.cloneData(task)
    buttonLeaveTask =  {
                            "content":"离开",
                            "tasks":[
                                {
                                    "action":"trigger_notify",
                                    "params":{
                                        "eventName":"UPDATE_MATCH_BACK_TO_LIST"
                                    }
                                }
                            ]
                        }
    retTask['params']['buttons'] = [buttonLeaveTask]
    mo = MsgPack()
    mo.setCmd('majiang_todotasks')
    mo.setResult('gameId', gameId)
    mo.setResult('userId', userid)
    mo.setResult('tasks', [retTask])
    router.sendToUser(mo, userid)
    return True, None
Beispiel #5
0
 def getInputParams(self, gameId, userBag, item, timestamp):
     ret = strutil.cloneData(self._inputParams)
     desc = ret.get('desc', '')
     status = loadSubMemberStatus(userBag.userId)
     unsubDesc = status.unsubDesc or ''
     ret['desc'] = strutil.replaceParams(desc, {'unsubDesc': unsubDesc})
     return ret
Beispiel #6
0
def sendBigMatchBackToListTodoTask(userid, gameId, cache=False, direct=True):
    """比赛结算界面返回按钮返回时  
    """
    from majiang2.entity.todotasks_builder.todotasks_builder import MahjongTodoTaskBuilder
    msg = "比赛已结束,点击离开按钮返回比赛列表"
    task = MahjongTodoTaskBuilder.dict_general_box(userid, msg, cache)
    retTask = strutil.cloneData(task)
    buttonLeaveTask = {
        "content":
        "离开",
        "tasks": [{
            "action": "trigger_notify",
            "params": {
                "eventName": "UPDATE_MATCH_BACK_TO_LIST"
            }
        }]
    }
    retTask['params']['buttons'] = [buttonLeaveTask]
    mo = MsgPack()
    mo.setCmd('majiang_todotasks')
    mo.setResult('gameId', gameId)
    mo.setResult('userId', userid)
    mo.setResult('tasks', [retTask])
    router.sendToUser(mo, userid)
    return True, None
Beispiel #7
0
def getEmojiConf(gameId, bigRoomId, vipLevel):
    conf = configure.getGameJson(gameId, 'table.smilies', {},
                                 configure.DEFAULT_CLIENT_ID)
    templateName = conf.get('rooms', {}).get(str(bigRoomId))
    if ftlog.is_debug():
        ftlog.debug('emoji.getEmojiConf', 'gameId=', gameId, 'bigRoomId=',
                    bigRoomId, 'templateName=', templateName)
    template = conf.get('templates', {}).get(templateName)
    if not template:
        return None

    # 获取levelConf
    vipsConf = conf.get('vip_special')
    if not vipsConf:
        return template

    vipConf = None
    for item in vipsConf:
        if vipLevel > item['level']:
            vipConf = item
            break

    if not vipConf:
        return template

    template = strutil.cloneData(template)
    rate = vipConf['rate'] + 1
    for _, value in template.iteritems():
        value['self_charm'] *= rate
    return template
Beispiel #8
0
    def getConfigForClient(self, gameId, userId, clientId):
        if day1st.isDayFirstLogin(userId, gameId):
            return None
        clientConf = strutil.cloneData(self._clientConf)
        firstChargeHasSent = hallstore.isGetFirstRechargeReward(userId)
        if firstChargeHasSent:
            return None
        tyGame = gdata.getGame(gameId)
        if not tyGame:
            return None
        userGameInnings = tyGame.getPlayGameCount(userId, clientId)
        if userGameInnings < 5:
            return None
        isFirstRecharged = hallstore.isFirstRecharged(userId)
        try:
            if not isFirstRecharged:
                rechargeFactory = TodoTaskFirstRechargeFactory().decodeFromDict(
                    self._serverConf.get("firstCharge", {})
                )
                product = rechargeFactory._getProduct(gameId, userId)
                todoTask = TodoTaskPayOrder(product)
                clientConf["config"]["button"]["todoTask"] = todoTask.toDict()
            else:
                rewardFactory = TodoTaskFirstRechargeRewardFactory.decodeFromDict(
                    self._serverConf.get("firstChargeReward", {})
                )
                clientConf["config"]["button"]["todoTask"] = rewardFactory.newTodoTask(gameId, userId,
                                                                                       clientId).toDict()
        except:
            ftlog.exception("TYActivityFirstCharge.getConfigForClient error")
            return None

        return clientConf
Beispiel #9
0
    def getConfigForClient(self, gameId, userId, clientId):
        '''
            用来对所有的general_btn对应的活动中的按钮
            进行统一管理
        '''
        clientConf = strutil.cloneData(self._clientConf)
        button = clientConf["config"]["button"]
        if button["visible"]:
            # true
            todoTaskDict = button["todoTask"]
            if todoTaskDict:
                todoTaskObj = hallpopwnd.decodeTodotaskFactoryByDict(
                    todoTaskDict).newTodoTask(gameId, userId, clientId)
                if not todoTaskObj:
                    gotoShopDict = {
                        "typeId": TodoTaskGotoShopFactory.TYPE_ID,
                        "subStore": "coin"
                    }
                    todoTaskObj = hallpopwnd.decodeTodotaskFactoryByDict(
                        gotoShopDict).newTodoTask(gameId, userId, clientId)

                clientConf["config"]["button"][
                    "todoTask"] = todoTaskObj.toDict()

            return clientConf
        else:
            # false
            pass
Beispiel #10
0
 def getInputParams(self, gameId, userBag, item, timestamp):
     ret = strutil.cloneData(self._inputParams)
     desc = ret.get('desc', '')
     status = loadSubMemberStatus(userBag.userId)
     unsubDesc = status.unsubDesc or ''
     ret['desc'] = strutil.replaceParams(desc, {'unsubDesc': unsubDesc})
     return ret
Beispiel #11
0
    def __onMatchEnd(self):
        mconf = self.matchPlugin.match_room_confs[self.bigRoomId]

        rankinglist = daobase.executeRankCmd("LRANGE", self.matchPlugin.rankingKey(self.bigRoomId), 0, -1)
        getName = lambda userId: userdata.getAttr(userId, 'name')
        rankingListWithName = [(i + 1, userId, getName(userId)) for i, userId in enumerate(reversed(rankinglist))]
        bireport.matchFinish(self.gameId, self.roomId,
                             mconf['start_time'].strftime('%Y-%m-%d_%H:%M:%S_') + str(self.roomId),
                             mconf['name'].replace('\n', ' '),
                             matchTypeId=mconf['match_id'],
                             endTimestamp=time.time(),
                             rewardChip=self.matchCounter['rewardChip'],
                             rewardCoupon=self.matchCounter['rewardCoupon'],
                             rankingList=rankingListWithName,
                             usersLeaveMatchCount=self.matchCounter['usersLeaveMatchCount'],
                             rebuyChip=self.matchCounter['rebuyChip'],
                             addonChip=self.matchCounter['addonChip'],
                             )

        # for check MTT gameEnd
        TYPluginCenter.event(TYPluginUtils.updateMsg(cmd='EV_MATCH_END', params={'room': self}), self.gameId)

        if ftlog.is_debug():
            ftlog.debug("len(self.scheduler.activeTableIds):", len(self.scheduler.activeTableIds), caller=self)

        # 回收决赛桌和异常牌桌
        remainActiveTables = strutil.cloneData(self.scheduler.activeTableIds)
        for activeTableId in remainActiveTables:
            self.scheduler._recycleTable(activeTableId)

        if mconf.get('day1EndConf'):
            self.matchPlugin.saveDay2Players(self)

        self.state = self.MTT_STATE_READY
Beispiel #12
0
def sendBuyDiamondTodoTask(userId, gameId, clientId, pay_order):
    """ 幸运大抽奖,钻石购买
    @param         pay_order        挑选商品模板
    """
    if not TYPlayer.isHuman(userId):
        return

    product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId,
                                                 pay_order)
    if not product:
        ftlog.error('userId =', userId, 'clientId =', clientId, 'pay_order =',
                    pay_order, 'can not find suitable product!')
        return
    try:
        product = product.clone()
    except:
        product = strutil.cloneData(product)
    desc = u'您的钻石不够哦~\n现在' + unicode(product.price) + u'元立得' + unicode(
        product.priceDiamond) + u'钻石!'
    product.content.desc = str(product.priceDiamond) + '钻石'
    client_ver = sessiondata.getClientIdVer(userId)
    if client_ver < 3.74:  # 客户端bug,小于3.74的版本转换一下
        product.priceDiamond = product.price
    todotasks = TodoTaskOrderShow.makeByProduct(desc, '', product)
    TodoTaskHelper.sendTodoTask(gameId, userId, todotasks)
Beispiel #13
0
    def getConfigForClient(self, gameId, userId, clientId):
        clientConf = strutil.cloneData(self._clientConf)
        if clientConf["config"]["firstButton"]["visible"]:
            '''
                处理第1个按钮的todotask
            '''
            todoTask = clientConf["config"]["firstButton"]
            todoTaskObj = hallpopwnd.decodeTodotaskFactoryByDict(todoTask).newTodoTask(gameId, userId, clientId)
            clientConf["config"]["firstButton"] = todoTaskObj.toDict()
            clientConf["config"]["firstButton"]["visible"] = 1
        else:
            pass

        if clientConf["config"]["secondButton"]["visible"]:
            '''
                处理第2个按钮的todotask
            '''
            todoTask = clientConf["config"]["secondButton"]
            todoTaskObj = hallpopwnd.decodeTodotaskFactoryByDict(todoTask).newTodoTask(gameId, userId, clientId)
            clientConf["config"]["secondButton"] = todoTaskObj.toDict()
            clientConf["config"]["secondButton"]["visible"] = 1
        else:
            pass
        ftlog.debug("the noticeImg client config : ", clientConf)
        return clientConf
    def getConfigForClient(self, gameId, userId, clientId):
        if day1st.isDayFirstLogin(userId, gameId):
            return None
        clientConf = strutil.cloneData(self._clientConf)
        firstChargeHasSent = hallstore.isGetFirstRechargeReward(userId)
        if firstChargeHasSent:
            return None
        tyGame = gdata.getGame(gameId)
        if not tyGame:
            return None
        userGameInnings = tyGame.getPlayGameCount(userId, clientId)
        if userGameInnings < 5:
            return None
        isFirstRecharged = hallstore.isFirstRecharged(userId)
        try:
            if not isFirstRecharged:
                rechargeFactory = TodoTaskFirstRechargeFactory(
                ).decodeFromDict(self._serverConf.get("firstCharge", {}))
                product = rechargeFactory._getProduct(gameId, userId)
                todoTask = TodoTaskPayOrder(product)
                clientConf["config"]["button"]["todoTask"] = todoTask.toDict()
            else:
                rewardFactory = TodoTaskFirstRechargeRewardFactory.decodeFromDict(
                    self._serverConf.get("firstChargeReward", {}))
                clientConf["config"]["button"][
                    "todoTask"] = rewardFactory.newTodoTask(
                        gameId, userId, clientId).toDict()
        except:
            ftlog.exception("TYActivityFirstCharge.getConfigForClient error")
            return None

        return clientConf
Beispiel #15
0
    def getConfigForClient(self, gameId, userId, clientId):
        clientConf = strutil.cloneData(self._clientConf)
        if clientConf["config"]["firstButton"]["visible"]:
            '''
                处理第1个按钮的todotask
            '''
            todoTask = clientConf["config"]["firstButton"]
            todoTaskObj = hallpopwnd.decodeTodotaskFactoryByDict(
                todoTask).newTodoTask(gameId, userId, clientId)
            clientConf["config"]["firstButton"] = todoTaskObj.toDict()
            clientConf["config"]["firstButton"]["visible"] = 1
        else:
            pass

        if clientConf["config"]["secondButton"]["visible"]:
            '''
                处理第2个按钮的todotask
            '''
            todoTask = clientConf["config"]["secondButton"]
            todoTaskObj = hallpopwnd.decodeTodotaskFactoryByDict(
                todoTask).newTodoTask(gameId, userId, clientId)
            clientConf["config"]["secondButton"] = todoTaskObj.toDict()
            clientConf["config"]["secondButton"]["visible"] = 1
        else:
            pass
        ftlog.debug("the noticeImg client config : ", clientConf)
        return clientConf
Beispiel #16
0
 def list_diff(cls, short_list, long_list):
     '''获取list差集
     '''
     l_list = strutil.cloneData(long_list)
     for l in short_list:
         if l in l_list:
             l_list.remove(l)
     return l_list
Beispiel #17
0
 def update(self, stateList):
     '''
     将 stateList (list类型) 数据更新到TYSeat类属性
     TYSeat子类可以通过覆写此函数来扩展属性,
     此方法通常再初始化桌子状态时调用
     '''
     assert (isinstance(stateList, list))
     self.__list = strutil.cloneData(stateList)
Beispiel #18
0
 def update(self, stateList):
     '''
     将stateList (list类型) 数据更新到TYTableState类属性
     TYTableState子类可以通过覆写此函数来扩展属性,
     此方法通常再初始化桌子状态时调用
     '''
     assert (isinstance(stateList, list))
     self.__list = strutil.cloneData(stateList)
Beispiel #19
0
 def list_diff(cls, short_list, long_list):
     '''获取list差集
     '''
     l_list = strutil.cloneData(long_list)
     for l in short_list:
         if l in l_list:
             l_list.remove(l)
     return l_list
Beispiel #20
0
 def getDuiZi(cls):
     '''
     对子
     '''
     tempCardsType = strutil.cloneData(cls.cardsType)
     tempCardsNum = strutil.cloneData(cls.cardsNum)
     num1 = random.choice(tempCardsNum)
     tempCardsNum.remove(num1)
     num2 = random.choice(tempCardsNum)
     cardType1 = random.choice(tempCardsType)
     tempCardsType.remove(cardType1)
     cardType2 = random.choice(tempCardsType)
     cardType3 = random.choice(cls.cardsType)
     return [
         {'num': num1, 'type': cardType1},
         {'num': num1, 'type': cardType2},
         {'num': num2, 'type': cardType3}
     ]
Beispiel #21
0
 def buildUpLevelTodoTasks(cls, gameId, userVip, clientId):
     deltaExp = userVip.deltaExpToNextLevel()
     if deltaExp > 0:
         payOrder = strutil.cloneData(hallvip.vipSystem.getLevelUpPayOrder())
         payOrder['priceDiamond'] = {'count': deltaExp, 'minCount': 0, 'maxCount': -1}
         product, _ = hallstore.findProductByPayOrder(gameId, userVip.userId, clientId, payOrder)
         if product:
             return TodoTaskHelper.encodeTodoTasks(TodoTaskPayOrder(product))
     return []
Beispiel #22
0
 def build(self):
     '''
     每次addingPrize之后都必须重新build
     :return: None
     '''
     self.clear()
     for item in self.prizeList:
         for _ in xrange(0, item.get('weight')):
             self.pool.append(strutil.cloneData(item))
     return
Beispiel #23
0
 def getBigK(cls):
     '''
     K以上单张,不是顺子,不是同花等
     '''
     tempCardsType = strutil.cloneData(cls.cardsType)
     tempCardsNoA = strutil.cloneData(cls.cardsNoA)
     tempCardsNoK = strutil.cloneData(cls.cardsNoK)
     num1 = random.choice(cls.cardsBigThanK)
     if num1 == 13:
         num2 = random.choice(tempCardsNoK)
         tempCardsNoK.remove(num2)
         if num2 == 12:
             tempCardsNoK.remove(11)
             tempCardsNoK.remove(1)
         elif num2 == 11:
             tempCardsNoK.remove(12)
         else:
             pass
         num3 = random.choice(tempCardsNoK)
     else:
         num2 = random.choice(tempCardsNoA)
         tempCardsNoA.remove(num2)
         if num2 == 2:
             tempCardsNoA.remove(3)
         elif num2 == 3:
             tempCardsNoA.remove(2)
         else:
             pass
         num3 = random.choice(tempCardsNoA)
     cardType1 = random.choice(tempCardsType)
     cardType2 = random.choice(tempCardsType)
     tempCardsType.remove(cardType2)
     cardType3 = random.choice(tempCardsType)
     return [{
         'num': num1,
         'type': cardType1
     }, {
         'num': num2,
         'type': cardType2
     }, {
         'num': num3,
         'type': cardType3
     }]
Beispiel #24
0
def getAllModulesInfo(userId, subGameId):
    '''
    获取所有模块tip信息
    '''
    global _tipModuleMap
    moduleInfo = []
    for _key, value in _tipModuleMap.iteritems():
        module = strutil.cloneData(value)
        module.count = getTipCount(userId, module, subGameId)
        moduleInfo.append(module)
    return moduleInfo
Beispiel #25
0
def getAllModulesInfo(userId, subGameId):
    '''
    获取所有模块tip信息
    '''
    global _tipModuleMap
    moduleInfo = []
    for _key, value in _tipModuleMap.iteritems():
        module = strutil.cloneData(value)
        module.count = getTipCount(userId, module, subGameId)
        moduleInfo.append(module)
    return moduleInfo
Beispiel #26
0
def getAllModulesInfo(userId):
    """
    获取所有模块tip信息
    """
    global _moduleTipMap
    modules = []
    for _key, value in _moduleTipMap.iteritems():
        module = strutil.cloneData(value)
        module.value = getTipValue(userId, module)
        modules.append(module)
    return modules
Beispiel #27
0
def _adjustHallSessionInfo(redisfullkey, alldata):
    if not alldata:
        return

    if ftlog.is_debug():
        ftlog.debug('hallconf._adjustHallSessionInfo', 'redisfullkey=',
                    redisfullkey, 'alldata=', alldata)

    redisfullkey = redisfullkey.replace(':hall.info', ':table.tbbox')
    tbbox = configure.getJson(redisfullkey, {}, 0)
    tbboxrooms = tbbox.get('rooms', {})
    convert = getattr(alldata, 'convert', None)
    if convert:
        return

    for _, si in alldata['session_items'].items():
        rooms = si['rooms']
        convertRooms = []
        for x in xrange(len(rooms)):
            roomItemKey = rooms[x]
            roomItem = alldata['room_items'].get(roomItemKey)
            if roomItem:
                rid = roomItem.get('id')
                convertRooms.append(roomItem)
                roomtbbox = tbboxrooms.get(str(rid))
                if roomtbbox and roomtbbox.get('playCount', 0) > 1:
                    items = roomtbbox.get('reward', {}).get('items', {})
                    items = strutil.cloneData(items)
                    for item in items:
                        item['name'] = translateAssetKindIdToOld(
                            item['itemId'])
                    roomItem['tbbox'] = {
                        'pt': roomtbbox.get('playCount', 0),
                        'rewards': items
                    }
            else:
                ftlog.error(
                    'hallconf._adjustHallSessionInfo UnknownRoomItemKey roomItemKey=',
                    roomItemKey)

        si['rooms'] = convertRooms

    for tname, ss in alldata['templates'].items():
        convertSS = []
        alldata['templates'][tname] = convertSS
        for x in xrange(len(ss)):
            sessionItemKey = ss[x]
            sessionItem = alldata['session_items'].get(sessionItemKey)
            if sessionItem:
                convertSS.append(sessionItem)
            else:
                ftlog.error(
                    'hallconf._adjustHallSessionInfo UnknownSessionItemKey sessionItemKey=',
                    sessionItemKey)
Beispiel #28
0
def resetTipCount(self, userId, modules, counts, subGameId):
    moduleInfo = []
    bds = zip(modules, counts)
    ftlog.debug('module_tip resetTipCount bds=', bds)
    for bd in bds:
        m = findTipModule(bd[0])
        if m and m.needReport:
            self.setTipCount(userId, bd[0], bd[1], subGameId)
            module = strutil.cloneData(m)
            module.count = bd[1]
            moduleInfo.append(module)
    return moduleInfo
Beispiel #29
0
    def inviteeTip(cls, userId, gameId, createTime, conf):
        prize = strutil.cloneData(conf.get('inviteePrize', {}))
        validday = conf.get('validDay', 7)
        createdate = datetime.strptime(createTime.rsplit(' ')[0], '%Y-%m-%d')
        now = datetime.now()
        if (now.date() - createdate.date()).days >= validday:
            day = 0
        else:
            day = validday - (now.date() - createdate.date()).days

        prize['warn'] = prize['warn'].format(REM_DAYS=day)
        return prize
Beispiel #30
0
def resetTipCount(self, userId, modules, counts, subGameId):
    moduleInfo = []
    bds = zip(modules, counts)
    ftlog.debug('module_tip resetTipCount bds=', bds)
    for bd in bds:
        m = findTipModule(bd[0])
        if m and m.needReport:
            self.setTipCount(userId, bd[0], bd[1], subGameId)
            module = strutil.cloneData(m)
            module.count = bd[1]
            moduleInfo.append(module)
    return moduleInfo
Beispiel #31
0
    def doFriendCall(self, gameId, userId):
        ftlog.debug('doFriendCall...')

        cmd = runcmd.getMsgPack()
        # router.sendToUser(mo, userId)
        # clientId = runcmd.getClientId(cmd)
        action = cmd.getParam('action')

        if action == 'invite_to_game':
            # 邀请好友牌桌游戏
            enterParams = cmd.getParam('enterParams')
            note = cmd.getParam('note')
            invitees = cmd.getParam('invitees')
            self.processInvitees(enterParams, note, invitees, userId, gameId)
            return
        elif action == 'answer_to_invite':
            # 对好友邀请的应答
            inviter = cmd.getParam('inviter')
            answer = cmd.getParam('answer')
            self.processInviteAnswser(inviter, answer, userId, gameId)
            return
        elif action in [
                'get_friends_rank', 'get_friend_tip_info', 'praise_friend'
        ]:
            from hall.entity import hallvip
            try:
                vip = hallvip.userVipSystem.getUserVip(userId).vipLevel.level
            except:
                vip = 0
            cmd.setParam('vip', vip)
        elif action == 'add_friend':
            if self._isObserver(userId):
                show_info_task = TodoTaskShowInfo("对不起,旁观时不能加好友哦~")
                TodoTaskHelper.sendTodoTask(gameId, userId, show_info_task)
                return

        # if not clientId:
        #     clientId = sessiondata.getClientId(userId)
        params = cmd._ht['params']
        tcp_params = strutil.cloneData(params)
        del tcp_params['authorCode']

        del params['action']
        del params['gameId']
        params['appId'] = gameId
        # params['from_tcp'] = 1

        import json
        params['tcp_params'] = json.dumps(tcp_params)

        url = self.action_urls[action]
        ftlog.debug('handleFriendCall post', url, params)
        sdkclient._requestSdk(url, params, needresponse=False)
Beispiel #32
0
    def inviteeTip(cls, userId, gameId, createTime, conf):
        prize = strutil.cloneData(conf.get('inviteePrize', {}))
        validday = conf.get('validDay', 7)
        createdate = datetime.strptime(createTime.rsplit(' ')[0], '%Y-%m-%d')
        now = datetime.now()
        if (now.date() - createdate.date()).days >= validday:
            day = 0
        else:
            day = validday - (now.date() - createdate.date()).days

        prize['warn'] = prize['warn'].format(REM_DAYS=day)
        return prize
Beispiel #33
0
    def doFriendCall(self, gameId, userId):
        ftlog.debug('doFriendCall...')

        cmd = runcmd.getMsgPack()
        # router.sendToUser(mo, userId)
        # clientId = runcmd.getClientId(cmd)
        action = cmd.getParam('action')

        if action == 'invite_to_game':
            # 邀请好友牌桌游戏
            enterParams = cmd.getParam('enterParams')
            note = cmd.getParam('note')
            invitees = cmd.getParam('invitees')
            self.processInvitees(enterParams, note, invitees, userId, gameId)
            return
        elif action == 'answer_to_invite':
            # 对好友邀请的应答
            inviter = cmd.getParam('inviter')
            answer = cmd.getParam('answer')
            self.processInviteAnswser(inviter, answer, userId, gameId)
            return
        elif action in ['get_friends_rank', 'get_friend_tip_info', 'praise_friend']:
            from hall.entity import hallvip
            try:
                vip = hallvip.userVipSystem.getUserVip(userId).vipLevel.level
            except:
                vip = 0
            cmd.setParam('vip', vip)
        elif action == 'add_friend':
            if self._isObserver(userId):
                show_info_task = TodoTaskShowInfo("对不起,旁观时不能加好友哦~")
                TodoTaskHelper.sendTodoTask(gameId, userId, show_info_task)
                return

        # if not clientId:
        #     clientId = sessiondata.getClientId(userId)
        params = cmd._ht['params']
        tcp_params = strutil.cloneData(params)
        del tcp_params['authorCode']

        del params['action']
        del params['gameId']
        params['appId'] = gameId
        # params['from_tcp'] = 1

        import json
        params['tcp_params'] = json.dumps(tcp_params)

        url = self.action_urls[action]
        ftlog.debug('handleFriendCall post', url, params)
        sdkclient._requestSdk(url, params, needresponse=False)
Beispiel #34
0
 def getBigK(cls):
     '''
     K以上单张,不是顺子,不是同花等
     '''
     tempCardsType = strutil.cloneData(cls.cardsType)
     tempCardsNoA = strutil.cloneData(cls.cardsNoA)
     tempCardsNoK = strutil.cloneData(cls.cardsNoK)
     num1 = random.choice(cls.cardsBigThanK)
     if num1 == 13:
         num2 = random.choice(tempCardsNoK)
         tempCardsNoK.remove(num2)
         if num2 == 12:
             tempCardsNoK.remove(11)
             tempCardsNoK.remove(1)
         elif num2 == 11:
             tempCardsNoK.remove(12)
         else:
             pass
         num3 = random.choice(tempCardsNoK)
     else:
         num2 = random.choice(tempCardsNoA)
         tempCardsNoA.remove(num2)
         if num2 == 2:
             tempCardsNoA.remove(3)
         elif num2 == 3:
             tempCardsNoA.remove(2)
         else:
             pass
         num3 = random.choice(tempCardsNoA)
     cardType1 = random.choice(tempCardsType)
     cardType2 = random.choice(tempCardsType)
     tempCardsType.remove(cardType2)
     cardType3 = random.choice(tempCardsType)
     return [
         {'num': num1, 'type': cardType1},
         {'num': num2, 'type': cardType2},
         {'num': num3, 'type': cardType3}
     ]
Beispiel #35
0
    def getConfigForClient(self, gameId, userId, clientId):
        clientConf = strutil.cloneData(self._clientConf)
        jumpTodoTask = TodoTaskEnterGame("", "")
        enterParam = {}
        enterParam["type"] = "roomlist"
        enterParam["pluginParams"] = {}
        enterParam["pluginParams"]["gameType"] = 3

        jumpTodoTask.setParam('gameId', 6)
        jumpTodoTask.setParam('type', "roomlist")
        jumpTodoTask.setParam('enter_param', enterParam)
        clientConf["config"]["button"]["todoTask"] = jumpTodoTask.toDict()

        return clientConf
Beispiel #36
0
def _initialize():
    '''
    初始化命令路由
    '''
    ftlog.debug('oldcmd._initialize begin')
    oldcmds = pokerconf.getOldCmds()
    for cmdpath, info in oldcmds.items():
        _oldcmd_target_map[cmdpath.split('#')[0]] = strutil.cloneData(info)
        info['cmdpath'] = info['cmd'] + '#' + info['act']
        if cmdpath.find('#') > 0:
            _oldcmd_convert_map[cmdpath] = info
        else:
            _oldcmd_convert_map[cmdpath + '#'] = info
    ftlog.debug('oldcmd._initialize end')
Beispiel #37
0
 def getDuiZi(cls):
     '''
     对子
     '''
     tempCardsType = strutil.cloneData(cls.cardsType)
     tempCardsNum = strutil.cloneData(cls.cardsNum)
     num1 = random.choice(tempCardsNum)
     tempCardsNum.remove(num1)
     num2 = random.choice(tempCardsNum)
     cardType1 = random.choice(tempCardsType)
     tempCardsType.remove(cardType1)
     cardType2 = random.choice(tempCardsType)
     cardType3 = random.choice(cls.cardsType)
     return [{
         'num': num1,
         'type': cardType1
     }, {
         'num': num1,
         'type': cardType2
     }, {
         'num': num2,
         'type': cardType3
     }]
Beispiel #38
0
 def _invokeLocal(self, markParams, argl, argd):
     try:
         if _DEBUG:
             debug('_FutureResultLocal._invokeLocal IN->', argl)
         self._status = FutureResult.STATUS_RUN
         ret = _invokeMethodLocked(markParams, argl, argd)
         self._result = strutil.cloneData(ret)
         assert (ret == None), 'the future result can not be None'
         self._status = FutureResult.STATUS_OK
         if _DEBUG:
             debug('_FutureResultLocal._invokeLocal OUT->', argl)
     except Exception, e:
         self._status = FutureResult.STATUS_ERROR
         self._exception = e
         ftlog.error()
Beispiel #39
0
def getModulesInfo(userId, modules, subGameId):
    '''
    获取模块tip信息
    @param userId: 用户Id
    @param modules: 模块信息
    @return: list<ModuleTip> 
    '''
    moduleInfo = []
    for name in modules:
        m = findTipModule(name)
        if m:
            module = strutil.cloneData(m)
            module.count = getTipCount(userId, module, subGameId)
            moduleInfo.append(module)
    return moduleInfo
Beispiel #40
0
def getModulesInfo(userId, moduleNames):
    """
    获取模块tip信息
    @param userId: 用户Id
    @param moduleNames: 模块名
    @return: list<ModuleTip>
    """
    modules = []
    for moduleName in moduleNames:
        m = findModuleTip(moduleName)
        if m:
            module = strutil.cloneData(m)
            module.value = getTipValue(userId, module)
            modules.append(module)
    return modules
Beispiel #41
0
def getModulesInfo(userId, modules, subGameId):
    '''
    获取模块tip信息
    @param userId: 用户Id
    @param modules: 模块信息
    @return: list<ModuleTip> 
    '''
    moduleInfo = []
    for name in modules:
        m = findTipModule(name)
        if m:
            module = strutil.cloneData(m)
            module.count = getTipCount(userId, module, subGameId)
            moduleInfo.append(module)
    return moduleInfo
Beispiel #42
0
 def buildUpLevelTodoTasks(cls, gameId, userVip, clientId):
     deltaExp = userVip.deltaExpToNextLevel()
     if deltaExp > 0:
         payOrder = strutil.cloneData(
             hallvip.vipSystem.getLevelUpPayOrder())
         payOrder['priceDiamond'] = {
             'count': deltaExp,
             'minCount': 0,
             'maxCount': -1
         }
         product, _ = hallstore.findProductByPayOrder(
             gameId, userVip.userId, clientId, payOrder)
         if product:
             return TodoTaskHelper.encodeTodoTasks(
                 TodoTaskPayOrder(product))
     return []
Beispiel #43
0
def cancelModulesTip(userId, modules, subGameId):
    '''
    将模块tip信息置为0
    @param userId: 用户Id
    @param modules: 模块信息
    @return: list<ModuleTip> 
    '''
    moduleInfo = []
    for moduleName in modules:
        m = findTipModule(moduleName)
        if m and m.needReport:
            setTipCount(userId, m.name, 0, subGameId)
            module = strutil.cloneData(m)
            module.count = 0
            moduleInfo.append(module)
    return moduleInfo
Beispiel #44
0
 def getSingle(cls):
     '''
     单张,确保不是顺子,也不是同花,也没有对子
     '''
     num1, num2, num3 = cls.getNonShunZi(cls.cardsSmallThanK)
     tempCardsType = strutil.cloneData(cls.cardsType)
     cardType1 = random.choice(tempCardsType)
     cardType2 = random.choice(tempCardsType)
     if cardType1 == cardType2:
         tempCardsType.remove(cardType2)
     cardType3 = random.choice(tempCardsType)
     return [
         {'num': num1, 'type': cardType1},
         {'num': num2, 'type': cardType2},
         {'num': num3, 'type': cardType3}
     ]
Beispiel #45
0
def cancelModulesTip(userId, modules, subGameId):
    '''
    将模块tip信息置为0
    @param userId: 用户Id
    @param modules: 模块信息
    @return: list<ModuleTip> 
    '''
    moduleInfo = []
    for moduleName in modules:
        m = findTipModule(moduleName)
        if m and m.needReport:
            setTipCount(userId, m.name, 0, subGameId)
            module = strutil.cloneData(m)
            module.count = 0
            moduleInfo.append(module)
    return moduleInfo
Beispiel #46
0
    def createGameData(cls, userId, gameId, clientId):
        '''初始化该游戏的所有的相关游戏数据'''
        if ftlog.is_debug():
            ftlog.debug('<< |gameId, userId, clientId:', gameId, userId, clientId, caller=cls)

        gdatas = strutil.cloneData(cls.gamedata_init_values)
        gdatas['createTime'] = int(time.time())

        # photo = random.choice(cls.CLIENT_PHONE_NAMES)
        # gdatas['photo'] = photo

        gdkeys = gdatas.keys()
        gvals = gdatas.values()

        gamedata.setGameAttrs(userId, gameId, gdkeys, gvals)

        return gdkeys, gvals
Beispiel #47
0
    def doAdjustTablePlayers(self, msg):
        if ftlog.is_debug():
            ftlog.debug("<<", "|roomId, state:", self.roomId, self.getStateStr(), caller=self)

        if self.state == self.MTT_STATE_START or self.state == self.MTT_STATE_QUALIFIER:
            self.scheduler.adjustTablePlayers(msg)

        elif self.state == self.MTT_STATE_PREFINALS:
            #             tableId = msg.getParam("tableId")
            msg.setParam("playersN", 0)  # 强制回收牌桌
            self.scheduler.adjustTablePlayers(msg)

            activeTableIds = self.scheduler.activeTableIds
            ftlog.hinfo("before final |roomId:", self.roomId,
                        "|activityTables, queueUsers:", activeTableIds, self.scheduler.users.keys(),
                        caller=self)

            if len(activeTableIds) == 0 \
                    or len(self.scheduler.users) >= self.tableConf["maxSeatN"] - 1:  # 第二个条件是防御代码,为了防止有桌子没有回收时导致决赛开不了。

                if len(activeTableIds) > 0:
                    ftlog.error("before final len(activeTableIds) > 0")
                self.__startFinalTableLater()
            else:
                self.__notifyFinalTable()

        elif self.state == self.MTT_STATE_FINALS:
            self.scheduler.adjustTablePlayers(msg, isFinal=True)

        # elif self.state == self.MTT_STATE_IDLE: #recycle决赛桌
        #             self.scheduler.adjustTablePlayers(msg)
        #             self.state = self.MTT_STATE_READY

        elif self.state == self.MTT_STATE_DAY1_END:
            msg.setParam("playersN", 0)  # 强制回收牌桌
            self.scheduler.adjustTablePlayers(msg)
            day1WinnerIds = strutil.cloneData(self.scheduler.users.keys())
            self.matchPlugin.rewardEnterDay2Match(self, day1WinnerIds)
            for userId in day1WinnerIds:
                self._leave(userId, TYRoom.LEAVE_ROOM_REASON_MATCH_END, needSendRes=False)

            activeTableIds = self.scheduler.activeTableIds
            ftlog.hinfo("before day1 match end |roomId:", self.roomId,
                        "|activityTables, queueUsers:", activeTableIds, self.scheduler.users.keys(),
                        caller=self)
Beispiel #48
0
 def getConfigForClient(self, gameId, userId, clientId):
     """
     预期实现功能。配置中,配置payOrder后台自动生成该商品的todotask
     
     """
     clientConf = strutil.cloneData(self._clientConf)
     payOrder = clientConf["config"]["button"]["payOrder"]
                 
     product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder)
     ftlog.debug("TYActivitySale product: ", product)
     payOrder = TodoTaskPayOrder(product)
     ftlog.debug("TYActivitySale params: ", payOrder)
     try:
         clientConf["config"]["button"]["todoTask"] = payOrder.toDict()
     except:
         ftlog.exception("getConfigForClient error, can not set todotask, clientId:", clientId)
         return None
     return clientConf
Beispiel #49
0
    def getConfigForClient(self, gameId, userId, clientId):
        """
        预期实现功能。配置中,配置payOrder后台自动生成该商品的todotask
        
        """
        clientConf = strutil.cloneData(self._clientConf)
        payOrder = clientConf["config"]["button"]["payOrder"]

        product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, payOrder)
        ftlog.debug("TYActivitySale product: ", product)
        payOrder = TodoTaskPayOrder(product)
        ftlog.debug("TYActivitySale params: ", payOrder)
        try:
            clientConf["config"]["button"]["todoTask"] = payOrder.toDict()
        except:
            ftlog.exception("getConfigForClient error, can not set todotask, clientId:", clientId)
            return None
        return clientConf
Beispiel #50
0
 def getRankingTabs(self, gameId, userId, rankingKey, clientId):
     templateName = hallconf.getClientRankTemplateName(rankingKey, clientId) or 'default'
     rankingDefines = hallranking.rankingSystem.getRankingDefinesForRankingKey(rankingKey, templateName)
     if ftlog.is_debug():
         ftlog.debug('RankTcpHandler.getRankingTabs gameId=', gameId,
                     'userId=', userId,
                     'rankKey=', rankingKey,
                     'templateName=', templateName,
                     'rankingIds=', [rd.rankingId for rd in rankingDefines])
     tabs = []
     for rankingDefine in rankingDefines:
         cacheRanking = self.getRanking(userId, rankingDefine)
         rankingUser = cacheRanking[0].rankingUserMap.get(userId)
         if rankingUser:
             cacheRanking = strutil.cloneData(cacheRanking)
             cacheRanking[2]['rankInfo'] = cacheRanking[0].rankingDefine.inRankDesc.replace('${rank}', str(
                 rankingUser.rank + 1))
         tabs.append(cacheRanking[2])
     return tabs
Beispiel #51
0
    def getNonShunZi(cls, cards):
        '''
        既不是顺子也不是对子,不连续的单张
        '''
        tempCardsNum = strutil.cloneData(cards)
        a1 = random.choice(tempCardsNum)
        tempCardsNum.remove(a1)
        a2 = random.choice(tempCardsNum)
        tempCardsNum.remove(a2)
        a3 = random.choice(tempCardsNum)
        rawList = [a1, a2, a3]
        copyList = [a1, a2, a3]
        cls.sortThree(copyList)

        if copyList == [1, 12, 13]:
            return [1, 12, random.choice(cls.cardsNoK)]

        if copyList[0] + 1 != copyList[1] or copyList[1] + 1 != copyList[2]:
            return rawList
        else:
            cls.toNonShunZi(copyList)
            return copyList
Beispiel #52
0
def _adjustHallSessionInfo(redisfullkey, alldata):
    if not alldata:
        return
    redisfullkey = redisfullkey.replace(':hall.info', ':table.tbbox')
    tbbox = configure.getJson(redisfullkey, {}, 0)
    tbboxrooms = tbbox.get('rooms', {})
    for _, si in alldata['session_items'].items():
        rooms = si['rooms']
        for x in xrange(len(rooms)):
            rooms[x] = alldata['room_items'][rooms[x]]
            rid = rooms[x]['id']
            roomtbbox = tbboxrooms.get(str(rid))
            if roomtbbox and roomtbbox.get('playCount', 0) > 1:
                items = roomtbbox.get('reward', {}).get('items', {})
                items = strutil.cloneData(items)
                for item in items:
                    item['name'] = translateAssetKindIdToOld(item['itemId'])
                rooms[x]['tbbox'] = {'pt': roomtbbox.get('playCount', 0),
                                     'rewards': items}
    for _, ss in alldata['templates'].items():
        for x in xrange(len(ss)):
            ss[x] = alldata['session_items'][ss[x]]
Beispiel #53
0
def sendBuyDiamondTodoTask(userId, gameId, clientId, pay_order):
    """ 幸运大抽奖,钻石购买
    @param         pay_order        挑选商品模板
    """
    if not TYPlayer.isHuman(userId):
        return
    
    product, _ = hallstore.findProductByPayOrder(gameId, userId, clientId, pay_order)
    if not product:
        ftlog.error('userId =', userId, 'clientId =', clientId, 'pay_order =', pay_order,
                    'can not find suitable product!')
        return
    try:
        product = product.clone()
    except:
        product = strutil.cloneData(product)
    desc = u'您的钻石不够哦~\n现在' + unicode(product.price) +u'元立得' + unicode(product.priceDiamond) +u'钻石!'
    product.content.desc = str(product.priceDiamond) + '钻石'
    client_ver = sessiondata.getClientIdVer(userId)
    if client_ver < 3.74:   # 客户端bug,小于3.74的版本转换一下
        product.priceDiamond = product.price
    todotasks = TodoTaskOrderShow.makeByProduct(desc, '', product)
    TodoTaskHelper.sendTodoTask(gameId, userId, todotasks)
Beispiel #54
0
    def getConfigForClient(self, gameId, userId, clientId):
        '''
            用来对所有的general_btn对应的活动中的按钮
            进行统一管理
        '''
        clientConf = strutil.cloneData(self._clientConf)
        button = clientConf["config"]["button"]
        if button["visible"]:
            # true
            todoTaskDict = button["todoTask"]
            if todoTaskDict:
                todoTaskObj = hallpopwnd.decodeTodotaskFactoryByDict(todoTaskDict).newTodoTask(gameId, userId, clientId)
                if not todoTaskObj:
                    gotoShopDict = {"typeId": TodoTaskGotoShopFactory.TYPE_ID, "subStore": "coin"}
                    todoTaskObj = hallpopwnd.decodeTodotaskFactoryByDict(gotoShopDict).newTodoTask(gameId, userId,
                                                                                                   clientId)

                clientConf["config"]["button"]["todoTask"] = todoTaskObj.toDict()

            return clientConf
        else:
            # false
            pass
Beispiel #55
0
    def getConfigForClient(self, gameId, userId, clientId):
        try:
            clientConf = strutil.cloneData(self._clientConf)

            todoTaskDict = clientConf["config"]["firstButton"]
            todoTaskFactory = TodoTaskEnterGameNewFactory()
            todoTaskFactory.decodeFromDict(todoTaskDict)
            todoTask = todoTaskFactory.newTodoTask(0, 0, 0)
            clientConf["config"]["firstButton"] = todoTask.toDict()
            clientConf["config"]["firstButton"]["visible"] = 1

            payOrder = clientConf["config"]["secondButton"]
            payOrderFac = TodoTaskPayOrderFactory()
            payOrderFac.decodeFromDict({"payOrder": payOrder})
            todoTaskPay = payOrderFac.newTodoTask(gameId, userId, clientId)
            if todoTaskPay:
                clientConf["config"]["secondButton"] = todoTaskPay.toDict()
                clientConf["config"]["secondButton"]["visible"] = 1
            else:
                return None
        except:
            ftlog.exception("getConfigForClient error, can not set todotask, clientId:", clientId)
            return None
        return clientConf