Esempio n. 1
0
class AsyncTest(object):
    def __init__(self, n):
        self.count = n
        self.executor = Executor()
        self.begin = self.end = 0

    def run(self):
        self.executor.set("r", 0)
        self.executor.set("r_ok", 0)
        self.executor.add_condition(lambda: self.executor.get('r_ok') >= 1,
                                    [self.finish, []])
        self.executor.add_condition(
            lambda: self.executor.get('r') >= self.count,
            [self.executor.inc1, ['r_ok']])

        self.begin = time.time()
        for i in range(self.count):
            Request(LOCAL_TEST_URL, self.callback)

    def callback(self, *args):
        self.executor.inc1("r")

    def finish(self):
        self.end = time.time()
        print("{} times Request cost: {}".format(self.count,
                                                 self.end - self.begin))
Esempio n. 2
0
class iRoomManager(object):
    """
	服务端游戏对象的基础接口类
	"""
    def __init__(self):
        self.rooms = {}
        self.destroyState = None
        self.destroy_ts = None
        self.executor = Executor()

    def addRoom(self, room):
        self.rooms[room.roomID] = room

    def delRoom(self, room):
        if room.roomID in self.rooms:
            del self.rooms[room.roomID]

    def enterRoom(self, roomID, user):
        if roomID in self.rooms:
            room = self.rooms[roomID]
            room.reqEnterRoom(user)
        else:
            user.enterRoomFailed(const.ENTER_FAILED_ROOM_NO_EXIST)

    def quitRoom(self, roomID, user):
        if roomID in self.rooms:
            room = self.rooms[roomID]
            room.reqLeaveRoom(user)

            if room.isEmpty:
                self.delRoom(room)
                room.destroySelf()

    def swapTileToTop(self, roomID, tile):
        if roomID in self.rooms:
            room = self.rooms[roomID]
            room.swapTileToTop(tile)

    def getRoom(self, roomID):
        return self.rooms.get(roomID)

    def readyForDestroy(self):
        INFO_MSG('iRoomManager readyForDestroy()')
        self.destroyState = const.DESTROY_PROCESS_BEGIN
        self.destroy_ts = utility.get_cur_timestamp()

        card_req = {}
        for key in list(self.rooms.keys()):
            room = self.rooms[key]
            if room.room_type == const.AGENT_ROOM and room.current_round < 1:
                # 代开房间没开始打, 返还房卡
                card_cost, diamond_cost = switch.calc_cost(
                    room.game_round, room.getCalCostNeed())
                if room.agent:
                    key = room.agent.accountName
                    if key in card_req:
                        val = card_req[key]
                        card_req[key] = (val[0] + card_cost,
                                         val[1] + diamond_cost)
                    else:
                        card_req[key] = (card_cost, diamond_cost)
            try:
                room.destroyByServer()
            except:
                pass
        self.rooms.clear()
        self.handleCardBack(card_req)

    def handleCardBack(self, req_d):
        if switch.DEBUG_BASE != 0 or len(req_d) == 0:
            # 1.测试服不用管 2.长度为空也直接结束
            self.destroyProcessFinish()
            return
        INFO_MSG("handleCardBack, all Request = {}".format(req_d))
        self.executor.set('c', 0)
        self.executor.set('c_ok', 0)
        self.executor.add_condition(lambda: self.executor.get('c_ok') >= 1,
                                    [self.destroyProcessFinish, []])
        self.executor.add_condition(
            lambda: self.executor.get('c') >= len(req_d),
            [self.executor.inc1, ['c_ok']])

        for k, v in req_d.items():
            utility.update_card_diamond(
                k, v[0], v[1], Functor(self.updateCb, k, v),
                "FourDeckCards safe kill server, pay back agent:{}".format(
                    k))  # reason 必须为英文

    def updateCb(self, accountName, value, content=None):
        try:
            content = content.decode()
            if content[0] != '{':
                INFO_MSG("{}: {} payBack failed1, content = {}".format(
                    accountName, value, content))
            else:
                INFO_MSG("{}: {} payBack succeed, content = {}".format(
                    accountName, value, content))
        except:
            INFO_MSG("{}: {} payBack failed2, content = {}".format(
                accountName, value, content))
        finally:
            self.executor.inc1('c')

    def destroyProcessFinish(self):
        self.destroyState = const.DESTROY_PROCESS_END

    def clubDismissed(self, club_id):
        for key in list(self.rooms.keys()):
            room = self.rooms[key]
            if room.room_type == const.CLUB_ROOM and room.club and room.club.clubId == club_id:
                if room.current_round < 1:
                    try:
                        room.destroyByServer("茶楼已解散")
                    except:
                        pass
                else:
                    room.club_table = None
