Exemplo n.º 1
0
		def callback(content):
			content = content.decode()
			try:
				DEBUG_MSG("cards response: {}".format(content))
				if content[0] != '{':
					if getattr(self, 'client', None):
						self.client.createRoomFailed(const.CREATE_FAILED_OTHER)
					return
				data = json.loads(content)
				card_cost, diamond_cost = switch.calc_cost(maxOldDealNum, maxLoseScore)
				if not KBEngine.globalData["GameWorld"].free_play and card_cost > data["card"] and diamond_cost > data["diamond"]:
					if getattr(self, 'client', None):
						self.client.createRoomFailed(const.CREATE_FAILED_NO_ENOUGH_CARDS)
					return
				params = {
					'owner_uid': self.userId,
					'game_round': 999,
					'lucky_tile': 0,
					"maxOldDealNum" : maxOldDealNum,
					"startOldDealNum" : startOldDealNum,
					"diceAddNum" : diceAddNum,
					"isSameAdd"	: isSameAdd,
					"maxLoseScore" : maxLoseScore,
					'is_agent': is_agent,
					"createRoomInfoList" : createRoomInfoList
				}
				KBEngine.createBaseAnywhere("GameRoom", params, self.createRoomCallback)
			except:
				DEBUG_MSG("createRoom callback error:{}".format(content))
				if getattr(self, 'self', None):
					self.client.createRoomFailed(const.CREATE_FAILED_OTHER)
Exemplo n.º 2
0
 def callback(content):
     content = content.decode()
     try:
         DEBUG_MSG("cards response: {}".format(content))
         if content[0] != '{':
             if getattr(self, 'client', None):
                 self.client.createRoomFailed(const.CREATE_FAILED_OTHER)
             return
         data = json.loads(content)
         card_cost, diamond_cost = switch.calc_cost(
             game_round, room_mode)
         if not KBEngine.globalData[
                 "GameWorld"].free_play and card_cost > data[
                     "card"] and diamond_cost > data["diamond"]:
             if getattr(self, 'client', None):
                 self.client.createRoomFailed(
                     const.CREATE_FAILED_NO_ENOUGH_CARDS)
             return
         params = {
             'owner_uid': self.userId,
             'room_mode': room_mode,
             'game_round': game_round,
             'insert_card': insert_card,
             'deal_mode': deal_mode,
             'score_mode': score_mode,
             'changeSeat': changeSeat,
             'best_phase': best_phase,
             'is_agent': is_agent,
         }
         KBEngine.createBaseAnywhere("GameRoom", params,
                                     self.createRoomCallback)
     except:
         DEBUG_MSG("createRoom callback error:{}".format(content))
         if getattr(self, 'self', None):
             self.client.createRoomFailed(const.CREATE_FAILED_OTHER)
Exemplo n.º 3
0
		def callback(content):
			content = content.decode()
			try:
				DEBUG_MSG("cards response: {}".format(content))
				if content[0] != '{':
					if getattr(self, 'client', None):
						self.client.createRoomFailed(const.CREATE_FAILED_OTHER)
					return
				data = json.loads(content)
				card_cost, diamond_cost = switch.calc_cost(game_round, player_num, pay_mode)
				if not KBEngine.globalData["GameWorld"].free_play and card_cost > data["card"] and diamond_cost > data["diamond"]:
					if getattr(self, 'client', None):
						self.client.createRoomFailed(const.CREATE_FAILED_NO_ENOUGH_CARDS)
					return
				params = {
					'owner_uid': self.userId,
					'player_num': player_num,
					'pay_mode': pay_mode,
					'win_quantity': win_quantity,
					'game_round': game_round,
					'king_num' : king_num,
					'is_agent': is_agent,
				}
				KBEngine.createBaseAnywhere("GameRoom", params, self.createRoomCallback)
			except:
				DEBUG_MSG("createRoom callback error:{}".format(content))
				if getattr(self, 'self', None):
					self.client.createRoomFailed(const.CREATE_FAILED_OTHER)
Exemplo n.º 4
0
		def callback(content):
			if content is None:
				DEBUG_MSG("createRoom callback error: content is None, user id {}".format(self.userId))
				self.createRoomFailed(const.CREATE_FAILED_NET_SERVER_ERROR)
				return
			try:
				DEBUG_MSG("cards response: {}".format(content))
				if content[0] != '{':
					if getattr(self, 'client', None):
						self.createRoomFailed(const.CREATE_FAILED_NET_SERVER_ERROR)
					return
				data = json.loads(content)
				card_cost, diamond_cost = switch.calc_cost(game_round, {"pay_mode":pay_mode})
				if not KBEngine.globalData["GameWorld"].free_play and card_cost > data["card"] and diamond_cost > data["diamond"]:
					if getattr(self, 'client', None):
						self.client.createRoomFailed(const.CREATE_FAILED_NO_ENOUGH_CARDS)
					return
				params ={
					# 基本必填信息
					'owner_uid'			: self.userId,
					'player_num'		: 4,
					# client 2 svr
					# 'game_mode'			: game_mode,
					'game_round'		: game_round,
					'hand_prepare'		: hand_prepare,

					'pay_mode'			: pay_mode,
					'room_type'			: room_type,
				}
				KBEngine.createBaseAnywhere("GameRoom", params, self.createRoomCallback)
			except:
				err, msg, stack = sys.exc_info()
				DEBUG_MSG("createRoom callback error:{} , exc_info: {} ,{}".format(content, err, msg))
				self.createRoomFailed(const.CREATE_FAILED_OTHER)
