示例#1
0
    def _exchange(self, gameid, userid, actkey, exchangeid):
        info = self._exchanges.get(exchangeid)
        if not info:
            return {'result': 'fail', 'tip': "unknown productId"}

        buynum = self.get_exchange_buynum(userid, actkey, info)
        if buynum >= info['limitTimes']:
            return {'result': 'fail', 'tip': '兑换次数已满'}

        curtime = timestamp.getCurrentTimestamp()
        userAssets = hallitem.itemSystem.loadUserAssets(userid)
        try:
            userAssets.consumeContentItemList(gameid, info['costs'], False, curtime,
                                              "ACT_ITEM_EXCHANGE_COST", exchangeid)
        except:
            return {'result': 'fail', 'tip': '您的道具不足,快去获取道具吧'}

        daobase.executeUserCmd(userid, 'HINCRBY', actkey, self.FIELD_EXCHANGE_NUM.format(exchangeid), 1)
        assetList = userAssets.sendContent(gameid, info['content'], 1, True,
                                           timestamp.getCurrentTimestamp(), "ACT_ITEM_EXCHANGE_GAIN", exchangeid)
        response = self._query(userid, actkey)
        ftlog.info('TYActItemExchange._exchange gameId=', gameid,
                   'userId=', userid,
                   'activityId=', self.getid(),
                   'reward=', TYAssetUtils.buildContents(assetList),
                   'buynum=', buynum + 1,
                   'credit=', response['credit'])
        changeNames = TYAssetUtils.getChangeDataNames(assetList)
        datachangenotify.sendDataChangeNotify(gameid, userid, changeNames)
        response['result'] = 'ok'
        response['tip'] = '兑换成功,您获得' + TYAssetUtils.buildContentsString(assetList)
        return response
示例#2
0
 def handleTableCallPeng(self, userId, seatId, message):
     """处理碰牌消息
     {
         "cmd": "table_call",
         "params": {
             "gameId": 7,
             "clientId": "Android_3.90_360.360,yisdkpay.0-hall6.360.win",
             "userId": 10788,
             "roomId": 75041001,
             "tableId": 750410010200,
             "seatId": 0,
             "action": "peng",
             "action_id": 0,
             "tile": 7,
             "pattern": [7, 7, 7]
         }
     }
     """
     actionId = self.getActionIdFromMessage(message)
     if actionId == self.table.actionID:
         tile = message.getParam('tile')
         pattern = message.getParam('pattern', None)
         pattern.sort()
         self.table.pengTile(seatId, tile, pattern, MTableState.TABLE_STATE_PENG)
     else:
         ftlog.info('wrong actionId:', actionId, ' now table actionId:', self.table.actionID, ' message:', message)
示例#3
0
文件: gdata.py 项目: zhaozw/hall37
def _initialize():
    global __datas
    if len(__datas) <= 0:
        ftlog.info('_initialize gdata begin.')
        __datas = {}
        pgdict = ftcon.getConf('poker:global')
        sid = ftcon.global_config["server_id"]
        __datas['server_type'] = sid[0:2]
        __datas['server_num'] = sid[2:]
        try:
            __datas['server_num_idx'] = int(sid[2:]) - 1
        except:
            __datas['server_num_idx'] = -1
        __datas.update(pgdict)
        __datas['game_packages'] = tuple(pgdict['game_packages'])
        mincenter = min(ftcon.server_type_map.get(SRV_TYPE_HTTP))
        if mincenter == sid:
            __datas['is_control_process'] = 1
        else:
            __datas['is_control_process'] = 0

        __datas['is_http_process'] = 0
        sdef = ftcon.server_map[sid]
        protocols = sdef.get('protocols')
        if protocols:
            server = protocols.get('server')
            if server:
                for p in server:
                    if p.endswith('http'):
                        __datas['is_http_process'] = 1
                        break
        _dumpGdataInfo()
        ftlog.info('_initialize gdata end.')
    return __datas
示例#4
0
    def doBindInviteCode(self, gameId, userId, clientId, inviteCode):
        """绑定上线推荐人ID"""
        try:
            hall_simple_invite.bindSimpleInviteRelationShip(inviteCode, userId)
            mo = MsgPack()
            mo.setCmd('invite_info')
            mo.setResult('action', 'bind_invite_code')
            mo.setResult('code', 0)
            mo.setResult('state', 1)
            mo.setResult('gameId', gameId)
            # 绑定成功,获取推荐人信息
            name, pic = self.getUserNameAndPic(inviteCode)
            mo.setResult('bindName', name)
            mo.setResult('bindPic', pic)
            mo.setResult('bindUserId', inviteCode)
            # 校验自己的领奖状态
            timestamp = pktimestamp.getCurrentTimestamp()
            inviteeStatus = hall_simple_invite.loadStatus(userId, timestamp)
            mo.setResult('rewardState', inviteeStatus.getRewardState(userId, gameId, clientId))
            router.sendToUser(mo, userId)

        except Exception, e:
            if not isinstance(e, TYBizException):
                ftlog.error()
            ec, info = (e.errorCode, e.message) if isinstance(e, TYBizException) else (-1, '系统错误')
            ftlog.info('invite.statics eventId=', 'INPUT_INVITE_CODE',
                       'userId=', userId,
                       'clientId=', clientId,
                       'inviteCode=', inviteCode,
                       'result=', 'failed',
                       'ec=', ec,
                       'info=', info)
            router.sendToUser(self.makeErrorResponse('invite_info', 'bind_invite_code', ec, info), userId)
示例#5
0
    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
示例#6
0
def get_gift(conf, userId, gameId, clientId):
    design = conf.get('design', {})
    cardPattern = design.keys()
    probability = [design[key].get('probability', 0) for key in cardPattern]
    # 根据所有存量进行判断,概率。每一次抽取玩之后,进行储量的减少。
    allNum = 0
    arise_chance = []
    for key in probability:
        allNum += key
    ftlog.debug("get_gift.. allNum..key", allNum)
    for key in probability:
        num = key / allNum
        arise_chance.append(num)
    ftlog.debug("get_gift.. arise_chance..key", arise_chance)
    ftlog.debug("get_gift.. probability..key", probability)
    gifttype = random_pick(cardPattern, probability)
    ftlog.debug("doGetGift key begin..Hall_Act_Fanfanle_Gift..Is1:", type(gifttype))
    '''
    count =0
    for key,value in conf:
        count += value.probability
    if count > 1 :
        return
     '''
    gift = get_gift_for_user(conf, gifttype, userId, gameId, clientId)
    # 将数量进行减少,执行-1操作s
    design[gifttype]["probability"] -= 1
    toUser = {}
    toUser["gift"] = gift
    toUser["gifttype"] = gifttype
    ftlog.info("用户的ID,领取的礼物类型,礼物", userId, gifttype, gift)
    return toUser
示例#7
0
 def reportEvent(self, event, players, gameId, roomId, tableId, roundId):
     ftlog.info('MTableStatisticLongNet.reportEvent event:', event
             , ' players:', players
             , ' gameId:', gameId
             , ' roomId:', roomId
             , ' tableId:', tableId
             , ' roundId:', roundId
     )
     
     uids = []
     for player in players:
         if player.isRobot():
             continue
         
         uids.append(player.userId)
         bireport.reportGameEvent(event
                 , player.userId
                 , gameId
                 , roomId
                 , tableId
                 , roundId
                 , 0, 0, 0, []
                 , player.clientId)
     
     if event == MTableStatistic.TABLE_START:  
         bireport.tableStart(gameId, roomId, tableId, roundId, uids)
     elif event == MTableStatistic.TABLE_WIN:
         bireport.tableWinLose(gameId, roomId, tableId, roundId, uids)
示例#8
0
文件: plugin.py 项目: zhaozw/hall37
    def __init__(self, gameId, cfg):
        ftlog.info('TYPlugin << |gameId, cfg:', gameId, cfg, caller=self)
        self.gameId = gameId
        self.name, self.module_name, self.class_name, self.object_name = (
            cfg['name'], cfg['module'], cfg.get('class'), cfg.get('object'))

        old_mod = sys.modules.get(self.module_name)
        if old_mod:
            del sys.modules[self.module_name]
        self.old_mod = old_mod
        self.module = importlib.import_module(self.module_name)
        reload(self.module)

        if self.object_name:
            self.object = getattr(self.module, self.object_name)(gameId)
            self.handlers = getattr(self.object, cfg['handle'])(gameId) or {}
        else:
            self._class = getattr(self.module, self.class_name)
            self.handlers = getattr(self._class, cfg['handle'])(gameId) or {}

        ftlog.info('TYPlugin |', 'handler:', self.name, 'loaded:', cfg,
                   'old_mod:', id(old_mod), old_mod, 'new_mod:', id(self.module),
                   'module:', self.module, 'events:', self.handlers.keys(),
                   caller=self
                   )
示例#9
0
    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)