Esempio n. 3
0
class ClubStub(KBEngine.Entity, GameObject):

	def __init__(self):
		KBEngine.Entity.__init__(self)
		GameObject.__init__(self)
		self.isReady = False
		self.clubs = {}
		self.executor = Executor()
		self.loadClubs()
		x42.ClubStub = self

	def loadClubs(self):
		club_list = list(self.clubList)
		if len(club_list) == 0:
			self.initFinish()
			return

		self.executor.set('c', 0)
		self.executor.set('c_ok', 0)
		self.executor.add_condition(lambda: self.executor.get('c_ok') >= 1, [self.initFinish, []])
		self.executor.add_condition(lambda: self.executor.get('c') >= len(club_list), [self.executor.inc1, ['c_ok']])

		for id in club_list:
			def create_cb(baseRef, databaseID, wasActive):
				self.executor.inc1('c')
				if baseRef:
					self.clubs[baseRef.clubId] = baseRef
				else:
					if databaseID in self.clubList:
						self.clubList.remove(databaseID)
					INFO_MSG("ClubStub load club failed. Club_%d not exist!" % databaseID)

			KBEngine.createEntityFromDBID("Club", id, create_cb)

	def initFinish(self):
		self.isReady = True
		self.add_repeat_timer(1, 6 * 60 * 60, self.processClubTableResult)

	def clubOperation(self, avatar_mb, op, club_id, args):
		club = self.clubs.get(club_id)
		if club is None:
			avatar_mb.clubOperationFailed(const.CLUB_OP_ERR_CLUB_NOT_EXIST)
			return

		club.doOperation(avatar_mb, op, args)

	def createClub(self, avatar_mb, club_game_type, club_name, club_params_dict):
		if not self.canCreateClub(avatar_mb.userId):
			avatar_mb.showTip("达到创建亲友圈数量上限, 无法创建更多亲友圈")
			return
		owner_info = {
			'userId': avatar_mb.userId,
			'uuid': avatar_mb.uuid,
			'sex': avatar_mb.sex,
			'name': avatar_mb.name,
			'head_icon': avatar_mb.head_icon,
			'accountName': avatar_mb.accountName,
			'isAgent': avatar_mb.isAgent,
			'login_time': avatar_mb.logout_time,
			'logout_time': avatar_mb.logout_time
		}
		self._doCreateClub(owner_info, club_game_type, club_name, club_params_dict, avatar_mb)

	def createClubFromServer(self, user_id, club_name):
		if not self.canCreateClub(user_id):
			DEBUG_MSG("ClubStub create from server, user {} can not create".format(user_id))
			return

		def find_cb(result):
			if not result:
				INFO_MSG("createClubFromServer:: user {} not found".format(user_id))
			else:
				INFO_MSG("ClubStub create from server,  uid: {}, club name: {}".format(user_id, club_name))
				club_game_type, params = roomParamsHelper.clubDefault_roomParams()
				self._doCreateClub(result, club_game_type, club_name, params)

		x42.GW.getUserInfoByUID(user_id, find_cb)

	def canCreateClub(self, user_id):
		for club in self.clubs.values():
			if club.isOwner(user_id):
				return False
		return True

	def _doCreateClub(self, user_info, club_game_type, club_name, club_params_dict, avatar_mb=None):
		club_name = utility.filter_emoji(club_name)
		club_name = club_name[:const.CLUB_NAME_LENGTH]
		self.clubCount += 1
		club_id = utility.gen_club_id(self.clubCount)
		user_id = user_info["userId"]
		owner_info = {
			'userId': user_info["userId"],
			'uuid': user_info["uuid"],
			'sex': user_info["sex"],
			'nickname': user_info["name"],
			'head_icon': user_info["head_icon"],
			'accountName': user_info["accountName"],
			'isAgent': user_info["isAgent"],
		}

		log_info = {
			'login_time': user_info['login_time'],
			'logout_time': user_info['logout_time']
		}

		# 开房时候需要, 这里就直接填上
		club_params_dict['club_id'] = club_id
		club_params_dict['owner_uid'] = user_id
		params = {
			'clubId': club_id,
			'name': club_name,
			'owner': owner_info,
			'gameType': club_game_type,
			'roomParams': club_params_dict,
		}
		INFO_MSG("ClubStub player{} createClub {}".format(user_id, params))
		club = KBEngine.createEntityLocally("Club", params)
		if club:
			club.writeToDB(Functor(self._onClubSaved, avatar_mb, owner_info, log_info))

	def _onClubSaved(self, avatar_mb, owner_info, log_info, success, club):
		uid = owner_info['userId']
		INFO_MSG("ClubStub player{} _onClubSaved state: {}, {}".format(uid, success, club.databaseID))

		if success:
			self.clubList.append(club.databaseID)
			self.clubs[club.clubId] = club
			mem_info = {
				'userId': uid,
				'uuid': owner_info['uuid'],
				'sex': owner_info['sex'],
				'nickname': owner_info['nickname'],
				'head_icon': owner_info['head_icon'],
				'login_time': log_info['login_time'],
				'logout_time': log_info['logout_time'],
				'notes': '',
				'ts': utility.get_cur_timestamp(),
				'power': const.CLUB_POWER_OWNER,
			}
			# 这么些是为了防止回调回来的时候avatar已经销毁
			if avatar_mb and not avatar_mb.isDestroyed:
				club.members[uid] = mem_info
				club.member_status[uid] = {'online': True, 'free': True, 'login_time': log_info['login_time'], 'logout_time': log_info['logout_time'],}
				avatar_mb.clubList.append(club.clubId)
				avatar_mb.createClubCallback(club.getDetailInfo(uid))
			else:
				club._addMemberIn(uid, mem_info)
			self.writeToDB()

	def deleteClub(self, avatar_mb, club_id):
		club = self.clubs.get(club_id)
		if club is None:
			avatar_mb.clubOperationFailed(const.CLUB_OP_ERR_CLUB_NOT_EXIST)
			return

		if club.isOwner(avatar_mb.userId):
			self.clubs.pop(club_id)
			self.clubList.remove(club.databaseID)
			club.dismiss()
			avatar_mb.deleteClubSucceed(club_id)
		else:
			avatar_mb.clubOperationFailed(const.CLUB_OP_ERR_PERMISSION_DENY)


	def deleteClubFromServer(self, club_id):
		club = self.clubs.get(club_id)
		if club is None:
			INFO_MSG("deleteClubFromServer:: club {} not found".format(club_id))
			return
		self.clubs.pop(club_id)
		self.clubList.remove(club.databaseID)
		club.dismiss()


	def lockClubFromServer(self, club_id, state):
		club = self.clubs.get(club_id)
		if club is None:
			INFO_MSG("lockClubFromServer:: club {} not found".format(club_id))
			return
		club.setClubLockSwitch(None, 1 if state else 0)

	def addTableForClub(self, club_id, num):
		club = self.clubs.get(club_id)
		if club:
			club.addClubTable(num)

	def getClub(self, club_id):
		return self.clubs.get(club_id)

	def getClubAbstract(self, club_id):
		club = self.clubs.get(club_id)
		if club is None:
			return None

		return club.getAbstract()

	def getClubDetailInfo(self, club_id, uid):
		club = self.clubs.get(club_id)
		if club is None:
			return None, const.CLUB_OP_ERR_CLUB_NOT_EXIST

		return club.getDetailInfo(uid), None

	def getClubTableInfoList(self, club_id):
		""" 为了分页下发数据 """
		club = self.clubs.get(club_id)
		if club is None:
			return None, const.CLUB_OP_ERR_CLUB_NOT_EXIST

		return club.table_mgr.getTableListInfo(True), None

	def isClubMember(self, club_id, user_id):
		""" 检查玩家是否是亲友圈的成员 """
		club = self.clubs.get(club_id)
		if club is None:
			return False
		return club.isMember(user_id)

	def processClubTableResult(self):
		for v in self.clubs.values():
			v.processTableResult()

	def getUserClubList(self, userId):
		clubs = []
		for club_id in self.clubs.keys():
			if self.isClubMember(club_id, userId):
				clubs.append(club_id)
		return clubs

	def onDestroy(self):
		self.clubs.clear()
		x42.ClubStub = None
		KBEngine.globalData['ClubStub'] = None