Exemplo n.º 5
0
	def createRoomCallback(self, room, err = None):
		DEBUG_MSG("createRoomCallback")
		if room:
			room.roomID = utility.gen_room_id(room.id)
			if room.is_agent == 1:
				def callback(content):
					try:
						content = content.decode()
						if content[0] != '{':
							DEBUG_MSG(content)
							return
						room.reqEnterRoom(self, True)
						self.room = room
						KBEngine.globalData["GameWorld"].addRoom(room)
						info = room.get_init_client_dict()
						if getattr(self, 'client', None):
							self.client.createRoomSucceed(info)
					except:
						DEBUG_MSG("agent consume callback error:{}".format(content))
				card_cost, diamond_cost = switch.calc_cost(room.game_round, room.player_num, room.pay_mode)
				if switch.DEBUG_BASE:
					callback('{"card":99, "diamond":999}'.encode())
				else:
					utility.update_card_diamond(self.accountName, -card_cost, -diamond_cost ,callback, "NingBoMJ RoomID:{}".format(self.roomID)) # reason 必须为英文
			else:
				room.reqEnterRoom(self, True)
				self.room = room
				KBEngine.globalData["GameWorld"].addRoom(room)
				info = room.get_init_client_dict()
				if getattr(self, 'client', None):
					self.client.createRoomSucceed(info)
		else:
			if getattr(self, 'client', None):
				self.client.createRoomFailed(const.CREATE_FAILED_OTHER)
Exemplo n.º 6
0
	def dropRoom(self):
		self.dismiss_timer = None
		for i,p in enumerate(self.players_list):
			if p and p.mb:
				try:
					p.mb.quitRoomSucceed()
				except:
					pass

		if self.room_type == const.AGENT_ROOM and self.agent:
			# 将房间从代理房间中删除
			if not self.agent.isDestroyed:
				self.agent.agentRoomDropped(self.roomID)

			try:
				# 如果是代开房, 没打完一局返还房卡
				if switch.DEBUG_BASE == 0 and self.current_round < 1 and self.agent and self.pay_mode == const.AGENT_PAY_MODE:
					card_cost, diamond_cost = switch.calc_cost(self.game_round, self.getCalCostNeed())

					def callback(room_id, user_id, content):
						try:
							content = content.decode()
							if content[0] != '{':
								DEBUG_MSG(content)
								return
						except:
							DEBUG_MSG("dropRoom{} AgentRoom return Failed, userID = {}. return {} back".format(room_id, user_id, (card_cost, diamond_cost)))

					utility.update_card_diamond(self.agent.accountName, card_cost, diamond_cost,
												Functor(callback, self.roomID, self.agent.userId), "KouDianDian drop AgentRoomID:{}".format(self.roomID))  # reason 必须为英文
			except:
				pass

		self._reset()
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
	def pay2StartGame(self):
		""" 开始游戏 """
		DEBUG_MSG("{} game_mode:{},game_max_lose:{},game_round:{},hand_prepare:{} pay2StartGame state:{}"
				  .format(self.prefixLogStr, self.game_mode, self.game_max_lose, self.game_round, self.hand_prepare, self.state))

		if self.timeout_timer:
			self.cancel_timer(self.timeout_timer)
			self.timeout_timer = None

		self.state = const.ROOM_TRANSITION

		# 仅仅在第1局扣房卡, 不然每局都会扣房卡
		if self.current_round == 0:
			self.origin_players_list = self.players_list[:]
			if switch.DEBUG_BASE != 0:
				self.paySuccessCbk()
				return

			card_cost, diamond_cost = switch.calc_cost(self.game_round, self.getCalCostNeed())
			if self.pay_mode == const.NORMAL_PAY_MODE:
				def pay_callback(content):
					if self._check_pay_callback(content):
						self.paySuccessCbk()

				utility.update_card_diamond(self.origin_players_list[0].mb.accountName, -card_cost, -diamond_cost, pay_callback, "{} RoomID:{}".format(const.GAME_NAME, self.roomID))
			elif self.pay_mode == const.AGENT_PAY_MODE:
				# 开房的时候已经扣了房卡 续房的时候需要再扣一次,这个时候房卡不足怎么办?
				if self._continue_room_flag:
					def pay_callback(content):
						if self._check_pay_callback(content):
							self.paySuccessCbk()

					utility.update_card_diamond(self.agent.accountName, -card_cost, -diamond_cost, pay_callback, "{} RoomID:{}".format(const.GAME_NAME, self.roomID))  # reason 必须为英文
			elif self.pay_mode == const.CLUB_PAY_MODE:
				pay_account = self.club.owner['accountName']
				reason = "{} Club:{} RoomID:{}".format(const.GAME_NAME, self.club.clubId, self.roomID)

				def pay_callback(content):
					if self._check_pay_callback(content):
						self.paySuccessCbk()

				utility.update_card_diamond(pay_account, -card_cost, -diamond_cost, pay_callback, reason)
			elif self.pay_mode == const.AA_PAY_MODE:
				pay_accounts = [p.mb.accountName for p in self.players_list if p is not None]
				if self.club:
					reason = "{} Club:{} AA RoomID:{}".format(const.GAME_NAME, self.club.clubId, self.roomID)
				else:
					reason = "{} AA RoomID:{}".format(const.GAME_NAME, self.roomID)

				def pay_callback(content):
					if self._check_aa_pay_callback(content):
						self.paySuccessCbk()

				utility.update_card_diamond_aa(pay_accounts, -card_cost, -diamond_cost, pay_callback, reason)
			else:
				ERROR_MSG("pay2StartGame Error: No this PayMode:{}".format(self.pay_mode))
				return
		else:
			self.paySuccessCbk()