示例#10
0
 def handleTableCallChi(self, userId, seatId, message):
     """处理吃消息
     {
         "clientId": "Android_3.90_360.360,yisdkpay.0-hall6.360.win",
         "cmd": "table_call",
         "params": {
             "gameId": 7,
             "clientId": "Android_3.90_360.360,yisdkpay.0-hall6.360.win",
             "userId": 10788,
             "roomId": 75041001,
             "tableId": 750410010200,
             "seatId": 0,
             "action": "chi",
             "action_id": 34,
             "tile": 19,
             "pattern": [17, 18, 19]
         }
     }
     """
     actionId = self.getActionIdFromMessage(message)
     if actionId == self.table.actionID:
         chi = message.getParam('tile')
         chiResult = message.getParam('pattern', None)
         if not chiResult:
             ftlog.error('handleTableCallChi pattern is None')
         self.table.chiTile(seatId, chi, chiResult, MTableState.TABLE_STATE_CHI)
     else:
         ftlog.info('wrong actionId:', actionId, ' now table actionId:', self.table.actionID, ' message:', message)
示例#11
0
文件: gm.py 项目: zhaozw/hall37
    def _do_http_gm_table_detail(self, gameId, httpRequest, httpArgs, httpResult):
        '''获取某牌桌的详情'''

        roomId = int(httpArgs['roomId'])
        tableId = int(httpArgs['tableId'])
        username = httpArgs.get('username')
        password = httpArgs.get('password')
        if username and password:
            token = daobase.executeMixCmd('HGET', '8:gm:token', username) == password
        else:
            token = False

        ftlog.info('GM._do_http_gm_table_detail << |',
                   'roomId, tableId, username, token', roomId, tableId, username, token)

        msg = utils.updateMsg(cmd='table', params={
            'action': 'gm',
            'sa': 'tableDetail',
            'gameId': gameId,
            'roomId': roomId,
            'tableId': tableId,
            'token': token,
        })
        ret = strutil.loads(router.queryTableServer(msg, roomId))
        ftlog.debug('_do_http_gm_table_detail| roomId, tableId, ret:', roomId, tableId, ret)
        tableDetail = strutil.loads(router.queryTableServer(msg, roomId))['result']['tableDetail']
        httpResult['tableDetail'] = tableDetail
示例#12
0
    def calcScore(self,winState = 0):
        """计算输赢数值"""

        # 序列化,以备后续的查找核实
        self.serialize()
        if self.resultType == self.RESULT_GANG:
            self.calcGang() 
        elif self.resultType == self.RESULT_WIN:
            playersAllTiles = [[] for _ in range(self.playerCount)]
            for player in self.tableTileMgr.players:
                playersAllTiles[player.curSeatId] = player.copyTiles()
            self.__win_rule_mgr = MWinRuleFactory.getWinRule(MPlayMode.QUESHOU)
            self.__win_pattern = []
            self.__tile_pattern_checker = MTilePatternCheckerFactory.getTilePatternChecker(MPlayMode.QUESHOU)
            self.__tile_pattern_checker.initChecker(playersAllTiles, self.winTile, self.tableTileMgr, False, self.lastSeatId, self.winSeatId, self.actionID)
            tiles = {MHand.TYPE_HAND: self.__tile_pattern_checker.playerHandTilesWithHu[self.winSeatId]}
            ftlog.info('MQueshouOneResult.calcScore tiles=',tiles) 
            winResult, winPattern = self.__win_rule_mgr.getHuPattern(tiles)
            self.__win_pattern = winPattern
            self.calcWin(winState)
        elif self.resultType == self.RESULT_FLOW:

            self.results[self.KEY_TYPE] = ''
            self.results[self.KEY_NAME] = '流局'
            score = [0 for _ in range(self.playerCount)]
            self.results[self.KEY_SCORE] = score
            winMode = [MOneResult.WIN_MODE_LOSS for _ in range(self.playerCount)]
            self.results[self.KEY_WIN_MODE] = winMode
            resultStat = [[] for _ in range(self.playerCount)]
            self.results[self.KEY_STAT] = resultStat
示例#13
0
 def returnFees(self, inst, userId, fees):
     '''
     退还报名费
     '''
     ftlog.info('SigninFee.returnFees matchId=', inst.matchId,
                'userId=', userId,
                'fees=', fees)
示例#14
0
 def handleTableCallWin(self, userId, seatId, message):
     """处理和牌消息
     {
         "cmd": "table_call",
         "params": {
             "gameId": 7,
             "clientId": "Android_3.90_360.360,yisdkpay.0-hall6.360.win",
             "userId": 10788,
             "roomId": 75041001,
             "tableId": 750410010200,
             "seatId": 0,
             "action": "win",
             "action_id": 14,
             "tile": 2
         }
     }
     """
     actionId = self.getActionIdFromMessage(message)
     if actionId == self.table.actionID:
         tile = message.getParam('tile')
         ftlog.debug('handleTableCallWin actionId =',actionId,'tile', tile,'seatId',seatId)
         self.table.gameWin(seatId, tile)
     else:
         ftlog.info('handleTableCallWin message:', message
                    , ' but actionID is wrong, actionIDInTable:', self.table.actionID
                     , ' actionIDInMsg:', actionId)
示例#15
0
 def sendRewards(self, player, rankRewards):
     '''给用户发送奖励'''
     ftlog.info('MatchRewardsTest.sendRewards userId=', player.userId,
                'matchId=', player.group.matchId,
                'matchingId=', player.group.matchingId,
                'stageIndex=', player.group.stageIndex,
                'rankRewards=', rankRewards.conf)
示例#16
0
 def collectFees(self, inst, userId, fees):
     '''
     收取用户报名费, 如果报名费不足则抛异常SigninFeeNotEnoughException
     '''
     ftlog.info('SigninFee.collectFees matchId=', inst.matchId,
                'userId=', userId,
                'fees=', fees)
示例#17
0
 def notifyMatchCancelled(self, signinUser, reason, message=None):
     '''
     通知用户比赛由于reason取消了
     '''
     ftlog.info('PlayerNotifierTest.notifyMatchCancelled userId=', signinUser.userId,
                'reason=', reason,
                'message=', message)
示例#18
0
文件: httpgame.py 项目: zhaozw/hall37
 def doDeliveryProduct(self, uid, orderId, prodId, orderPrice, prodCount, platformOrder, isError, error):
     ftlog.info('doDeliveryProduct->', uid, orderId, prodId, orderPrice, prodCount, platformOrder, isError, error)
     userdata.clearUserCache(uid)
     mo = MsgPack()
     mo.setCmd('prod_delivery')
     mo.setParam('userId', uid)
     mo.setParam('orderId', orderId)
     mo.setParam('prodId', prodId)
     mo.setParam('orderPrice', orderPrice)
     mo.setParam('orderPlatformId', platformOrder)
     if isError == 'true':
         mo.setResult('ok', '0')
         mo.setResult('info', error)
         mo.setError(1, error)
         router.sendToUser(mo, uid)
         return 'success'
     else:
         mo.setParam('ok', '1')
         isSub = runhttp.getParamInt('is_monthly', 0)
         if isSub:
             mo.setParam('isSub', isSub)
         ret = router.queryUtilServer(mo, uid)
         ftlog.info('doDeliveryProduct->', uid, orderId, prodId, orderPrice, prodCount, platformOrder, isError,
                    error, 'result=', ret)
         if isinstance(ret, (str, unicode)) and ret.find('error') < 0:
             return 'success'
     return 'error'
示例#19
0
文件: protocol.py 项目: zhaozw/hall37
    def onMsg(self):
        pack = stackless.getcurrent()._fttask.pack
        ftlog.debug('A2SProtocol->[' + pack + ']')
        src, dst, queryid, userheader1, userheader2, message = agentmsg.unpack(pack)
        if src == None or dst == None:
            ftlog.info("ERROR, recive a error format message")
            return
        if self.peer_id == 0:
            self.peer_id = src
            ftcon.serverid_protocol_map[self.peer_id] = self
            ftlog.info("Receive service register, serverid=", self.peer_id, self)
            return

        # 处理agent服务自身的命令
        if dst == ftcon.global_config["server_id"] and A2SProtocol.onCommand != None:
            #             ftlog.debug('A2SProtocol-> it self command !!')
            A2SProtocol.onCommand(self, src, queryid, userheader1, userheader2, message)
            return

        if dst.find('AG') == 0:  # 如果是直接发送给另外的一个AGENT, 那器agent就是其本身
            agent_id = dst
        else:
            server_conf = ftcon.getServerConf(dst)
            agent_id = server_conf['agent']
        try:
            # 从src发过来的数据,转给dst所在的agent
            # 如果是agent所属内部进程过来的数据, 直接转发至dst进程
            if agent_id == ftcon.global_config["server_id"]:
                agent_id = dst
            # ftlog.debug('A2SProtocol->send to agentid->', agent_id, 'dst=', dst)
            protocol = ftcon.serverid_protocol_map[agent_id]
            protocol.transport.write(pack + '\r\n')
        except:
            ftlog.error('msg route error, not found agent protocol, dst_server_id=', dst, 'agend=', agent_id)