Esempio n. 4
0
class SportWeeklyStub(BaseEntity):
    def __init__(self):
        BaseEntity.__init__(self)
        self.sportWeeklyDict = {}
        self.executor = Executor()
        self.loadWeeklyStubs()
        x42.SportWeeklyStub = self

    # step 1
    def loadWeeklyStubs(self):
        weekly_list = list(self.sportWeeklyList)
        if len(weekly_list) == 0:
            self.loadFinish()
            return

        self.executor.set('s_load', 0)
        self.executor.set('s_load_over', 0)

        self.executor.add_condition(
            lambda: self.executor.get('s_load_over') >= 1,
            [self.loadFinish, []])
        self.executor.add_condition(
            lambda: self.executor.get('s_load') >= len(weekly_list),
            [self.executor.inc1, ["s_load_over"]])

        for id in weekly_list:

            def createSportWeekly(baseRef, databaseID, wasActive):
                self.executor.inc1("s_load")
                if baseRef:
                    self.sportWeeklyDict[baseRef.sportId] = baseRef
                else:
                    if databaseID in self.sportWeeklyList:
                        self.sportWeeklyList.remove(databaseID)

            KBEngine.createBaseFromDBID("SportWeekly", id, createSportWeekly)

    # step 2
    def loadFinish(self):
        # 根据表的变化而变化
        table_weekly_sports = h1global.rc.sportDict[const.SPORT_WEEKLY]
        for sportId in self.sportWeeklyDict:
            if sportId not in table_weekly_sports:
                self.sportWeeklyDict.pop(sportId)
                self.sportWeeklyDict[sportId].destroyself(True)

        newSportIdList = []
        for id in table_weekly_sports:
            if id not in self.sportWeeklyDict:
                newSportIdList.append(id)
        self.createSportWeekly(newSportIdList)

    # step 3
    def createSportWeekly(self, newSportIdList):
        if len(newSportIdList) == 0:
            self.createFinish()
            return
        self.executor.set('s_create', 0)
        self.executor.set('s_create_over', 0)

        self.executor.add_condition(
            lambda: self.executor.get('s_create_over') >= 1,
            [self.createFinish, []])
        self.executor.add_condition(
            lambda: self.executor.get('s_create') >= len(newSportIdList),
            [self.executor.inc1, ["s_create_over"]])

        for id in newSportIdList:
            sport = KBEngine.createBaseLocally("SportWeekly", {'sportId': id})
            self.sportWeeklyDict[id] = sport
            if sport:
                sport.writeToDB(self._onSportWeeklySaved)

    def _onSportWeeklySaved(self, isSaved, baseRef):
        self.executor.inc1('s_create')
        return

    # step 4 over
    def createFinish(self):
        DEBUG_MSG("create sportWeekly Finish")
        return

    def join(self, avt_mb, sportId):
        if sportId in self.sportWeeklyDict:
            sport_info = h1global.rc.sportDict[const.SPORT_WEEKLY][sportId]
            t = time.localtime()
            for k in sport_info["time"]:
                week_days = sport_info["time"][k]

                s_t = time.strptime(
                    '{}-{}-{} {}'.format(t.tm_year, t.tm_mon, t.tm_mday, k[0]),
                    '%Y-%m-%d %H:%M:%S')
                e_t = time.strptime(
                    '{}-{}-{} {}'.format(t.tm_year, t.tm_mon, t.tm_mday, k[1]),
                    '%Y-%m-%d %H:%M:%S')
                if t.tm_wday in week_days and time.mktime(
                        s_t) < time.time() < time.mktime(e_t):
                    self.sportWeeklyDict[sportId].join(avt_mb)
                    break
            else:
                avt_mb.client.showTip("不在周赛事开启时间段内")
        else:
            avt_mb.client.showTip("找不到该赛事")

    def getWeeklySportRank(self, avt_mb, sportId):
        if sportId in self.sportWeeklyDict:
            self.sportWeeklyDict[sportId].getWeeklySportRank(avt_mb)
        else:
            ERROR_MSG(
                "getWeeklySportRank error weekly sport:{}".format(sportId))

    def record(self, sportId, rc_list):
        if sportId in self.sportWeeklyDict:
            self.sportWeeklyDict[sportId].record(rc_list)
        else:
            ERROR_MSG("record not found weekly sport:{}".format(sportId))

    def addRoom(self, room):
        if room.sportId in self.sportWeeklyDict:
            self.sportWeeklyDict[room.sportId].addRoom(room)
        else:
            ERROR_MSG("addRoom not found weekly sport:{}".format(room.sportId))

    def dismissRoom(self, room):
        if room.sportId in self.sportWeeklyDict:
            self.sportWeeklyDict[room.sportId].dismissRoom(room)
        else:
            ERROR_MSG("deleteRoom not found weekly sport:{}".format(
                room.sportId))