Exemplo n.º 9
0
	def pay2StartGame(self):
		""" 开始游戏 """
		DEBUG_MSG("room:{},curround:{},game_mode:{},king_mode:{},game_round:{},hand_prepare:{} pay2StartGame state:{}".format(self.roomID, self.current_round,
		self.game_mode, self.king_mode, self.game_round, self.hand_prepare,
		self.state))

		if self.timeout_timer:
			self.cancel_timer(self.timeout_timer)
			self.timeout_timer = None

		self.state = const.ROOM_TRANSITION

		# 在第2局开始扣房卡
		if self.current_round == 1:
			if switch.DEBUG_BASE:
				self.paySuccessCbk()
				return

			card_cost, diamond_cost = switch.calc_cost(self.game_round, self.getCalCostNeed())
			if self.pay_mode == const.NORMAL_PAY_MODE:
				pay_account = self.origin_players_list[0].mb.accountName
				reason = "KouDianDian RoomID:{}".format(self.roomID)

				def pay_callback(content):
					if self._check_pay_callback(content):
						self.paySuccessCbk()

				utility.update_card_diamond(pay_account, -card_cost, -diamond_cost, pay_callback, reason)
			elif self.pay_mode == const.AGENT_PAY_MODE:
				# 开房的时候已经扣了房卡
				self.paySuccessCbk()
			elif self.pay_mode == const.CLUB_PAY_MODE:
				pay_account = self.club.owner['accountName']
				reason = "KouDianDian Club:{} RoomID:{}".format(self.club.clubId, self.roomID)

				def pay_callback(content):
					if self._check_pay_callback(content):
						self.paySuccessCbk()

				utility.update_card_diamond(pay_account, -card_cost, -diamond_cost, pay_callback, reason)
			elif self.pay_mode == const.AA_PAY_MODE:
				pay_accounts = [p.mb.accountName for p in self.players_list]
				if self.club:
					reason = "KouDianDian Club:{} AA RoomID:{}".format(self.club.clubId, self.roomID)
				else:
					reason = "KouDianDian AA RoomID:{}".format(self.roomID)

				def pay_callback(content):
					if self._check_aa_pay_callback(content):
						self.paySuccessCbk()

				utility.update_card_diamond_aa(pay_accounts, -card_cost, -diamond_cost, pay_callback, reason)
			else:
				ERROR_MSG("pay2StartGame Error: No this PayMode:{}".format(self.pay_mode))
				return
		else:
			self.paySuccessCbk()
Exemplo n.º 10
0
 def callback(content):
     if content is None:
         DEBUG_MSG(
             "createRoom callback error: content is None, user id {}".
             format(self.userId))
         self.createRoomFailed(const.CREATE_FAILED_NET_SERVER_ERROR)
         return
     try:
         DEBUG_MSG("cards response: {}".format(content))
         if content[0] != '{':
             self.createRoomFailed(const.CREATE_FAILED_NET_SERVER_ERROR)
             return
         data = json.loads(content)
         card_cost, diamond_cost = switch.calc_cost(
             game_round, {
                 "game_mode": game_mode,
                 "pay_mode": pay_mode,
                 "game_max_lose": game_max_lose
             })
         if not KBEngine.globalData[
                 "GameWorld"].free_play and card_cost > data[
                     "card"] and diamond_cost > data["diamond"]:
             self.createRoomFailed(const.CREATE_FAILED_NO_ENOUGH_CARDS)
             return
         params = {
             # 基本必填信息
             'owner_uid': self.userId,
             'king_num': 1,
             'player_num': 4,
             'lucky_num': 0,
             # client 2 svr
             'game_mode': game_mode,
             'base_score': base_score if game_mode == 0 else 1,
             'king_mode': play_list[0],
             'begin_dealer_mul': play_list[1],
             'win_mode': play_list[2],
             'three_job': play_list[3],
             'pong_useful': play_list[4],
             'bao_tou': play_list[5],
             'round_max_lose': round_max_lose if game_mode == 0 else 0,
             'game_max_lose':
             game_max_lose if game_mode == 1 else 999999,
             'game_round': game_round if game_mode == 0 else 999999,
             'hand_prepare': hand_prepare,
             'pay_mode': pay_mode,
             'room_type': room_type,
         }
         KBEngine.createBaseAnywhere("GameRoom", params,
                                     self.createRoomCallback)
     except:
         err, msg, stack = sys.exc_info()
         DEBUG_MSG(
             "createRoom callback error:{} , exc_info: {} ,{}".format(
                 content, err, msg))
         self.createRoomFailed(const.CREATE_FAILED_OTHER)
Exemplo n.º 11
0
        def callback(content):
            try:
                DEBUG_MSG("cards response: {}".format(content))
                if content[0] != '{':
                    self.createRoomFailed(const.CREATE_FAILED_OTHER)
                    return
                data = json.loads(content)
                card_cost, diamond_cost = switch.calc_cost(room_op["game_round"])
                can_do = False
                if x42.GW.free_play:
                    can_do = True
                if card_cost and card_cost <= data['card']:
                    can_do = True
                if diamond_cost and diamond_cost <= data['diamond']:
                    can_do = True

                if not can_do:
                    self.createRoomFailed(const.CREATE_FAILED_NO_ENOUGH_CARDS)
                    return

                detail_op = {}
                detail_op["game_mode"] = game_mode
                # FIXME 测试用, 正式时候记得改回来
                # detail_op["game_round"] = game_round
                detail_op["game_round"] = 2
                detail_op["player_num"] = player_num
                detail_op["game_function"] = game_function
                detail_op["game_start"] = game_start
                detail_op["game_hei3"] = game_hei3
                detail_op["game_deal"] = game_deal
                detail_op["game_force"] = game_force
                detail_op["game_cardnum"] = game_cardnum
                detail_op["game_plays"] = game_plays
                detail_op["game_end"] = game_end
                detail_op["anticheating"] = anticheating
                detail_op["is_competition"] = is_competition
                detail_op["is_agent"] = is_agent

                detail_op.setdefault("match_mode", belong_info["match_mode"])
                detail_op.setdefault("group_id", belong_info["group_id"])
                detail_op.setdefault("team_uuid", belong_info["team_uuid"])
                detail_op.setdefault("sportId", belong_info["sportId"])
                detail_op.setdefault("owner_uid", self.userId)
                detail_op.setdefault("create_time", time.time())

                DEBUG_MSG("reqCreate----GroupRoom", detail_op)
                KBEngine.createBaseAnywhere("GameRoom", detail_op, self.createRoomCallback)
            except:
                self.createRoomFailed(const.CREATE_FAILED_OTHER)