示例#20
0
def _doTcpPortTuyou():
    mo = MsgPack()
    mo.setCmd('hellotcp')
    userId = runhttp.getParamInt('userId')
    nicaiCode = runhttp.getParamStr('nicaiCode', '')
    clientId = runhttp.getParamStr('clientId', '')
    if not nicaiCode:
        mo.setError(3, 'nicai error !')
        return mo
    if userId < 1:
        mo.setError(3, 'userId error !')
        return mo

    ftlog.debug('tcpport->userId=', userId, 'nicaiCode=', nicaiCode)
    HelloTuyou.getNiCaiCode(mo, nicaiCode)

    ip, port = getGaoFangIp2(userId, clientId)
    if not ip:
        ipports = gdata.getUserConnIpPortList()
        address = ipports[userId % len(ipports)]
        ip, port = getGaoFangIp(clientId, address[0], address[1])

    ftlog.info('doTcpPortTuyou->', userId, ip, port)
    mo.setResult('tcpsrv', {'ip': ip, 'port': port})
    return mo
示例#21
0
 def sendRankRewards(self, player, rankRewards):
     '''
     给用户发奖
     '''
     ftlog.info('MatchPlayerNotifierTest.sendRankRewards userId=', player.userId,
                'rankRewards=', rankRewards,
                'totalOver=', len(self._playerMap))
示例#22
0
def getGaoFangIp2(userId, clientId):
    ip, port = '', 0
    try:
        gaofangConfs = configure.getJson('poker:map.gaofangip.2', {})
        policy = gaofangConfs.get('policy')
        if policy == 'defence2':
            intClientId = sessiondata.getClientIdNum(userId, clientId)
            clientIds = gaofangConfs['clientIds']
            areaId = clientIds.get(intClientId)
            if not areaId:
                areaId = clientIds.get(str(intClientId))
                if not areaId:
                    areaId = clientIds.get('default')
                    if not areaId:
                        areaId = gaofangConfs['areas'].keys()[0]
                    ftlog.warn('ERROR, getGaoFangIp2 not found area id of ',
                               intClientId, clientId, 'use default !')
                clientIds[intClientId] = areaId
            entrys = gaofangConfs['areas'][areaId]
            ipPorts = random.choice(entrys)  # 切换不同的端口接入
            ipPort = ipPorts[userId % len(ipPorts)]  # 使用相对固定的IP地址接入
            ip, port = ipPort[0], ipPort[1]
    except:
        ftlog.error()
    ftlog.info('getGaoFangIp2->', ip, port, userId, clientId)
    return ip, port
示例#23
0
    def onTableChat(self, gameId, msg):
        if ftlog.is_debug():
            ftlog.debug("<< |msg", msg, caller=self)

        table = msg.getParam("table")
        userId = msg.getParam("userId")
        seatIndex = msg.getParam("seatId")
        isFace = msg.getParam("isFace")
        voiceIdx = msg.getParam("voiceIdx")
        chatMsg = msg.getParam("msg")

        player = table.players[seatIndex]
        if player.userId != userId:
            ftlog.warn(table._baseLogStr("onTableChat player.userId != userId!", userId),
                       "|seatIndex, player:", seatIndex, player.userId, caller=self)
            return False

        if isFace == 0:
            # 纯文本内容
            chatMsg = keywords.replace(chatMsg[:80])  # 80个字符长度限制
            if difangConf.isEnableLogChatMsg(gameId):
                hallchatlog.reportChatLog(userId, chatMsg, self.gameId, table.roomId, table.tableId, seatIndex,
                                          userName=player.name, roomName=table.room.roomConf.get('name'))
                ftlog.info('onTableChat |gameId, tableId, userId, name, chatMsg:',
                           gameId, table.tableId, player.userId, player.name, chatMsg, caller=self)

        self.sendTableChatResToAll(table, player, isFace, voiceIdx, chatMsg)
示例#24
0
文件: protocol.py 项目: zhaozw/hall37
    def onMsg(self):
        pack = stackless.getcurrent()._fttask.pack
        ftlog.debug('A2AProtocol->', FTTasklet.concurrent_task_count, '[' + pack + ']')
        src, dst, queryid, userheader1, userheader2, message = agentmsg.unpack(pack)
        if src == None or dst == None:
            ftlog.info("ERROR, recive a error format message")
            return

        if self.peer_id == 0:
            self.peer_id = src
            ftcon.serverid_protocol_map[self.peer_id] = self
            ftlog.info("Receive other agent register, agentid=", self.peer_id)
            return

        # 处理agent服务自身的命令
        if dst == ftcon.global_config["server_id"] and A2AProtocol.onCommand != None:
            #             ftlog.debug('A2AProtocol-> it self command !!')
            A2AProtocol.onCommand(self, src, queryid, userheader1, userheader2, message)
            return

        try:
            # 从其他agent过来的数据,转给连接的dst service
            #             ftlog.debug('A2AProtocol->send to target->', dst)
            protocol = ftcon.serverid_protocol_map[dst]
            if performance.PERFORMANCE_NET:
                pack = performance.linkMsgTime('LW', pack)
            protocol.transport.write(pack + '\r\n')
        except:
            ftlog.error('msg route error, dst_server_id=', dst)
示例#25
0
    def doQuickStart(self, msg):
        assert self.roomId == msg.getParam("roomId")

        userId = msg.getParam("userId")
        shadowRoomId = msg.getParam("shadowRoomId")
        tableId = msg.getParam("tableId")
        clientId = msg.getParam("clientId")
        ftlog.info(getMethodName(), "<<", "|userId, clientId, roomId, shadowRoomId, tableId:", userId, clientId,
                   self.roomId, shadowRoomId, tableId)

        if tableId == self.roomId * 10000:
            isOk = True  # 玩家在队列里时断线重连
            player = self.match.findPlayer(userId)
            if player is None or not player.group:
                #             if player is None or not player.group:
                ftlog.warn(getMethodName(), '|room=', self.roomId,
                           'userId=', userId, 'not found player')
                onlinedata.removeOnlineLoc(userId, self.roomId, tableId)
                isOk = False
        else:
            isOk = False

        if isOk:
            reason = self.ENTER_ROOM_REASON_OK
            self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId, self.match.tableId)
            # 如果用户已经被分组则发送等待信息
            if player.group:
                self.match.playerNotifier.notifyMatchWait(player, player.group)
        else:
            reason = self.ENTER_ROOM_REASON_INNER_ERROR
            info = u'在线状态错误或其他系统内部错误'
            self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId, 0, info)
示例#26
0
文件: uploader.py 项目: zhaozw/hall37
def uploadVideo(uploadUrl, token, uploadPath, videoData):
    filename = os.path.basename(uploadPath)
    formItems = []
    formItems.append(FormItemData('token', token))
    formItems.append(FormItemData('key', uploadPath))
    formItems.append(FormItemFile('file', videoData, filename))
    # formItems.append(FormItemFile('fileBinaryData', videoData, filename))

    boundary = genBoundary()
    uploadData = encodeFormItems(boundary, formItems)
    headers = {
        'Content-Type': ['multipart/form-data; charset=utf-8; boundary=%s' % (boundary)]
    }
    try:
        code, body = http.runHttp(method='POST', url=uploadUrl, header=headers,
                                  body=uploadData,
                                  connect_timeout=5,
                                  timeout=5)
        if ftlog.is_debug():
            ftlog.debug('uploader.uploadVideo uploadUrl=', uploadUrl,
                        'uploadPath=', uploadPath,
                        'token=', token,
                        'ret=', (code, body))

        if code == 200:
            return 0, body

        ftlog.info('uploader.uploadVideo Res uploadUrl=', uploadUrl,
                   'uploadPath=', uploadPath,
                   'token=', token,
                   'ret=', code)
        return -1, '上传失败'
    except:
        return -2, '上传失败'
示例#27
0
文件: config.py 项目: zhaozw/hall37
def _initByData(svrid, sc, rc, glc, conf):
    global global_config
    global_config.update(json.loads(glc))

    # init log system...
    log_file = "%s.log" % svrid
    log_path = global_config["log_path"]
    ftlog.trace_stdout("FreeTime service(%s) up, log to %s/%s..." % (svrid, log_path, log_file))
    log_level = int(global_config.get("log_level", 0))
    # skip twisted noisy in no-debug level...
    if log_level > 0:
        Factory.noisy = False
    if ide_debug():
        ftlog.initLog(log_file, log_path, log_level)
        # ftlog.initLog(log_file, 'stdout', log_level)
    else:
        ftlog.initLog(log_file, log_path, log_level)

    # init maps...
    ftlog.info("init from redis:", conf[0], conf[1], conf[2])
    _initServerMap(json.loads(sc))
    dbs = json.loads(rc)
    global_config['freetime:db'] = dbs
    if "redis" in dbs:
        _initRedisPoolMap(svrid, conf, dbs["redis"])
    if "mysql" in dbs:
        _initMysqlPoolMap(svrid, conf, dbs["mysql"])