Esempio n. 5
0
class ClubStub(BaseEntity):
    def __init__(self):
        BaseEntity.__init__(self)
        self.isReady = False
        self.clubs = {}
        self.executor = Executor()
        self.loadClubs()
        x42.ClubStub = self

    def loadClubs(self):
        club_list = list(self.clubList)
        if len(club_list) == 0:
            self.initFinish()
            return

        self.executor.set('c', 0)
        self.executor.set('c_ok', 0)
        self.executor.add_condition(lambda: self.executor.get('c_ok') >= 1,
                                    [self.initFinish, []])
        self.executor.add_condition(
            lambda: self.executor.get('c') >= len(club_list),
            [self.executor.inc1, ['c_ok']])

        for id in club_list:

            def create_cb(baseRef, databaseID, wasActive):
                self.executor.inc1('c')
                if baseRef:
                    self.clubs[baseRef.clubId] = baseRef
                else:
                    if databaseID in self.clubList:
                        self.clubList.remove(databaseID)
                    INFO_MSG("ClubStub load club failed. Club_%d not exist!" %
                             databaseID)

            KBEngine.createBaseFromDBID("Club", id, create_cb)

    def initFinish(self):
        self.isReady = True
        self.add_repeat_timer(1, 6 * 60 * 60, self.processClubTableResult)

    def clubOperation(self, avatar_mb, op, club_id, args):
        club = self.clubs.get(club_id)
        if club is None:
            avatar_mb.clubOperationFailed(const.CLUB_OP_ERR_CLUB_NOT_EXIST)
            return

        club.doOperation(avatar_mb, op, args)

    def createClub(self, avatar_mb, club_name, club_params_dict):
        if avatar_mb.isAgent != 1:
            avatar_mb.clubOperationFailed(const.CLUB_OP_ERR_PERMISSION_DENY)
            return

        club_name = utility.filter_emoji(club_name)
        club_name = club_name[:const.CLUB_NAME_LENGTH]
        self.clubCount += 1
        club_id = utility.gen_club_id(self.clubCount)
        owner_info = {
            'userId': avatar_mb.userId,
            'uuid': avatar_mb.uuid,
            'sex': avatar_mb.sex,
            'nickname': avatar_mb.name,
            'head_icon': avatar_mb.head_icon,
            'accountName': avatar_mb.accountName,
        }
        params = {
            'clubId': club_id,
            'name': club_name,
            'owner': owner_info,
            'roomType': club_params_dict,
        }
        INFO_MSG("ClubStub player{} createClub {}".format(
            avatar_mb.userId, params))
        club = KBEngine.createBaseLocally("Club", params)
        if club:
            club.writeToDB(Functor(self._onClubSaved, avatar_mb, owner_info))

    def _onClubSaved(self, avatar_mb, owner_info, success, club):
        uid = owner_info['userId']
        INFO_MSG("ClubStub player{} _onClubSaved state: {}, {}".format(
            uid, success, club.databaseID))

        if success:
            self.clubList.append(club.databaseID)
            self.clubs[club.clubId] = club
            mem_info = {
                'userId': uid,
                'uuid': owner_info['uuid'],
                'sex': owner_info['sex'],
                'nickname': owner_info['nickname'],
                'head_icon': owner_info['head_icon'],
                'notes': '',
                'ts': utility.get_cur_timestamp(),
            }
            # 这么些是为了防止回调回来的时候avatar已经销毁
            if avatar_mb and not avatar_mb.isDestroyed:
                club.members[uid] = mem_info
                avatar_mb.clubList.append(club.clubId)
                avatar_mb.createClubCallback(club.getDetailInfo())
            else:
                club._addMemberIn(uid, mem_info)
            self.writeToDB()

    def deleteClub(self, avatar_mb, club_id):
        club = self.clubs.get(club_id)
        if club is None:
            avatar_mb.clubOperationFailed(const.CLUB_OP_ERR_CLUB_NOT_EXIST)
            return

        if club.isOwner(avatar_mb.userId):
            self.clubs.pop(club_id)
            self.clubList.remove(club.databaseID)
            club.dismiss()
            avatar_mb.deleteClubSucceed(club_id)
        else:
            avatar_mb.clubOperationFailed(const.CLUB_OP_ERR_PERMISSION_DENY)

    def getClubAbstract(self, club_id):
        club = self.clubs.get(club_id)
        if club is None:
            return None

        return club.getAbstract()

    def getClubDetailInfo(self, club_id):
        club = self.clubs.get(club_id)
        if club is None:
            return None, const.CLUB_OP_ERR_CLUB_NOT_EXIST

        return club.getDetailInfo(), None

    def isClubMember(self, club_id, user_id):
        """ 检查玩家是否是亲友圈的成员 """
        club = self.clubs.get(club_id)
        if club is None:
            return False
        return club.isMember(user_id)

    def processClubTableResult(self):
        for v in self.clubs.values():
            v.processTableResult()