Exemplo n.º 12
0
    def createRoomCallback(self, room, err=None):
        DEBUG_MSG("createRoomCallback")
        if room:
            if room.room_type == const.AGENT_ROOM:
                if room.pay_mode == const.AGENT_PAY_MODE:

                    def callback(content):
                        self.req_entering_room = False
                        try:
                            if content is None or content[0] != '{':
                                DEBUG_MSG(
                                    "agent consume callback error: content is None or error, room id {} ,content: {}"
                                    .format(room.roomId, content))
                                # 此处应当执行退款逻辑
                                room.destroySelf()
                                return
                            room.agent = self
                            x42.GW.addRoom(room)
                            self.playingRoomList.append(room.roomId)
                            self.getPlayingRoomInfo(True)
                        except:
                            DEBUG_MSG("agent consume callback error:{}".format(
                                content))
                            # 此处应当执行退款逻辑
                            room.destroySelf()
                            return

                    card_cost, diamond_cost = switch.calc_cost(
                        room.game_round, room.pay_mode)
                    if switch.DEBUG_BASE:
                        callback('{"card":99, "diamond":9999}')
                    else:
                        utility.update_card_diamond(
                            self.accountName, -card_cost, -diamond_cost,
                            callback, "GuiXi RoomID:{}".format(
                                room.roomId))  # reason 必须为英文
                elif room.pay_mode == const.AA_PAY_MODE:
                    self.req_entering_room = False
                    room.agent = self
                    x42.GW.addRoom(room)
                    self.playingRoomList.append(room.roomId)
                    self.getPlayingRoomInfo(True)
                else:
                    self.createRoomFailed(const.CREATE_FAILED_OTHER)
            else:
                room.reqEnterRoom(self, True)
        else:
            self.createRoomFailed(const.CREATE_FAILED_OTHER)
Exemplo n.º 13
0
 def callback(content):
     if content is None:
         DEBUG_MSG(
             "createRoom callback error: content is None, user id {}".
             format(self.userId))
         self.createRoomFailed(const.CREATE_FAILED_NET_SERVER_ERROR)
         return
     try:
         DEBUG_MSG("cards response: {}".format(content))
         if content[0] != '{':
             self.createRoomFailed(const.CREATE_FAILED_NET_SERVER_ERROR)
             return
         data = json.loads(content)
         card_cost, diamond_cost = switch.calc_cost(
             game_round, {
                 "round_mode": round_mode,
                 "pay_mode": pay_mode
             })
         if not KBEngine.globalData[
                 "GameWorld"].free_play and card_cost > data[
                     "card"] and diamond_cost > data["diamond"]:
             self.createRoomFailed(const.CREATE_FAILED_NO_ENOUGH_CARDS)
             return
         params = {
             'owner_uid': self.userId,
             'king_num': 1,
             'player_num': 4,
             'game_round': game_round,
             'round_mode': round_mode,
             'base_score_mode': base_score_mode,
             'pay_mode': pay_mode,
             'game_mode': game_mode,
             'king_mode': king_mode,
             'max_lose': max_lose,
             'score': score,
             'job': job,
             'discard_seconds': discard_seconds,
             'hand_prepare': hand_prepare,
             'room_type': room_type,
         }
         KBEngine.createBaseAnywhere("GameRoom", params,
                                     self.createRoomCallback)
     except:
         err, msg, stack = sys.exc_info()
         DEBUG_MSG(
             "createRoom callback error:{} , exc_info: {} ,{}".format(
                 content, err, msg))
         self.createRoomFailed(const.CREATE_FAILED_OTHER)
Exemplo n.º 14
0
		def _check_user_info(content):
			if content is None:
				DEBUG_MSG("room:{0},curround:{1} userId:{2} enterRoomFailed callback error: content is None".format(self.roomID, self.current_round, avt_mb.userId))
				if not first:
					avt_mb.enterRoomFailed(const.CREATE_FAILED_NET_SERVER_ERROR)
				return False
			try:
				data = json.loads(content)
				card_cost, diamond_cost = switch.calc_cost(self.game_round, self.getCalCostNeed())
				if card_cost > data["card"]:
					avt_mb.enterRoomFailed(const.ENTER_FAILED_ROOM_DIAMOND_NOT_ENOUGH)
					return False
			except:
				err, msg, stack = sys.exc_info()
				DEBUG_MSG("room:{0},curround:{1} _check_user_info callback error:{2} , exc_info: {3} ,{4}".format(self.roomID, self.current_round, content, err, msg))
				avt_mb.enterRoomFailed(const.CREATE_FAILED_OTHER)
				return False
			return True
Exemplo n.º 15
0
    def createRoomCallback(self, room, err=None):
        if room:
            if room.is_agent == 1:
                def callback(content):
                    if content[0] != '{':
                        DEBUG_MSG(content)
                        return
                    self.createRoomSucceed(room)

                card_cost, diamond_cost = switch.calc_cost(room.game_round)
                if switch.DEBUG_BASE:
                    callback('{"card":99, "diamond":999}')
                else:
                    utility.update_card_diamond(self.accountName, -card_cost, -diamond_cost, callback,
                                                "PaoDeKuai RoomID:{}".format(self.roomID))  # reason 必须为英文
            else:
                self.createRoomSucceed(room)
        else:
            self.createRoomFailed(const.CREATE_FAILED_OTHER)