示例#28
0
 def testChipBag(self):
     # 测试参赛券
     itemKind = hallitem.itemSystem.findItemKind(item_chip_bag_id)
     componentKindIdList = [item_chip_bag_part1_id, item_chip_bag_part2_id,
                         item_chip_bag_part3_id, item_chip_bag_part4_id,
                         item_chip_bag_part5_id, item_chip_bag_part6_id,
                         item_chip_bag_part7_id]
     
     # 获取用户背包
     userBag = hallitem.itemSystem.loadUserAssets(self.userId).getUserBag()
     self.assertEqual(userBag.getAllKindItem(itemKind), [])
     
     
     for i, componentKindId in enumerate(componentKindIdList):
         componentKind = hallitem.itemSystem.findItemKind(componentKindId)
         ftlog.info('componentKindId=', componentKindId, 'componentKind=', componentKind)
         self.assertIsNotNone(componentKind)
         item = userBag.addItemUnitsByKind(self.gameId, componentKind, 1, self.timestamp, 0, 'TEST_ADJUST', 0)[0]
         if i + 1 < len(componentKindIdList):
             #gameId, item, actionName, timestamp=None, params={}
             self.assertRaises(TYItemKindAssembleNotEnoughException, userBag.doAction,
                               self.gameId, item, 'assemble', self.timestamp, {})
     
     newItem = userBag.doAction(self.gameId, item, 'assemble', self.timestamp, {}).assembledItem
     self.assertEqual(newItem.kindId, item_chip_bag_id)
示例#29
0
def getAllReward(status):
    from hall.entity import hallitem
    count = 0
    for invitation in status.inviteeMap.values():
        if invitation.state == Invitation.STATE_ACCEPT:
            invitation.state = Invitation.STATE_REWARD
            count += 1
    assetTupleList = []
    if count > 0:
        _saveStatus(status)

        timestamp = pktimestamp.getCurrentTimestamp()
        if _conf.prizeRewardItem:
            ftlog.info('neituiguang.getAllReward userId=', status.userId,
                       'assetKindId=', _conf.prizeRewardItem.assetKindId,
                       'assetCount=', _conf.prizeRewardItem.count,
                       'invitationCount=', count)
            assetTuple = hallitem.itemSystem.loadUserAssets(status.userId).addAsset(HALL_GAMEID,
                                                                                    _conf.prizeRewardItem.assetKindId,
                                                                                    _conf.prizeRewardItem.count,
                                                                                    timestamp, 'PROMOTE_REWARD', 0)
            assetTupleList.append(assetTuple)
            datachangenotify.sendDataChangeNotify(HALL_GAMEID, status.userId,
                                                  TYAssetUtils.getChangeDataNames(assetTupleList))
    return count, assetTupleList
示例#30
0
文件: plugin.py 项目: zhaozw/hall37
    def buildEventMap(cls, gameId, plugins, handlers_config, map_events):
        # 然后 build 事件处理表
        # step 1: 有些事件是有顺序要求的,先按顺序要求,构架一个架子
        for event, plugin_names in handlers_config['event_seq'].items():
            if ' ' in event:
                event = tuple(event.split())
            map_events[event] = []
            for plugin_name in plugin_names:
                if plugin_name == '...':  # 事件顺序分割符号
                    map_events[event].append('...')
                    continue
                plugin = plugins.get(plugin_name)
                if plugin and event in plugin.handlers:
                    map_events[event].append((plugin_name, plugin.handlers[event]))

        # step 2: 把 event_seq 配置中未明确的事件,加到 '...' 的位置
        for plugin_name, plugin in plugins.items():
            for event, handler in plugin.handlers.items():
                if event not in map_events:
                    map_events[event] = []
                if not (plugin_name, handler) in map_events[event]:  # 加过的不再加
                    if '...' in map_events[event]:  # 如果包含事件顺序分割符,则普通事件添加到分割符前面
                        map_events[event].insert(map_events[event].index('...'), (plugin_name, handler))
                    else:
                        map_events[event].append((plugin_name, handler))

        # 最后把这个 '...' 标志删除掉
        for event_handlers in cls.map_events[gameId].values():
            if '...' in event_handlers:
                event_handlers.remove('...')

        ftlog.info('buildEventMap >> |', plugins, caller=cls)
        ftlog.info('buildEventMap >> |', map_events, caller=cls)
示例#31
0
    def doQuickStart(self, msg):
        assert (self.roomId == msg.getParam("roomId"))

        userId = msg.getParam("userId")
        shadowRoomId = msg.getParam("shadowRoomId")
        tableId = msg.getParam("tableId")
        clientId = msg.getParam("clientId")
        ftlog.info(getMethodName(), "<<",
                   "|userId, clientId, roomId, shadowRoomId, tableId:", userId,
                   clientId, self.roomId, shadowRoomId, tableId)

        if tableId == self.roomId * 10000:
            isOk = True  # 玩家在队列里时断线重连
            player = self.match.findPlayer(userId)

            if ftlog.is_debug():
                ftlog.debug('TYArenaMatchRoom.doQuickStart reconnect userId=',
                            userId, 'tableId=', tableId, 'player=',
                            player.__dict__ if player else None)

            if player is None:
                ftlog.warn(getMethodName(), '|room=', self.roomId, 'userId=',
                           userId, 'not found player')
                onlinedata.removeOnlineLoc(userId, self.roomId, tableId)
                isOk = False
        else:
            isOk = False

        if isOk:
            reason = self.ENTER_ROOM_REASON_OK
            self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId,
                                   self.match.tableId)
            # 如果用户已经被分组则发送等待信息
            if player.stage and player.state in (MatchPlayer.STATE_WAIT,
                                                 MatchPlayer.STATE_RISE):
                self.match.playerNotifier.notifyMatchWait(player)
        else:
            reason = self.ENTER_ROOM_REASON_INNER_ERROR
            info = u'在线状态错误或其他系统内部错误'
            self.sendQuickStartRes(self.gameId, userId, reason, self.bigRoomId,
                                   0, info)
示例#32
0
 def doSendReward(cls, gameId, userId, clientId, activityId):
     activities = {
         'activity_hall_reward_hszz': {
             'url': 'http://apk.dl.tuyoo.com/down/hszz/Clash_Royale.apk',
             'rewardChip': 10000,
             'goldRain': '恭喜您获得1万金币',
             'intActId': 20000
         },
         'act_hall_reward_wzry': {
             'url':
             'http://down.s.qq.com/download/apk/10015420_com.tencent.tmgp.sgame.apk',
             'rewardChip': 0,
             'goldRain': '恭喜您获得100金币',
             'intActId': 20001
         },
         'act_hall_reward_cyhx': {
             'url':
             'http://down.s.qq.com/download/apk/10015420_com.tencent.tmgp.cf.apk',
             'rewardChip': 0,
             'goldRain': '恭喜您获得100金币',
             'intActId': 20002
         }
     }
     actConf = activities.get(activityId)
     if actConf:
         todotasks = [TodoTaskDownloadApkPromote(actConf['url'])]
         if (actConf['rewardChip'] > 0 and gamedata.setnxGameAttr(
                 userId, gameId, 'act.sendReward:%s' %
             (activityId), 1) == 1):
             # 发1完金币
             userchip.incrChip(userId, gameId, actConf['rewardChip'],
                               daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                               'ACTIVITY_REWARD', actConf['intActId'],
                               clientId)
             datachangenotify.sendDataChangeNotify(gameId, userId, ['chip'])
             todotasks.append(TodoTaskGoldRain(actConf['goldRain']))
             ftlog.info('ActivitySendReward.doSendReward gameId=', gameId,
                        'userId=', userId, 'clientId=', clientId,
                        'activityId=', activityId, 'rewardChip=',
                        actConf['rewardChip'])
         TodoTaskHelper.sendTodoTask(gameId, userId, todotasks)
示例#33
0
    def doGameQuickStart(self, userId, gameId, clientId, roomId0, tableId0, playMode, sessionIndex):
        '''
        TCP 发送的至UTIL服务的quick_start暂时不能用lock userid的方式, 
        因为,消息流 CO->UT->GR->GT->UT会死锁
        '''
        msg = runcmd.getMsgPack()
        ftlog.debug('doGameQuickStart', userId, gameId, clientId, roomId0, tableId0, playMode, sessionIndex,
                    caller=self)
        if not playMode and roomId0 <= 0 and tableId0 <= 0:
            try:
                # 前端对于sessionIndex是写死的, 不会更具hall_info中的顺序改变而改变
                if sessionIndex == 0:
                    playMode = majiang_conf.PLAYMODE_GUOBIAO
                elif sessionIndex == 1:
                    playMode = majiang_conf.PLAYMODE_SICHUAN
                elif sessionIndex == 2:
                    playMode = majiang_conf.PLAYMODE_GUOBIAO_EREN
                elif sessionIndex == 3:
                    playMode = majiang_conf.PLAYMODE_HARBIN
                elif sessionIndex == 4:
                    playMode = majiang_conf.PLAYMODE_SICHUAN_DQ
                elif sessionIndex == 5:
                    playMode = majiang_conf.PLAYMODE_SICHUAN_XLCH
                elif sessionIndex == 6:
                    playMode = majiang_conf.PLAYMODE_GUOBIAO_VIP
                else:
                    playMode = majiang_conf.PLAYMODE_GUOBIAO
                msg.setParam('playMode', playMode)  # 透传playMode, 以便发送高倍房引导弹窗
            except:
                ftlog.error('doGameQuickStart', msg)
            ftlog.debug('doGameQuickStart sessionIndex=', sessionIndex, 'playMode=', playMode)

        if roomId0 < 1000:
            roomIdx = roomId0
            roomId0 = 0
            ftlog.info("quickstart roomID error, from %d change to %d" % (roomIdx, roomId0))

        MajiangQuickStartDispatcher.dispatchQuickStart(msg, userId, gameId, roomId0, tableId0, playMode, clientId)
        if router.isQuery():
            mo = runcmd.newOkMsgPack(1)
            router.responseQurery(mo, '', str(userId))
示例#34
0
    def bet(self, gameId, userId, clientId, target, betAmount, timestamp):
        '''
        @param target:
            下注目标
        @param betId:
            下注额
        '''
        status = self.loadUserQuizStatus(userId)

        # 检查totalAmount
        if status.totalBet + betAmount > self._serverConf['totalBetLimit']:
            raise TYBizException(-1, self._serverConf['totalBetLimitDesc'])

        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        assetKind, consumeCount, final = userAssets.consumeAsset(gameId,
                                                                 self._serverConf['chipAssetId'],
                                                                 betAmount,
                                                                 timestamp,
                                                                 'ACTIVITY_CONSUME',
                                                                 self.intActivityId)
        if consumeCount != betAmount:
            raise TYBizException(-1, self._serverConf['chipNotEnough'])

        ftlog.info('TYActivityMatchQuiz.bet gameId=', gameId,
                   'userId=', userId,
                   'target=', target,
                   'betAmount=', betAmount,
                   'chipAssetId=', self._serverConf['chipAssetId'],
                   'activityId=', self.activityId,
                   'intActivityId=', self.intActivityId,
                   'totalBet=', status.totalBet)
        # 消耗筹码
        status.addBet(target, betAmount)
        self.saveUserQuizStatus(status)

        # 加入该活动参与用户集合
        addUserIdToActivity(gameId, self.activityId, userId)

        if assetKind and assetKind.keyForChangeNotify:
            datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, assetKind.keyForChangeNotify)
        return final, status
示例#35
0
    def doGetFirstRechargeReward(self, gameId, userId, clientId):
        if not hallstore.isFirstRecharged(userId):
            mo = MsgPack()
            mo.setCmd('get_first_recharge')
            mo.setError(-1, '你还没有首充!')
            router.sendToUser(mo, userId)
            return

        if not hallstore.setFirstRechargeReward(userId):
            mo = MsgPack()
            mo.setCmd('get_first_recharge')
            mo.setError(-1, '您已经领取了!')
            router.sendToUser(mo, userId)
            return

        timestamp = pktimestamp.getCurrentTimestamp()
        userAssets = hallitem.itemSystem.loadUserAssets(userId)
        itemKindId = hall_first_recharge.queryFirstRecharge(
            gameId, userId, clientId)
        assetKindId = hallitem.itemIdToAssetId(itemKindId)
        balance = userAssets.balance(gameId, assetKindId, timestamp)
        if balance <= 0:
            userAssets.addAsset(gameId, assetKindId, 1, timestamp,
                                'FIRST_RECHARGE', 0)

            ftlog.info('SotreTcpHandler.doGetFirstRechargeReward gameId=',
                       gameId, 'userId=', userId, 'itemId=', itemKindId)

            userBag = userAssets.getUserBag()
            item = userBag.getItemByKindId(itemKindId)
            if item:
                try:
                    userBag.doAction(gameId, item, 'open', timestamp)
                except:
                    ftlog.error(
                        'SotreTcpHandler.doGetFirstRechargeReward gameId=',
                        gameId, 'userId=', userId, 'itemId=', itemKindId)
            pkmessage.send(gameId, pkmessage.MESSAGE_TYPE_PRIVATE, userId,
                           '恭喜您获得首充豪华大礼包奖励!')
        datachangenotify.sendDataChangeNotify(gameId, userId,
                                              ['item', 'promotion_loc'])
示例#36
0
    def userBetChip(self, userId, activityGameId, issueNumber, userModel,
                    isLeft, betChip):
        # 加载用户活动数据
        ftlog.debug('BetGuess.userBetChip:', 'userId=', userId,
                    'activityGameId=', activityGameId, 'issueNumber=',
                    issueNumber, 'isLeft=', isLeft, 'betChip=', betChip)

        # 先查看玩家投注是否超额
        issueConf = self.issueCalculator.getCurrentIssueConf(issueNumber)
        userMaxBetChip = issueConf.get('userMaxBetChip', -1)
        item = userModel.findOrCreateItemByIssueNumber(issueNumber)
        if userMaxBetChip and userMaxBetChip > 0 and \
            (item.leftBetValue + item.rightBetValue + betChip) > userMaxBetChip:
            return Tool.dictGet(self._clientConf,
                                'config.server.betChipOverflow')

        # 消耗玩家金币
        clientId = sessiondata.getClientId(userId)
        trueDelta, _ = userchip.incrChip(userId, activityGameId, -betChip,
                                         daoconst.CHIP_NOT_ENOUGH_OP_MODE_NONE,
                                         'ACT_BETGUESS_CHIP', 0, clientId)
        datachangenotify.sendDataChangeNotify(activityGameId, userId, 'chip')
        ftlog.debug('BetGuess.userBetChip:', 'userId=', userId, 'trueDelta=',
                    trueDelta)
        if trueDelta != -betChip:
            ftlog.debug('BetGuess.userBetChip:chipNotEnough')
            return Tool.dictGet(self._clientConf,
                                'config.server.chipNotEnough')

        # 玩家记录数据
        userModel.incrChip(issueNumber, isLeft, betChip)
        userModel.save()

        # 日志记录每个UID每场的下注额及下注项
        packageGameId = strutil.getGameIdFromHallClientId(
            sessiondata.getClientId(userId))
        ftlog.info('BetGuess.userBetChip', 'userId', userId, 'packageGameId',
                   packageGameId, 'activityGameId', activityGameId,
                   'activityId', self.getid(), 'issueNumber', issueNumber,
                   'isLeft', isLeft, 'betChip', betChip)
        return None
示例#37
0
 def _choiceTableRoom(self, userId):
     """选择一个房间影子Id"""
     shadowRoomIdList = self.shadowRoomIdOccupyList
     ignoreShadowRoomList = self.roomConf.get("ignoreShadowRoomList", [])
     usebleShadowRoomIdList = [
         v[0] for v in shadowRoomIdList if v[0] not in ignoreShadowRoomList
     ]
     choiceShadowRoomId = choice(usebleShadowRoomIdList[-2:])
     mainTaskId = util.getMainTaskId(userId, self.bigRoomId)  # 获得用户主线任务ID
     occupyData = self.roomConf.get("occupyMax", [0.9])
     maxSeatN = self.roomConf.get("tableConf", {}).get("maxSeatN", 4)
     if not isinstance(occupyData, list):
         occupyData = [occupyData]
     occupy = occupyData[-1]
     for _oc in occupyData:
         isFind = True
         for index, shadowRoomOccupy in enumerate(shadowRoomIdList):
             if shadowRoomIdList[index][0] in ignoreShadowRoomList:
                 continue
             if shadowRoomOccupy[1] >= _oc:
                 continue
             if maxSeatN > 1 and shadowRoomOccupy[2]:
                 if mainTaskId not in shadowRoomOccupy[2]:
                     continue
                 # elif shadowRoomOccupy[2].count(mainTaskId) <= 1:
                 #     continue
             choiceShadowRoomId = shadowRoomIdList[index][0]
             break
         else:
             isFind = False
         if isFind:
             occupy = _oc
             break
     ftlog.info("FishNewbieRoom._choiceTableRoom", "roomId=", self.roomId,
                "userId=", userId, "choiceShadowRoomId=",
                choiceShadowRoomId, "shadowRoomIdList=", shadowRoomIdList,
                "shadowRoomIdOccupyList=", self.shadowRoomIdOccupyList,
                "occupyData =", occupyData, "occupy =", occupy,
                "usebleShadowRoomIdList =", usebleShadowRoomIdList,
                "ignoreShadowRoomList =", ignoreShadowRoomList)
     return choiceShadowRoomId