Exemplo n.º 16
0
			def user_cb(content):
				DEBUG_MSG("cardCheck user_cb content is {}".format(content))
				if content is None:
					DEBUG_MSG("cardCheck user_cb content is None")
					callable(callback) and callback(False, "网络有点问题")
					return
				try:
					data = json.loads(content)
					# AA付费 自己房卡必须大于等于房间最低消耗数量, 否则不让玩家坐下游戏

					card_cost, diamond_cost = switch.calc_cost(club_game_round, self.club.getCalCostNeed())
					if data["card"] >= card_cost:
						callable(callback) and callback(True, None)
					else:
						callable(callback) and callback(False, "您的房卡不足, 无法坐下游戏")
				except:
					import traceback
					ERROR_MSG(traceback.format_exc())
					callable(callback) and callback(False, "网络有点问题")
Exemplo n.º 17
0
        def callback(content):
            content = content.decode()
            try:
                data = json.loads(content)
                card_cost, diamond_cost = switch.calc_cost(
                    self.game_round, self.player_num, self.pay_mode)
                if diamond_cost > data["diamond"]:
                    avt_mb.enterRoomFailed(
                        const.ENTER_FAILED_ROOM_DIAMOND_NOT_ENOUGH)
                    return
                # 代开房
                if first and self.is_agent == 1:
                    self.agent = PlayerProxy(avt_mb, self, -1)
                    self.players_dict[avt_mb.userId] = self.agent
                    avt_mb.enterRoomSucceed(self, -1)
                    return

                for i, p in enumerate(self.players_list):
                    if p and p.mb and p.mb.userId == avt_mb.userId:
                        p.mb = avt_mb
                        avt_mb.enterRoomSucceed(self, i)
                        return

                DEBUG_MSG("Room.reqEnterRoom: %s" % (self.roomID))
                idx = self.getSit()
                n_player = PlayerProxy(avt_mb, self, idx)
                self.players_dict[avt_mb.userId] = n_player
                self.players_list[idx] = n_player
                # 确认准备
                # if idx not in self.confirm_next_idx:
                # 	self.confirm_next_idx.append(idx)

                if not first:
                    self.broadcastEnterRoom(idx)
                    self.check_same_ip()

                if self.isFull:
                    self.origin_players_list = self.players_list[:]
            except:
                DEBUG_MSG("enterRoomFailed callback error:{}".format(content))
Exemplo n.º 18
0
 def callback(content):
     if content is None:
         DEBUG_MSG(
             "createRoom callback error: content is None, user id {}".
             format(self.userId))
         self.createRoomFailed(const.CREATE_FAILED_NET_SERVER_ERROR)
         return
     # try:
     DEBUG_MSG("cards response: {}".format(content))
     if content[0] != '{':
         self.createRoomFailed(const.CREATE_FAILED_NET_SERVER_ERROR)
         return
     data = json.loads(content)
     card_cost, diamond_cost = switch.calc_cost(game_round, pay_mode)
     if not KBEngine.globalData[
             "GameWorld"].free_play and card_cost > data[
                 "card"] and diamond_cost > data["diamond"]:
         self.createRoomFailed(const.CREATE_FAILED_NO_ENOUGH_CARDS)
         return
     # @formatter:off
     params = {
         'owner_uid': self.userId,
         'king_num': 0,
         'player_num': player_num,
         'game_round': game_round,
         'pay_mode': pay_mode,
         'game_mode': game_mode,
         'max_lose': max_lose,
         'lucky_num': lucky_num,
         'discard_seconds': 0,
         'hand_prepare': hand_prepare,
         'room_type': room_type,
     }
     # @formatter:on
     KBEngine.createEntityAnywhere("GameRoom", params,
                                   self.createRoomCallback)
Exemplo n.º 19
0
	def startGame(self):
		""" 开始游戏 """
		DEBUG_MSG("startGame")
		self.op_record = []
		self.state = 1
		self.current_round += 1

		diceList = self.throwTheDice([self.dealer_idx])
		idx, num = self.getMaxDiceIdx(diceList)

		# 仅仅在第1局扣房卡, 不然每局都会扣房卡
		def callback(content):
			content = content.decode()
			try:
				if content[0] != '{':
					DEBUG_MSG(content)
					self.dropRoom()
					return
				# 第一局时房间默认房主庄家, 之后谁上盘赢了谁是, 如果臭庄, 最后摸牌的人是庄
				for p in self.players_list:
					p.reset()
				self.current_idx = self.dealer_idx

				self.initTiles()
				self.deal(self.king_num)
				dragon_greens_list = [p.dragon_greens for i,p in enumerate(self.players_list)]
				for p in self.players_list:
					if p and p.mb:
						DEBUG_MSG("start game,dealer_idx:{0},tiles:{1}, kingTiles:{2}, diceList:{3},leftTileNum:{4}".format(self.dealer_idx, p.tiles, self.kingTiles, diceList, len(self.tiles)))
						p.mb.startGame(self.dealer_idx, p.tiles, dragon_greens_list, self.kingTiles, diceList)
				
				self.beginRound()
			except:
				DEBUG_MSG("consume failed!")

		if self.current_round == 1 and self.is_agent == 0:
			card_cost, diamond_cost = switch.calc_cost(self.game_round, self.player_num)
			if switch.DEBUG_BASE:
				callback('{"card":99, "diamond":999}'.encode())
			else:
				signal = 0
				def payCallback(content):
					nonlocal signal
					try:
						signal += 1
						if signal == len(self.players_list):
							callback(content)
					except:
						DEBUG_MSG("AA payCallback Failed")
				if self.player_num == 3:
					utility.update_card_diamond(self.players_list[0].mb.accountName, -card_cost, -diamond_cost, payCallback, "WuNingMJ RoomID:{}".format(self.roomID))
					utility.update_card_diamond(self.players_list[1].mb.accountName, -card_cost, -diamond_cost, payCallback, "WuNingMJ RoomID:{}".format(self.roomID))
					utility.update_card_diamond(self.players_list[2].mb.accountName, -card_cost, -diamond_cost, payCallback, "WuNingMJ RoomID:{}".format(self.roomID))
				else:
					utility.update_card_diamond(self.players_list[0].mb.accountName, -card_cost, -diamond_cost, payCallback, "WuNingMJ RoomID:{}".format(self.roomID))
					utility.update_card_diamond(self.players_list[1].mb.accountName, -card_cost, -diamond_cost, payCallback, "WuNingMJ RoomID:{}".format(self.roomID))
					utility.update_card_diamond(self.players_list[2].mb.accountName, -card_cost, -diamond_cost, payCallback, "WuNingMJ RoomID:{}".format(self.roomID))
					utility.update_card_diamond(self.players_list[3].mb.accountName, -card_cost, -diamond_cost, payCallback, "WuNingMJ RoomID:{}".format(self.roomID))
			return

		DEBUG_MSG("start Game: Room{0} - Round{1}".format(self.roomID, str(self.current_round)+'/'+str(self.game_round)))

		callback('{"card":99, "diamond":999}'.encode())