示例#38
0
def uploadVideo(uploadUrl, token, uploadPath, videoData):
    filename = os.path.basename(uploadPath)
    formItems = []
    formItems.append(FormItemData('token', token))
    formItems.append(FormItemData('key', uploadPath))
    formItems.append(FormItemFile('file', videoData, filename))

    boundary = genBoundary()
    uploadData = encodeFormItems(boundary, formItems)
    headers = {
        'Content-Type':
        ['multipart/form-data; charset=utf-8; boundary=%s' % (boundary)]
    }

    if ftlog.is_debug():
        ftlog.debug('obsystem.uploader.uploadVideo uploadUrl=', uploadUrl,
                    'uploadPath=', uploadPath, 'token=', token, 'filename=',
                    filename, 'formItems=', formItems, 'boundary=', boundary,
                    'uploadData=', uploadData, 'headers=', headers)

    try:
        code, body = http.runHttp(method='POST',
                                  url=uploadUrl,
                                  header=headers,
                                  body=uploadData,
                                  connect_timeout=5,
                                  timeout=5)
        if ftlog.is_debug():
            ftlog.debug('uploader.uploadVideo uploadUrl=', uploadUrl,
                        'uploadPath=', uploadPath, 'token=', token, 'ret=',
                        (code, body))

        if code == 200:
            return 0, uploadPath

        ftlog.info('uploader.uploadVideo Fail uploadUrl=', uploadUrl,
                   'uploadPath=', uploadPath, 'token=', token, 'ret=',
                   (code, body))
        return -1, '上传失败'
    except:
        return -2, '上传失败'
示例#39
0
def _reloadConf():
    global _activities
    activities = {}
    conf = pkconfigure.getGameJson(DIZHU_GAMEID, 'activity.wx', {})
    for actConf in conf.get('activities', []):
        act = ActivityWxRegister.decodeFromDict(actConf)
        if act.actId in activities:
            raise TYBizConfException(actConf,
                                     'duplicate actId: %s' % act.actId)
        # if act.isExpired(pktimestamp.getCurrentTimestamp()):
        #     ftlog.info('activity_wx._reloadConf expired actId=', act.actId)
        #     continue
        activities[act.actId] = act

    try:
        _cleanupActivities(_activities)
        _initActivities(activities)
        _activities = activities
        ftlog.info('activity_wx._reloadConf actIds=', _activities.keys())
    except Exception as e:
        ftlog.error('activity_wx._reloadConf err=', e.message)
示例#40
0
def unlockMatchUser(gameId, userId, bigRoomId, instId, ctrlRoomId, tableId,
                    seatId):
    if ftlog.is_debug():
        ftlog.debug("match_remote.unlockMatchUser gameId=", gameId, "userId=",
                    userId, "bigRoomId=", bigRoomId, "instId=", instId,
                    "ctrlRoomId=", ctrlRoomId, "tableId=", tableId, "seatId=",
                    seatId)

    if _removeMatchUser(gameId, userId, bigRoomId, instId, ctrlRoomId):
        try:
            onlinedata.removeOnlineLoc(userId, ctrlRoomId, tableId)
        except:
            ftlog.error("match_remote.unlockMatchUser gameId=", gameId,
                        "userId=", userId, "bigRoomId=", bigRoomId, "instId=",
                        instId, "ctrlRoomId=", ctrlRoomId, "tableId=", tableId,
                        "seatId=", seatId)

    ftlog.info("match_remote.unlockMatchUser ok gameId=", gameId, "userId=",
               userId, "bigRoomId=", bigRoomId, "instId=", instId,
               "ctrlRoomId=", ctrlRoomId, "tableId=", tableId, "seatId=",
               seatId)
示例#41
0
def addInvitee(status, invitee, accepted):
    '''
    给userId的推荐列表增加inviteeUserId
    @param userId: 给哪个用户增加
    @param inviteeUserId: 被推荐人
    @return: status
    '''
    # 确认可以成为推荐人
    ensureCanBeInviter(status, invitee)
    if status.inviteeCount + 1 > MAX_INVITEE:
        ftlog.info('neituiguang.addInvitee overCountLimit userId=',
                   status.userId, 'invitee=', invitee, 'inviteeCount=',
                   status.inviteeCount, 'MAX_INVITEE=', MAX_INVITEE)
        return
    # 添加被推荐人
    status._addInvitee(invitee, accepted)
    _saveStatus(status)
    ftlog.info('neituiguang.addInvitee userId=', status.userId, 'invitee=',
               invitee, 'accepted=', accepted)
    TGHall.getEventBus().publishEvent(
        NeituiguangAddInviteeEvent(HALL_GAMEID, status.userId, invitee))
示例#42
0
def getGaoFangIp(clientId, ip, port):
    try:
        _, cver, _ = strutil.parseClientId(clientId)
        gaofangConfs = configure.getJson('poker:map.gaofangip', None)
        if gaofangConfs:
            policy = gaofangConfs['policy']
            if policy == 'tuyou':
                ip = gaofangConfs[policy].get(ip, ip)

            elif policy == 'aligaofang':
                original = gaofangConfs['original']
                group = original[ip + ':' + str(port)]
                groupIps = gaofangConfs[policy][group]
                if groupIps:
                    ip = random.choice(groupIps)
            if cver >= 3.78:
                ip = gaofangConfs['namespace'][ip]
    except:
        ftlog.error()
    ftlog.info('getGaoFangIp->', ip, port, clientId)
    return ip, port
示例#43
0
文件: handler.py 项目: zhaozw/hall37
def __registerRemoteRpcMethod(gameId, serverType, fullName, handler, method,
                              markParams):
    syncCall = markParams.get('syncCall', 0)
    assert (syncCall in (0, 1))

    groupBy = markParams.get('groupBy', '')
    assert (isinstance(groupBy, (str, unicode)))

    omethod = markParams['fun_method_original']
    paramkeys, _, __, ___ = inspect.getargspec(omethod)
    remoteGroupByIndex = paramkeys.index(groupBy)

    markParams['remoteServerType'] = serverType
    markParams['remoteSyncCall'] = syncCall
    markParams['remoteGroupByIndex'] = remoteGroupByIndex
    markParams['remoteGroupBy'] = groupBy
    markParams['remoteCmd'] = '_remote_rpc_'
    markParams['remoteAction'] = fullName + '.' + method.__name__
    markParams['remoteGameId'] = gameId

    ftlog.info('TCP RPC Remote ->remote=', fullName, 'method=', method)
示例#44
0
    def disbindFT(self, ftId, returnFee):
        from dizhu.friendtable import ft_service
        ftTable = self.findFT(ftId)
        if not ftTable:
            raise TYBizException(-1, '没有找到该牌桌')

        # 没有开始则退费
        if not ftTable.table or returnFee:
            self._returnFee(ftTable.userId, ftId, ftTable.ftConf)

        del self._ftMap[ftId]
        if ftTable.table:
            self._tableManager.returnTable(ftTable.table)
        ft_service.releaseFTId(ftId)

        ftlog.info('DizhuCtrlRoomFriend.disbindFT Succ', 'roomId=',
                   self.roomId, 'userId=', ftTable.userId, 'ftId=',
                   ftTable.ftId, 'nRound=', ftTable.ftConf.nRound,
                   'canDouble=', ftTable.ftConf.canDouble, 'playMode=',
                   ftTable.ftConf.playMode, 'fee=',
                   ftTable.ftConf.fee.toDict() if ftTable.ftConf.fee else None)
示例#45
0
    def handleRequest(self, msg):
        userId = msg.getParam('userId')
        gameId = msg.getParam('gameId')
        clientId = msg.getParam('clientId')
        activityId = msg.getParam('activityId')
        ftlog.debug('BetGuess.handleRequest:', 'userId=', userId, 'gameId=',
                    gameId, 'clientId=', clientId, 'activityId=', activityId,
                    'msg=', msg)

        action = msg.getParam('action')
        if action == 'ddz.act.betguess.betchip':
            betChip = msg.getParam('betChip', 0)
            isLeft = msg.getParam('isLeft')
            issueNumber = msg.getParam('issueNumber')
            return self.onActionBetChip(userId, betChip, isLeft, issueNumber)
        elif action == 'ddz.act.betguess.update':
            return self.buildActivityInfo(userId)
        else:
            ftlog.info('BetGuess.handleRequest:', 'userId=', userId,
                       'action not match')
            return {}
示例#46
0
    def gameReady(self, table):
        '''
        发牌,选择首叫,初始化gameRound
        '''
        gameRound = table.dealer.newGameRound(table)
        table.dealer.sendCardsPolicy.sendCards(table)
        
        seatCards = [seat.status.cards[:] for seat in gameRound.seats]
        baseCards = gameRound.baseCards[:]
        
        gameRound.firstCallSeat = table.dealer.firstCallPolicy.chooseFirstCall(table)

        if ftlog.is_debug():
            ftlog.info('Table gameReady',
                       'tableId=', table.tableId,
                       'roundId=', gameRound.roundId,
                       'seatCards=', seatCards,
                       'baseCards=', baseCards,
                       'firstCallSeat=', gameRound.firstCallSeat.seatId)
        
        table.fire(GameReadyEvent(table, seatCards, baseCards, gameRound.firstCallSeat))
示例#47
0
def _count_pps_info(wrapper):
    try:
        if wrapper.call_count % wrapper.pps_block == 0:
            ct = datetime.now()
            dt = ct - wrapper.pps_time
            dt = dt.seconds + dt.microseconds / 1000000.0
            pps = '%0.2f' % (wrapper.pps_block / dt)
            wrapper.pps_time = ct
            if wrapper.hits + wrapper.misses > 0:
                rate = '%0.3f' % (float(wrapper.hits) /
                                  float(wrapper.hits + wrapper.misses))
            else:
                rate = 'None'
            ftlog.info("LFUTIMECACHE PPS", pps, 'ALLCOUNT=',
                       wrapper.call_count,
                       'MAXSIZE=', wrapper.maxsize, 'CACHE COUNT=',
                       len(wrapper.cache), 'HITS=', wrapper.hits, 'MISSES=',
                       wrapper.misses, 'HIT RATE=', rate, 'NAME=',
                       wrapper.cache_name)
    except:
        ftlog.error()
示例#48
0
def unlockMatchUser(gameId, userId, bigRoomId, instId, ctrlRoomId, tableId,
                    seatId):
    if ftlog.is_debug():
        ftlog.debug('match_remote.unlockMatchUser gameId=', gameId, 'userId=',
                    userId, 'bigRoomId=', bigRoomId, 'instId=', instId,
                    'ctrlRoomId=', ctrlRoomId, 'tableId=', tableId, 'seatId=',
                    seatId)

    if _removeMatchUser(gameId, userId, bigRoomId, instId, ctrlRoomId):
        try:
            onlinedata.removeOnlineLoc(userId, ctrlRoomId, tableId)
        except:
            ftlog.error('match_remote.unlockMatchUser gameId=', gameId,
                        'userId=', userId, 'bigRoomId=', bigRoomId, 'instId=',
                        instId, 'ctrlRoomId=', ctrlRoomId, 'tableId=', tableId,
                        'seatId=', seatId)

    ftlog.info('match_remote.unlockMatchUser ok gameId=', gameId, 'userId=',
               userId, 'bigRoomId=', bigRoomId, 'instId=', instId,
               'ctrlRoomId=', ctrlRoomId, 'tableId=', tableId, 'seatId=',
               seatId)
示例#49
0
 def quit(self, table, seat):
     assert (seat.table == table)
     ftlog.info('PlayMode.quit',
                'roomId=', table.roomId,
                'tableId=', table.tableId,
                'seatId=', seat.seatId,
                'userId=', seat.userId)
     # 将用户位置信息存到redis, 清空大厅的位置信息
     if seat._status:
         seat._status.giveup = True
     if seat.player:
         seat.player.isQuit = 1
     timestamp = pktimestamp.getCurrentTimestamp()
     try:
         if seat.userId:
             onlinedata.removeOnlineLoc(seat.userId, table.roomId, table.tableId)
     except Exception, e:
         ftlog.warn('DizhuTableRoomNormalBase.leaveRoom removeOnlineLoc',
                    'roomId=', table.roomId,
                    'userId=', seat.userId,
                    'ex=', str(e))
示例#50
0
 def addCreateTableNo(cls, tableId, roomId, serverId, tableNoKey):
     """添加自建桌验证码数据 只在GT服调用
     """
     ftlog.debug('CreateTableData.addCreateTableNo tableId:', tableId
         , ' roomId:', roomId
         , ' serverId:', serverId
         , ' tableNoKey:', tableNoKey)
     
     tableNoMapValue = json.dumps([tableId,roomId])
     result = daobase.executeMixLua(cls.ADD_CREATE_TABLE_NO_SCRIPT_NAME
             , 6
             , cls._getCreateTableNoKey()
             , tableNoKey
             , serverId
             , cls._getTableNoMapTableIdKey()
             , tableId
             , tableNoMapValue
     )
     
     ftlog.info("===addCreateTableNo===",serverId, tableNoKey, result)
     return result
示例#51
0
    def sendTableInfoRes(self, seat):
        logUserIds = [66706022]
        if seat.player and seat.userId in logUserIds:
            ftlog.info('DizhuTableProtoFriend.sendTableInfoRes beforeSentMsg',
                       'tableId=', self.tableId,
                       'userId=', seat.userId,
                       'gameClientVer=', seat.player.gameClientVer,
                       'isGiveup=', seat.isGiveup,
                       'isQuit=', seat.player.isQuit,
                       'seats=', [(s.userId, s.seatId) for s in self.table.seats])

        if seat.player and not seat.isGiveup and not seat.player.isQuit:
            mp = self.buildTableInfoResp(seat, 0)
            router.sendToUser(mp, seat.userId)
            if seat.userId in logUserIds:
                ftlog.info('DizhuTableProtoFriend.sendTableInfoRes sentMsg',
                           'tableId=', self.tableId,
                           'userId=', seat.userId,
                           'gameClientVer=', seat.player.gameClientVer,
                           'seats=', [(seat.userId, seat.seatId) for seat in self.table.seats],
                           'mp=', mp.pack())
示例#52
0
文件: bireport.py 项目: zhaozw/hall37
def _report(arglist, argdict, isHinfo=0):
    if _ENABLE_BIFILE:
        global _BILOGER
        if _BILOGER is None:
            log_file_fullpath = gdata.globalConfig()['log_path']
            log_file_fullpath = log_file_fullpath + '/bi.' + gdata.serverId() + '.log'
            _BILOGER = ftlog.openNormalLogfile(log_file_fullpath)
        jsondata = [timestamp.formatTimeMs(), gdata.serverId()]
        jsondata.extend(arglist)
        jsondata.append(argdict)
        msg = strutil.dumps(jsondata)
        _BILOGER.info(msg)
    else:
        jsondata = ['BIREPORT', gdata.serverId()]
        jsondata.extend(arglist)
        jsondata.append(argdict)
        msg = strutil.dumps(jsondata)
        if isHinfo:
            ftlog.hinfo(msg)
        else:
            ftlog.info(msg)
示例#53
0
def addPlayerToGroup(serverId, roomId, masterRoomId, groupId, playerList):
    startTime = time.time()
    _area, group = findGroup(roomId, groupId)
    if not group:
        ftlog.error('group_match_remote.addPlayerToGroup serverId=', serverId,
                    'roomId=', roomId, 'masterRoomId=',
                    masterRoomId, 'groupId=', groupId, 'playerCount=',
                    len(playerList), 'err=', 'NotFoundGroup')
        return
    playerList = decodePlayerList(playerList)
    for player in playerList:
        group.addPlayer(player)
    if ftlog.is_debug():
        ftlog.info('group_match_remote.addPlayerToGroup serverId=', serverId,
                   'roomId=', roomId, 'masterRoomId=', masterRoomId,
                   'groupId=', groupId, 'userIds=',
                   [p.userId for p in playerList])
    ftlog.info('group_match_remote.addPlayerToGroup OK serverId=', serverId,
               'roomId=', roomId, 'masterRoomId=', masterRoomId, 'groupId=',
               groupId, 'playerCount=', len(playerList), 'usedTime=',
               time.time() - startTime)
示例#54
0
 def checkCompensateOrderId(cls, gameId, realGameId, userId, orderId,
                            productId):
     '''
     自动补单处理
     '''
     if orderId in ('ios_compensate', 'momo_compensate'):
         ftlog.info('checkCompensateOrderId compensate fix->', gameId,
                    realGameId, userId, orderId, productId)
         try:
             clientId = sessiondata.getClientId(userId)
             orderId = cls._makeOrderId(gameId, userId, productId)
             order = hallstore.storeSystem.buyProduct(
                 gameId, realGameId, userId, clientId, orderId, productId,
                 1)
             orderId = order.orderId
             ftlog.info('checkCompensateOrderId compensate fix->orderId=',
                        orderId)
         except:
             ftlog.error('ERROR checkCompensateOrderId compensate fix !!',
                         gameId, realGameId, userId, orderId, productId)
     return orderId
示例#55
0
 def handleTableCallExchange(self, userId, seatId, message):
     """
     换牌动作
     """
     if self.table.dropCardProcessor.getState(
     ) != 0 or self.table.qiangGangHuProcessor.getState() != 0:
         return
     pengInfo = message.getParam('peng', [])
     gangInfo = message.getParam('gang', {})
     # 换的是碰牌中的癞子
     if pengInfo and len(pengInfo) > 0:
         pengInfo.sort()
         self.table.exchangeMagicTilePeng(userId, pengInfo)
     else:
         if gangInfo and gangInfo.has_key('style'):
             gangInfo['pattern'].sort()
             self.table.exchangeMagicTileGang(userId, gangInfo)
         else:
             ftlog.info(
                 'handleTableCallExchange error neither peng nor gang info in message'
             )