Exemplo n.º 20
0
    def startGame(self):
        """ 开始游戏 """
        self.op_record = []
        self.controller_discard_list = []
        self.deskPokerList = [[] for i in range(const.ROOM_PLAYER_NUMBER)]
        self.state = 1
        self.current_round += 1
        self.key_card = 0

        #扣费后开始游戏的回调
        def callback(content):
            content = content.decode()
            # try:
            if content[0] != '{':
                DEBUG_MSG(content)
                self.dropRoom()
                return
            for p in self.players_list:
                p.reset()
            self.initCards()
            self.deal()
            if self.changeSeat:
                if True or self.current_round == 1 or len(
                        self.show_empty_list) == 2:
                    # 根据需求每次重新换座位
                    self.random_key_card()
                    first_key_idx, second_key_idx = self.getKeyCardSeat()
                    self.swap_list = self.swapSeat(first_key_idx,
                                                   second_key_idx)
                    self.controller_idx = self.swap_list.index(first_key_idx)
                    self.wait_idx = self.controller_idx
                else:
                    self.key_card = 0
                    self.controller_idx = self.show_empty_list[0]
                    self.wait_idx = self.controller_idx
            else:
                if len(self.show_empty_list) > 0:
                    self.controller_idx = self.show_empty_list[0]
                    self.wait_idx = self.controller_idx
                else:
                    self.controller_idx = 0
                    self.wait_idx = self.controller_idx
            self.show_empty_list = []

            #DEBUG_MSG
            for i, p in enumerate(self.players_list):
                DEBUG_MSG("player [{0}] cards: {1}".format(p.idx, p.cards))
            for p in self.players_list:
                if p and p.mb:
                    p.start()
                    p.mb.startGame(self.controller_idx, self.key_card, p.cards,
                                   self.swap_list)
            # except:
            # 	DEBUG_MSG("consume failed!")

        if self.current_round == 1 and self.is_agent == 0:
            # 仅仅在第1局扣房卡, 不然每局都会扣房卡
            card_cost, diamond_cost = switch.calc_cost(self.game_round,
                                                       self.room_mode)
            if switch.DEBUG_BASE:
                callback('{"card":99, "diamond":999}'.encode())
            else:
                utility.update_card_diamond(
                    self.players_list[0].mb.accountName, -card_cost,
                    -diamond_cost, callback,
                    "BaiBianShuangKou RoomID:{}".format(self.roomID))
            return

        DEBUG_MSG("start Game: Room{0} - Round{1}".format(
            self.roomID,
            str(self.current_round) + '/' + str(self.game_round)))

        callback('{"card":99, "diamond":999}'.encode())
Exemplo n.º 21
0
    def startGame(self):
        """ 开始游戏 """
        DEBUG_MSG("startGame")
        self.op_record = []
        self.state = 1
        self.current_round += 1
        self.wait_give_up_list = []
        self.give_up_list = []
        self.polling_give_up_op = -1
        for i, p in enumerate(self.players_list):
            if p is not None:
                p.wreaths = []

        diceList = self.throwTheDice([self.dealer_idx])
        idx, num = self.getMaxDiceIdx(diceList)

        # 仅仅在第1局扣房卡, 不然每局都会扣房卡
        def callback(content):
            content = content.decode()
            try:
                if content[0] != '{':
                    DEBUG_MSG(content)
                    self.dropRoom()
                    return
                # 第一局时房间默认房主庄家, 之后谁上盘赢了谁是, 如果臭庄, 最后摸牌的人是庄
                for p in self.players_list:
                    p.reset()
                self.current_idx = self.dealer_idx
                #圈风
                if sum([1 for state in self.player_dealer_state
                        if state == 1]) == self.player_num:
                    windIdx = (self.prevailing_wind + 1 -
                               const.WIND_EAST) % len(const.WINDS)
                    self.prevailing_wind = const.WINDS[windIdx]
                    self.player_dealer_state = [0, 0, 0, 0]
                self.player_dealer_state[self.dealer_idx] = 1
                #自风
                for i, p in enumerate(self.players_list):
                    if p is not None:
                        p.wind = (self.player_num + i - self.dealer_idx
                                  ) % self.player_num + const.WIND_EAST
                self.initTiles()
                self.deal(self.king_num)
                wreathsList = [
                    p.wreaths for i, p in enumerate(self.players_list)
                ]
                playerWindList = [
                    p.wind for i, p in enumerate(self.players_list)
                ]

                for p in self.players_list:
                    if p and p.mb:
                        DEBUG_MSG(
                            "start game,dealer_idx:{0},tiles:{1}, wreathsList:{2}, kingTiles:{3}, diceList:{4},leftTileNum:{5}"
                            .format(self.dealer_idx, p.tiles, wreathsList,
                                    self.kingTiles, diceList, len(self.tiles)))
                        p.mb.startGame(self.dealer_idx, p.tiles, wreathsList,
                                       self.kingTiles, self.prevailing_wind,
                                       playerWindList, diceList)

                self.beginRound()
            except:
                DEBUG_MSG("consume failed!")

        if self.current_round == 1 and self.is_agent == 0:
            card_cost, diamond_cost = switch.calc_cost(self.game_round,
                                                       self.player_num,
                                                       self.pay_mode)
            if switch.DEBUG_BASE:
                callback('{"card":99, "diamond":999}'.encode())
            elif self.pay_mode == 1:
                utility.update_card_diamond(
                    self.players_list[0].mb.accountName, -card_cost,
                    -diamond_cost, callback,
                    "FengHua RoomID:{}".format(self.roomID))
            else:
                signal = 0

                def payCallback(content):
                    nonlocal signal
                    try:
                        signal += 1
                        if signal == len(self.players_list):
                            callback(content)
                    except:
                        DEBUG_MSG("AA payCallback Failed")

                if self.player_num == 3:
                    utility.update_card_diamond(
                        self.players_list[0].mb.accountName, -card_cost,
                        -diamond_cost, payCallback,
                        "NingBoMJ RoomID:{}".format(self.roomID))
                    utility.update_card_diamond(
                        self.players_list[1].mb.accountName, -card_cost,
                        -diamond_cost, payCallback,
                        "NingBoMJ RoomID:{}".format(self.roomID))
                    utility.update_card_diamond(
                        self.players_list[2].mb.accountName, -card_cost,
                        -diamond_cost, payCallback,
                        "NingBoMJ RoomID:{}".format(self.roomID))
                else:
                    utility.update_card_diamond(
                        self.players_list[0].mb.accountName, -card_cost,
                        -diamond_cost, payCallback,
                        "NingBoMJ RoomID:{}".format(self.roomID))
                    utility.update_card_diamond(
                        self.players_list[1].mb.accountName, -card_cost,
                        -diamond_cost, payCallback,
                        "NingBoMJ RoomID:{}".format(self.roomID))
                    utility.update_card_diamond(
                        self.players_list[2].mb.accountName, -card_cost,
                        -diamond_cost, payCallback,
                        "NingBoMJ RoomID:{}".format(self.roomID))
                    utility.update_card_diamond(
                        self.players_list[3].mb.accountName, -card_cost,
                        -diamond_cost, payCallback,
                        "NingBoMJ RoomID:{}".format(self.roomID))
            return

        DEBUG_MSG("start Game: Room{0} - Round{1}".format(
            self.roomID,
            str(self.current_round) + '/' + str(self.game_round)))

        callback('{"card":99, "diamond":999}'.encode())
Exemplo n.º 22
0
    def startGame(self):
        """ 开始游戏 """
        self.op_record = []
        self.state = 1
        self.current_round += 1
        self.discardKingTileIdx = -2

        diceList = [[0, 0], [0, 0], [0, 0], [0, 0]]

        addDealNum = 0
        if self.current_round <= 1:  #首次选庄
            diceList = self.throwTheDice([0, 1, 2, 3])
            idx, num = self.getMaxDiceIdx(diceList)
            self.dealer_idx = idx
            if self.diceAddNum > 0 and num >= self.diceAddNum:
                addDealNum += 1
            elif self.isSameAdd > 0 and diceList[idx][0] == diceList[idx][1]:
                addDealNum += 1
        else:
            diceList = self.throwTheDice([self.dealer_idx])
            idx, num = self.getMaxDiceIdx(diceList)
            if self.dealer_idx != self.last_dealer_idx:
                if self.diceAddNum > 0 and num >= self.diceAddNum:
                    addDealNum += 1
                elif self.isSameAdd > 0 and diceList[idx][0] == diceList[idx][
                        1]:
                    addDealNum += 1

        #老庄
        self.setCurOldDealNum(addDealNum)
        DEBUG_MSG(
            "start game,curOldDealNum{0},dealer_idx{1},diceList{2}".format(
                self.curOldDealNum, self.dealer_idx, str(diceList)))

        # 仅仅在第1局扣房卡, 不然每局都会扣房卡
        def callback(content):
            content = content.decode()
            try:
                if content[0] != '{':
                    DEBUG_MSG(content)
                    self.dropRoom()
                    return
                for p in self.players_list:
                    p.reset()
                self.initTiles()
                self.deal()
                self.current_idx = self.dealer_idx

                for p in self.players_list:
                    if p and p.mb:
                        p.mb.startGame(self.dealer_idx, p.tiles, self.kingTile,
                                       diceList, self.curOldDealNum,
                                       self.game_round, self.roomMode)
                self.beginRound()
            except:
                DEBUG_MSG("consume failed!")

        if self.current_round == 1 and self.is_agent == 0:
            card_cost, diamond_cost = switch.calc_cost(self.roomMode,
                                                       self.game_round)
            if switch.DEBUG_BASE:
                callback('{"card":99, "diamond":999}'.encode())
            else:
                utility.update_card_diamond(
                    self.players_list[0].mb.accountName, -card_cost,
                    -diamond_cost, callback,
                    "XiaoShanMJ RoomID:{}".format(self.roomID))
            return

        DEBUG_MSG("start Game: Room{0} - Round{1}".format(
            self.roomID,
            str(self.current_round) + '/' + str(self.game_round)))

        callback('{"card":99, "diamond":999}'.encode())