示例#56
0
 def getScoreByResults(self, results, maxFan=0):
     index = 0
     score = 0
     for result in results:
         index += result['index']
         score += result['score']
     scoreIndex = self.tableConfig.get(MTDefine.FAN_LIST,
                                       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
     ftlog.info('MLuosihuOneResult.getScoreByResults scoreIndex:',
                scoreIndex)
     if len(scoreIndex) <= index:
         # 如果超出最大番型的定义,按照len-1计算,防止超出边界
         ftlog.info(
             'MLuosihuOneResult.getScoreByResults exceed fan_list in MTDefine, index=',
             index)
         index = len(scoreIndex) - 1
     fan = scoreIndex[index]
     if maxFan:
         # maxFan不为0时,限制最大番数。算最大番型时,不要传递此参数,要么就算不出来了
         if fan > maxFan:
             fan = maxFan
     finalScore = fan + score
     ftlog.info('MLuosihuOneResult.getScoreByResults score=', finalScore,
                ' fan=', fan, ' index=', index, ' result=', results)
     return finalScore, index
示例#57
0
def initialize():
    ftlog.info("newfish quest_system initialize begin")
    global _inited
    if not _inited:
        _inited = True
        # 每日任务系统初始化
        daily_quest.initialize()
        from newfish.game import TGFish
        TGFish.getEventBus().subscribe(CatchEvent, _triggerCatchEvent)                                  # 捕鱼事件
        TGFish.getEventBus().subscribe(GameTimeEvent, _triggerGameTimeEvent)                            # 每日任务
        TGFish.getEventBus().subscribe(BuyChestEvent, _triggerBuyChestEvent)
        TGFish.getEventBus().subscribe(UseSkillEvent, _triggerUseSkillEvent)                            # 使用n次技能
        TGFish.getEventBus().subscribe(UseSmiliesEvent, _triggerUseSmiliesEvent)
        TGFish.getEventBus().subscribe(WinCmpttTaskEvent, _triggerWinCmpttTaskEvent)
        TGFish.getEventBus().subscribe(WinNcmpttTaskEvent, _triggerWinNcmpttTaskEvent)
        TGFish.getEventBus().subscribe(WinBonusTaskEvent, _triggerWinBonusTaskEvent)
        TGFish.getEventBus().subscribe(EnterTableEvent, _triggerEnterTableEvent)                        # 进入招财模式
        TGFish.getEventBus().subscribe(StoreBuyEvent, _triggerStoreBuyEvent)
        TGFish.getEventBus().subscribe(TableTaskEndEvent, _triggerTableTaskEndEvent)
        TGFish.getEventBus().subscribe(ShareFinishEvent, _triggerShareFinishEvent)
        TGFish.getEventBus().subscribe(CheckinEvent, _triggerCheckinEvent)                              # 每日签到
        TGFish.getEventBus().subscribe(UseCoolDownEvent, _triggerUseCoolDownEvent)
        TGFish.getEventBus().subscribe(FireEvent, _triggerFireEvent)
        TGFish.getEventBus().subscribe(ItemChangeEvent, _triggerItemChangeEvent)
        TGFish.getEventBus().subscribe(GainChestEvent, _triggerGainChestEvent)
        TGFish.getEventBus().subscribe(RobberyBulletProfitEvent, _triggerRobberyBulletProfitEvent)
        TGFish.getEventBus().subscribe(EventUserLogin, _triggerUserLoginEvent)                          # 登陆事件
        TGFish.getEventBus().subscribe(SkillLevelUpEvent, _triggerSkillLevelUpEvent)                    # 提升技能等级
        TGFish.getEventBus().subscribe(AchievementLevelUpEvent, _triggerAchievementLevelUpEvent)        # 荣耀任务升级事件
        TGFish.getEventBus().subscribe(GunLevelUpEvent, _triggerLevelUpEvent)                           # 解锁多少倍炮

        TGFish.getEventBus().subscribe(UseSkillItemEvent, _triggerUseSkillItemEvent)                    # 触发使用道具卡次数
        TGFish.getEventBus().subscribe(UserLevelUpEvent, _triggerUserLevelUpEvent)                      # 触发玩家升级事件
        TGFish.getEventBus().subscribe(MiniGameBossExchange, _triggerMiniGameBossExchangeEvent)         # 玩家Boss素材兑换
        TGFish.getEventBus().subscribe(PlayMiniGame, _triggerPlayMiniGameEvent)                         # 玩家玩小游戏次数
        TGFish.getEventBus().subscribe(HitPoseidonEvent, _triggerHitPoseidonEvent)                      # 击中波塞冬事件
        TGFish.getEventBus().subscribe(JoinGrandPrixEvent, _triggerJoinGrandPrixEvent)                  # 参加大奖赛事件
        TGFish.getEventBus().subscribe(TreasureLevelUp, _triggerTreasureLevelUpEvent)                   # 宝藏升级事件
        TGFish.getEventBus().subscribe(PrizeWheelSpinEvent, _triggerPrizeWheelSpinEvent)                # 转动轮盘
    ftlog.info("newfish quest_system initialize end")
示例#58
0
def unRegisterCmdActionMethod(gameId, fullName, handler, method, markParams):
    cmd = markParams.get('cmd', None)
    assert (isinstance(cmd, (str, unicode)) and len(cmd.strip()) > 0)
    assert (cmd.find('#') < 0)

    action = markParams.get('action', '')
    assert (isinstance(action, (str, unicode)))
    action = action.strip()
    assert (action.find('#') < 0)

    clientIdVer = markParams.get('clientIdVer', 0.0)
    assert (isinstance(clientIdVer, (int, float)))

    scope = markParams.get('scope', 'global')
    assert (scope in ('global', 'game'))

    cmdpath = cmd + '#' + action
    if scope == 'game':
        cmdpath = cmdpath + '#' + str(gameId)

    vcalls = runcmd._cmd_path_methods.get(cmdpath, None)
    ftlog.info('unRegisterCmdActionMethod->vcalls=', vcalls)
    if vcalls:
        for x in xrange(len(vcalls)):
            if vcalls[x][0] == clientIdVer:
                ftlog.info('unRegisterCmdActionMethod->cmdpath=', cmdpath,
                           'clientIdVer=', clientIdVer, 'old=', vcalls[x])
                del vcalls[x]
                return 1
    ftlog.info('unRegisterCmdActionMethod->cmdpath=', cmdpath, 'clientIdVer=',
               clientIdVer, 'old=notfound !!')
    return 0
示例#59
0
 def doConsumDelivery(self, appId, userId, orderId, prodId, prodCount,
                      platformOrder):
     ftlog.info('doConsumDelivery->', appId, userId, orderId, prodId,
                prodCount, platformOrder)
     appKey = hallconf.getAppKeyInfo(appId).get('key', '')
     if not runhttp.checkHttpParamCode(appKey):
         mo = MsgPack()
         mo.setCmd('prod_delivery')
         mo.setError(1, '校验失败')
         ftlog.info('doConsumDelivery->', appId, userId, orderId, prodId,
                    prodCount, platformOrder, 'result=code verify error')
         return mo
     userdata.clearUserCache(userId)
     mo = MsgPack()
     mo.setCmd('prod_delivery')
     mo.setParam('userId', userId)
     mo.setParam('orderId', orderId)
     mo.setParam('prodCount', prodCount)
     mo.setParam('prodId', prodId)
     mo.setParam('appId', appId)
     mo.setParam('orderPlatformId', platformOrder)
     mo.setParam('ok', '1')
     isSub = runhttp.getParamInt('is_monthly', 0)
     if isSub:
         mo.setParam('isSub', isSub)
     chargeType, chargeMap, consumeMap = self.getChargeInfos()
     mo.setParam('consumeMap', consumeMap)
     mo.setParam('chargeMap', chargeMap)
     mo.setParam('chargeType', chargeType)
     ret = router.queryUtilServer(mo, userId)
     ftlog.info('doConsumDelivery->', appId, userId, orderId, prodId,
                prodCount, platformOrder, 'result=', ret)
     if isinstance(ret, (str, unicode)) and ret.find('error') < 0:
         return 'success'
     return 'error'
示例#60
0
def connect_agent_eachother(server_id):
    """
    Agent进程调用,监听自己的端口,并与其他Agent建立连接
    """
    ftlog.debug('connect_agent_eachother', server_id)
    myconf = ftcon.server_map[server_id]
    myip = myconf['ip']
    agentids = ftcon.server_type_map.get('AG', None)
    for agentid in agentids:
        agent = ftcon.server_map.get(agentid, None)
        ip = agent['ip']
        inner_port = agent['protocols']['server']['a2s']
        outer_port = agent['protocols']['server']['a2a']
        if agentid == server_id:
            # listen inner port for inner process
            factory = Factory()
            factory.protocol = A2SProtocol
            reactor.listenTCP(inner_port, factory)
            ftlog.info('Agent Start, listen for services port', inner_port)
            # listen outer port for other agent
            factory = Factory()
            factory.protocol = A2AProtocol
            reactor.listenTCP(outer_port, factory)
            ftlog.info('Agent Start, listen for agent port', outer_port)
        else:
            # 只连接比自己的ID大的agent,这样节省一半的连接,n*(n-1)/2
            if cmp(agentid, server_id) > 0:
                factory = FTReconnectFactory()
                factory.protocol = A2AProtocol
                if ip == myip:
                    ip = '127.0.0.1'
                reactor.connectTCP(ip, outer_port, factory)
                ftlog.info('Agent connect Agent', agentid, server_id)