Exemplo n.º 23
0
	def pay2StartGame(self):
		""" 开始游戏 """
		DEBUG_MSG("room:{},curround:{},game_mode:{},base_score:{},king_mode:{},begin_dealer_mul:{},win_mode:{},three_job:{},pong_useful:{},bao_tou:{},round_max_lose:{},game_max_lose:{},game_round:{},hand_prepare:{} pay2StartGame state:{}".format(self.roomID, self.current_round,
		self.game_mode, self.base_score, self.king_mode, self.begin_dealer_mul, self.win_mode, self.three_job,
		self.pong_useful, self.bao_tou, self.round_max_lose, self.game_max_lose, self.game_round, self.hand_prepare,
		self.state))

		if self.timeout_timer:
			self.cancel_timer(self.timeout_timer)
			self.timeout_timer = None

		self.state = const.ROOM_TRANSITION

		if self.current_round == 0:
			# 第一局备份原始座位
			self.origin_players_list = self.players_list[:]
			self.dealer_idx = 0

		# 仅仅在第1局扣房卡, 不然每局都会扣房卡
		if self.current_round == 0:
			if switch.DEBUG_BASE:
				self.paySuccessCbk()
				return

			card_cost, diamond_cost = switch.calc_cost(self.game_round, self.getCalCostNeed())
			if self.pay_mode == const.NORMAL_PAY_MODE:
				pay_account = self.origin_players_list[0].mb.accountName
				reason = "FourDeckCards RoomID:{}".format(self.roomID)

				def pay_callback(content):
					if self._check_pay_callback(content):
						self.paySuccessCbk()

				utility.update_card_diamond(pay_account, -card_cost, -diamond_cost, pay_callback, reason)
			elif self.pay_mode == const.CLUB_PAY_MODE:
				pay_account = self.club.owner['accountName']
				reason = "FourDeckCards Club:{} RoomID:{}".format(self.club.clubId, self.roomID)

				def pay_callback(content):
					if self._check_pay_callback(content):
						self.paySuccessCbk()

				utility.update_card_diamond(pay_account, -card_cost, -diamond_cost, pay_callback, reason)
			elif self.pay_mode == const.AGENT_PAY_MODE:
				# 开房的时候已经扣了房卡
				self.paySuccessCbk()
			elif self.pay_mode == const.AA_PAY_MODE:
				pay_accounts = [p.mb.accountName for p in self.players_list]
				if self.club:
					reason = "FourDeckCards Club:{} AA RoomID:{}".format(self.club.clubId, self.roomID)
				else:
					reason = "FourDeckCards AA RoomID:{}".format(self.roomID)

				def pay_callback(content):
					if self._check_aa_pay_callback(content):
						self.paySuccessCbk()

				utility.update_card_diamond_aa(pay_accounts, -card_cost, -diamond_cost, pay_callback, reason)
			else:
				ERROR_MSG("pay2StartGame Error: No this PayMode:{}".format(self.pay_mode))
				return
		else:
			self.paySuccessCbk()
Exemplo n.º 24
0
	def get_continue_list(self, callback, playing_players):
		# 如果时代开房需要检查代理的房卡
		# 如果时房主 需要检查房主放房卡
		# 如果时AA 需要检查所有人的房卡
		card_cost, diamond_cost = switch.calc_cost(self.game_round, self.getCalCostNeed())

		def _check_user_info(user_id, content):
			if self.club and not self.club.isMember(user_id):
				DEBUG_MSG("{0} userId:{1} get_continue_list callback error: not in club {2}".format(self.prefixLogStr, user_id, self.club.clubId))
				return False
			if content is None:
				DEBUG_MSG("{0} userId:{1} get_continue_list callback error: content is None".format(self.prefixLogStr, user_id))
				return False
			try:
				data = json.loads(content)
				if diamond_cost > data["diamond"] and card_cost > data["card"]:
					return False
			except:
				err, msg, stack = sys.exc_info()
				DEBUG_MSG("{0} _check_user_info callback error:{1} {4}, exc_info: {2} ,{3}".format(self.prefixLogStr, content, err, msg, user_id))
				return False
			return True

		def _user_info_callback(user_id, content):
			if _check_user_info(user_id, content):
				callback and callback([const.ROOM_CONTINUE] * self.player_num)
			else:
				callback and callback([const.ROOM_END] * self.player_num)

		if switch.DEBUG_BASE > 0:
			if self.pay_mode == const.CLUB_PAY_MODE:
				if self.club is None:
					callback and callback([const.ROOM_END] * self.player_num)
					return
			callback and callback([random.randint(0, 1) if i % 2 == 0 and i > 0 else 1 for i in range(self.player_num)])
		elif self.room_type == const.AGENT_ROOM and self.agent:
			# user_id = self.agent.userId
			# utility.get_user_info(self.agent.accountName, _user_info_callback)
			pass
		elif self.pay_mode == const.NORMAL_PAY_MODE:
			utility.get_user_info(self.players_list[0].mb.accountName, Functor(_user_info_callback, self.players_list[0].mb.userId))
		elif self.pay_mode == const.AA_PAY_MODE:
			count = len(playing_players)
			stats = 0
			result = [const.ROOM_END] * self.player_num
			for p in playing_players:
				result[p.idx] = const.ROOM_CONTINUE

			def _find_idx(user_id):
				for p in playing_players:
					if p.userId == user_id:
						return p.idx
				return -1

			def _check_callback_aa(roomId, user_id, content):
				nonlocal stats
				nonlocal result
				stats += 1
				if not _check_user_info(user_id, content):
					idx = _find_idx(user_id)
					if idx != -1:
						result[idx] = const.ROOM_END
				if count == stats:
					callback and callback(result)

			for p in playing_players:
				utility.get_user_info(p.mb.accountName, Functor(_check_callback_aa, self.roomID, p.userId))
		elif self.pay_mode == const.CLUB_PAY_MODE:
			if self.club is None:
				callback and callback([const.ROOM_END] * self.player_num)
			else:
				pay_account = self.club.owner['accountName']
				utility.get_user_info(pay_account, Functor(_user_info_callback, self.club.owner['userId']))
		else:
			ERROR_MSG("{} get_continue_list: not support {} {}".format(self.prefixLogStr, self.room_type, self.pay_mode))
			callback and callback([0] * self.player_num)