def execute(userId, message, messageHandle): redis = gl.get_v("redis") if redis.exists(str(userId) + "_room"): roomNo = redis.get(str(userId) + "_room") betScoreAction = DouniuScoreAction() betScoreAction.ParseFromString(message) redis.lock("lockroom_" + str(roomNo)) try: room = redis.getobj("room_" + str(roomNo)) if room.gameStatus != GameStatus.PLAYING: gl.get_v("serverlogger").logger.info("下注失败状态不对") redis.unlock("lockroom_" + str(roomNo)) return seat = room.getSeatByUserId(userId) if seat is not None and -1 == seat.playScore and not seat.guanzhan and room.banker != userId: playScore = betScoreAction.score if playScore < room.betType * room.score: playScore = room.betType * room.score seat.playScore = playScore betScoreAction.score = playScore room.executeAction(userId, 2, betScoreAction, messageHandle) room.checkPlay(messageHandle) room.save(redis) except: print traceback.print_exc() redis.unlock("lockroom_" + str(roomNo))
def execute(userId, message, messageHandle): redis = gl.get_v("redis") if redis.exists(str(userId) + "_room"): roomNo = redis.get(str(userId) + "_room") grabAction = DouniuScoreAction() grabAction.ParseFromString(message) redis.lock("lockroom_" + str(roomNo)) try: room = redis.getobj("room_" + str(roomNo)) if room.gameStatus != GameStatus.GRABING: gl.get_v("serverlogger").logger.info("抢庄失败状态不对") redis.unlock("lockroom_" + str(roomNo)) return seat = room.getSeatByUserId(userId) if seat is not None and -1 == seat.grab and not seat.guanzhan: maxGrab = seat.score / 30 / room.betType / room.score if 0 == maxGrab: maxGrab = 1 elif maxGrab > grabAction.score: maxGrab = grabAction.score seat.grab = maxGrab room.executeAction(userId, 1, grabAction, messageHandle) room.checkGrab(messageHandle) room.save(redis) except: print traceback.print_exc() redis.unlock("lockroom_" + str(roomNo))
def send_to_coordinate(opcode, data): send_data = NetMessage() send_data.opcode = opcode send_data.data = data.SerializeToString() send_data.id = gl.get_v("uuid") gl.get_v("redis").publish("game-coordinate", send_data.SerializeToString())
def execute(room, messageHandle): if room.gameStatus == GameStatus.WAITING: banker = room.getWatchSeatByUserId(room.banker) getBankerScore = int(config.get("niuniu", "getBankerScore")) onlyPlayerBanker = config.get("niuniu", "onlyPlayerBanker") == "True" if (1 != room.banker and room.xiazhuang) or ( banker is not None and banker.shangzhuangScore < getBankerScore): messageHandle.broadcast_watch_to_gateway(LEAVE_BANKER, None, room) if onlyPlayerBanker and 0 == len( room.bankerList) and (1 == room.banker or room.xiazhuang or banker is None or room.bankerScore < getBankerScore): gl.get_v("serverlogger").logger.info('''开始游戏-无庄''') room.banker = 1 return room.seats = [] if len(room.watchSeats) < 6: room.seats.extend(room.watchSeats[0:len(room.watchSeats)]) else: room.seats.extend(room.watchSeats[0:6]) room.recUpdateScore(messageHandle, 0) room.bankerConfirm(messageHandle) if onlyPlayerBanker and 1 == room.banker: gl.get_v("serverlogger").logger.info('''开始游戏-无庄''') return dealcard_cmd.execute(room, messageHandle)
def execute(userId, message, messageHandle): redis = gl.get_v("redis") if redis.exists(str(userId) + "_room"): roomNo = redis.get(str(userId) + "_room") redis.lock("lockroom_" + str(roomNo)) try: room = redis.getobj("room_" + str(roomNo)) if room.gameStatus != GameStatus.PLAYING: gl.get_v("serverlogger").logger.info("看牌失败状态不对") redis.unlock("lockroom_" + str(roomNo)) return seat = room.getSeatByUserId(userId) if seat is not None and not seat.lookCard and not seat.end: seat.lookCard = True recExecuteAction = RecExecuteAction() recExecuteAction.playerId = seat.userId for s in room.seats: lookCardAction = JinhuaLookCardAction() if s.userId == userId: lookCardAction.cards.extend(s.initialCards) room.historyActions.append( recExecuteAction.SerializeToString()) recExecuteAction.data = lookCardAction.SerializeToString() messageHandle.send_to_gateway(EXECUTE_ACTION, recExecuteAction, s.userId) room.save(redis) except: print traceback.print_exc() redis.unlock("lockroom_" + str(roomNo))
def passRequest(self, request): request = request.decode('utf-8') if len(request.split('\r\n', 1)) != 2: return request_line, body = request.split('\r\n', 1) request_head = body.split('\r\n\r\n', 1)[0] # 头部信息 self.passRequestLine(request_line) self.passRequestHead(request_head) if self.method == 'POST': self.request_data = {} request_body = body.split('\r\n\r\n', 1)[1] parameters = request_body.split('&') # 每一行是一个字段 gl.get_v("serverlogger").logger.info("参数%s" % str(request_body)) for i in parameters: if i == '': continue key, val = i.split('=', 1) self.request_data[key] = val if self.method == 'GET': if self.url.find('?') != -1: # 含有参数的get self.request_data = {} req = self.url.split('?', 1)[1] s_url = self.url.split('?', 1)[0] parameters = req.split('&') gl.get_v("serverlogger").logger.info("参数%s" % str(req)) for i in parameters: key, val = i.split('=', 1) self.request_data[key] = val self.url = s_url self.do(self.url)
def sendToGame(self, uuid, opcode, data): message = NetMessage() message.opcode = opcode if data is not None: message.data = data.SerializeToString() gl.get_v("serverlogger").logger.info("发送%d给游戏服" % opcode) gl.get_v("redis").publish(uuid, message.SerializeToString())
def execute(room, messageHandle): try: if room.gameStatus == GameStatus.PLAYING: shuffleData = ShuffleData() conn = grpc.insecure_channel('127.0.0.1:50001') client = zhipai_pb2_grpc.ZhipaiStub(channel=conn) shuffleResult = client.shuffle(shuffleData) update_currency = [] for seat in room.seats: seat.initialCards = [] seat.initialCards.extend( shuffleResult.cardlist[3 * seat.seatNo - 3:3 * seat.seatNo]) seat.playScore = room.score seat.score -= int(0.5 * room.score) update_currency.append( UpdateCurrency(-int(0.5 * room.score), seat.userId, room.roomNo)) if 0 != len(update_currency): gl.get_v("update_currency").putall(update_currency) room.deskScore = room.score * len(room.seats) room.minScore = room.score gl.get_v("serverlogger").logger.info("发牌完成") except: print traceback.print_exc()
def handle(self, queue): while not self.__close: try: messages = queue.getall(30, True, 20) for message in messages: s = GateWayMessage() s.ParseFromString(message) netMessage = NetMessage() netMessage.ParseFromString(s.data) gl.get_v("serverlogger").logger.info('''收到%d消息%d''' % (s.userId, netMessage.opcode)) self.__lock.acquire() if s.userId not in self.__user_queue: messagequeue = TestQueue() messagehandle = UserMessageHandle(s.userId, self) threading.Thread(target=UserMessageHandle.handle, args=(messagehandle, messagequeue,), name='handle').start() # 线程对象. self.__user_queue[s.userId] = messagequeue self.__user_queue[s.userId].put(netMessage) self.__lock.release() except Queue.Empty: gl.get_v("serverlogger").logger.info("Received timeout") except: print traceback.print_exc()
def changeServerState(self, uuid, state): for g in gl.get_v("games"): if g.uuid == uuid: g.state = state self.sendToGame(uuid, CHANGE_SERVICE_STATE, None) if g.state == EXITING: gl.get_v("games").remove(g) break
def unlock(self, key): """ : 解锁 :param key: :return: """ gl.get_v("serverlogger").logger.info("解锁%s" % key) self.__redis.delete(key)
def execute(userId, message, messageHandle): redis = gl.get_v("redis") betScoreAction = BaiRenBetScoreAction() betScoreAction.ParseFromString(message) if redis.exists(str(userId) + "_room"): roomNo = redis.get(str(userId) + "_room") gl.get_v("play-handle")[str(roomNo)].queue.put( PlayScore(userId, betScoreAction))
def handle(self, queue): while not self.__close: try: details = queue.getall(20, True, 20) data_game_details.create_game_details(details) except Empty: gl.get_v("serverlogger").logger.info("Received timeout") except: print traceback.print_exc()
def send_to_gateway(self, opcode, data): send_data = NetMessage() send_data.opcode = opcode send_data.data = data.SerializeToString() s = GateWayMessage() s.userId = self.__userId s.data = send_data.SerializeToString() gl.get_v("redis").publish("server-gateway", s.SerializeToString()) gl.get_v("serverlogger").logger.info("发送%d给%s" % (opcode, self.__userId))
def handle(self, queue): while not self.__close: try: updates = queue.getall(20, True, 20) data_account.update_currencys(updates) data_gold.create_golds(1, updates) except Empty: gl.get_v("serverlogger").logger.info("Received timeout") except: print traceback.print_exc()
def relSend(self): while not self.__close: try: ss = self.sendQueue.getall(20, True, 20) for s in ss: gl.get_v("redis").publish("server-gateway", s) except Queue.Empty: gl.get_v("serverlogger").logger.info("Received timeout") except: print traceback.print_exc()
def tcp_link(sock, addr): gl.get_v("serverlogger").logger.info( 'Accept new connection from %s:%s...' % addr) request = sock.recv(1024) http_req = HttpRequest() try: http_req.passRequest(request) except: print traceback.print_exc() sock.send(http_req.getResponse().encode('utf-8')) sock.close()
def readBytes(self, conn, length): result = bytes() while length != 0: result1 = conn.recv(length) if result1: result += result1 length -= len(result1) else: gl.get_v("serverlogger").logger.info("client close") break return result
def sendToGame(self, uuid, opcode, data): message = NetMessage() message.opcode = opcode if data is not None: message.data = data s = GateWayMessage() s.userId = self.__userId s.data = message.SerializeToString() gl.get_v("serverlogger").logger.info("%d发送%d给游戏服" % (self.__userId, opcode)) gl.get_v("redis").publish(uuid.encode("utf-8"), s.SerializeToString())
def execute(room, messageHandle): try: if room.gameStatus == GameStatus.WAITING: room.startDate = int(time.time()) room.executeAsk(messageHandle, room.banker, 1) room.gameStatus = GameStatus.PLAYING threading.Thread(target=selnum_timeout.execute, args=(room.roomNo, room.gameCount, messageHandle,), name='selnum_timeout').start() # 线程对象. gl.get_v("serverlogger").logger.info("开始下注") except: print traceback.print_exc()
def send_to_gateway(self, opcode, data, userId=None): self.send_data.Clear() self.send_data.opcode = opcode if data is not None: self.send_data.data = data.SerializeToString() if userId is None: self.s.userId = self.__userId else: self.s.userId = userId self.s.data = self.send_data.SerializeToString() self.__server_receive.sendQueue.put(self.s.SerializeToString()) gl.get_v("serverlogger").logger.info( "发送%d给%s" % (opcode, self.__userId if userId is None else userId))
def broadcast_watch_to_gateway(self, opcode, data, room): gl.get_v("serverlogger").logger.info("发送之前") self.get_send_data(opcode, data) datas = [] for s in room.watchSeats: if s.userId is None: self.s.userId = self.__userId else: self.s.userId = s.userId self.s.data = self.send_data.SerializeToString() datas.append(self.s.SerializeToString()) self.__server_receive.sendQueue.putall(datas) gl.get_v("serverlogger").logger.info("发送之后")
def lock(self, key): """ : 加锁 :param key: :return: """ t = time.time() while True: if self.__redis.setnx(key, time.strftime("%Y%m%d%H%M%S", time.localtime())) == 1: self.__redis.expire(key, 5) gl.get_v("serverlogger").logger.info("加锁成功%s" % key) return True time.sleep(random.randint(1, 5) / 1000.0)
def execute(userId, message, messageHandle): redis = gl.get_v("redis") if redis.exists(str(userId) + "_room"): roomNo = redis.get(str(userId) + "_room") jinhuaCompare = JinhuaCompare() jinhuaCompare.ParseFromString(message) redis.lock("lockroom_" + str(roomNo)) try: room = redis.getobj("room_" + str(roomNo)) if room.gameStatus != GameStatus.PLAYING: gl.get_v("serverlogger").logger.info("比牌失败状态不对") redis.unlock("lockroom_" + str(roomNo)) return seat = room.getSeatByUserId(userId) if seat is not None and seat.seatNo == room.operationSeat and not seat.end: compareSeat = room.getSeatByUserId(jinhuaCompare.compareId) if compareSeat is not None and compareSeat != seat and not compareSeat.end: compareScore = room.minScore if seat.lookCard: compareScore *= 2 if compareScore <= seat.score - seat.playScore: seat.playScore += compareScore room.deskScore += compareScore seat.canLookUser.append(compareSeat.userId) compareSeat.canLookUser.append(seat.userId) settleResult = room.settle(seat, compareSeat) if settleResult is not None: jinhuaCompare.score = compareScore if settleResult.userSettleResule[0].win > 0: jinhuaCompare.win = True compareSeat.end = True else: jinhuaCompare.win = False seat.end = True room.executeAction(seat.userId, 3, jinhuaCompare, messageHandle) if not room.checkOver(messageHandle): room.changeOperation() room.executeRound(messageHandle, 0) seat.round += 1 room.checkRound(messageHandle) room.save(redis) else: gl.get_v("serverlogger").logger.info("比牌失败分数不够") except: print traceback.print_exc() redis.unlock("lockroom_" + str(roomNo))
def execute(room, messageHandle): try: if room.gameStatus == GameStatus.WAITING: shuffleData = ShuffleData() conn = grpc.insecure_channel('127.0.0.1:50002') client = zhipai_pb2_grpc.ZhipaiStub(channel=conn) shuffleResult = client.shuffle(shuffleData) update_currency = [] for seat in room.seats: seat.initialCards = [] seat.initialCards.extend( shuffleResult.cardlist[5 * seat.seatNo - 5:5 * seat.seatNo]) seat.score -= int(0.5 * room.score) update_currency.append( UpdateCurrency(-int(0.5 * room.score), seat.userId, room.roomNo)) if 0 != len(update_currency): gl.get_v("update_currency").putall(update_currency) gl.get_v("serverlogger").logger.info("发牌完成") executeAction = RecExecuteAction() if room.gameStatus == GameStatus.PLAYING: for s in room.seats: dealCardAction = DouniuCardAction() if 0 != len(s.initialCards): dealCardAction.cards.append(s.initialCards[4]) else: dealCardAction.cards.append(0) executeAction.data = dealCardAction.SerializeToString() messageHandle.send_to_gateway(EXECUTE_ACTION, executeAction, s.userId) room.gameStatus = GameStatus.OPENING room.executeAsk(messageHandle, 0, 3) else: for s in room.seats: dealCardAction = DouniuCardAction() if 0 != len(s.initialCards): dealCardAction.cards.extend(s.initialCards[0:4]) else: dealCardAction.cards.extend([0, 0, 0, 0]) executeAction.data = dealCardAction.SerializeToString() messageHandle.send_to_gateway(EXECUTE_ACTION, executeAction, s.userId) room.gameStatus = GameStatus.GRABING room.executeAsk(messageHandle, 0, 1) room.historyActions.append(executeAction.SerializeToString()) except: print traceback.print_exc()
def handle(self, queue): while True: try: messages = queue.getall(20, True, 20) for message in messages: s = GateWayMessage() s.userId = self.__userId s.data = message.SerializeToString() gl.get_v("redis").publish("gateway-coordinate", s.SerializeToString()) except Empty: print("messagehandle received timeout") if self.__close: break except: print traceback.print_exc()
def execute(userId, message, messageHandle): redis = gl.get_v("redis") if redis.exists(str(userId) + "_room"): roomNo = redis.get(str(userId) + "_room") gameid = redis.get(str(roomNo) + "_gameId") if 1 != gameid: return redis.lock("lockroom_" + str(roomNo)) try: room = redis.getobj("room_" + str(roomNo)) seat = room.getSeatByUserId(userId) if seat is not None: recReEnterGame = RecReEnterGame() recReEnterGame.gameState = room.gameStatus recReEnterGame.state = True recReEnterGame.curPlayCount = room.gameCount messageHandle.send_to_gateway(REENTER_GAME, recReEnterGame) room.recUpdateGameInfo(messageHandle) room.recUpdateScore(messageHandle, 0) if room.gameStatus != GameStatus.WAITING: room.recReEnterGameInfo(messageHandle, userId) except: print traceback.print_exc() redis.unlock("lockroom_" + str(roomNo))
def execute(userId, message, messageHandle): redis = gl.get_v("redis") if redis.exists(str(userId) + "_room"): roomNo = redis.get(str(userId) + "_room") score = BaiRenScore() score.ParseFromString(message.data) onlyPlayerBanker = config.get("tuitongzi", "onlyPlayerBanker") == "True" redis.lock("lockroom_" + str(roomNo)) try: room = redis.getobj("room_" + str(roomNo)) seat = room.getWatchSeatByUserId(userId) if seat is None or room.banker == userId or userId in room.bankerList: redis.unlock("lockroom_" + str(roomNo)) return if 1 == len(score.score): seat.shangzhuangScore = score.score[0] room.bankerList.append(userId) room.updateBankerList(messageHandle, 0) if onlyPlayerBanker and room.gameStatus == GameStatus.WAITING and 1 == room.banker: gamestart_cmd.execute(room, messageHandle) room.save(redis) except: print traceback.print_exc() redis.unlock("lockroom_" + str(roomNo))
def execute(userId, message, messageHandle): redis = gl.get_v("redis") if redis.exists(str(userId) + "_room"): roomNo = redis.get(str(userId) + "_room") account = data_account.query_account_by_id(None, userId) if account is not None: redis.lock("lockroom_" + str(roomNo)) try: room = redis.getobj("room_" + str(roomNo)) seat = room.getWatchSeatByUserId(userId) inseat = False if seat is not None: seat.score = int(account.gold.quantize(Decimal('0'))) seat = room.getSeatByUserId(userId) if seat is not None: inseat = True seat.score = int(account.gold.quantize(Decimal('0'))) room.sendBetScore(messageHandle) room.save(redis) room.recUpdateScore(messageHandle, userId) if inseat: room.recUpdateScore(messageHandle, 0) except: print traceback.print_exc() redis.unlock("lockroom_" + str(roomNo))
def exit(self, userId, messageHandle): seat = self.getWatchSeatByUserId(userId) if seat is not None: if seat.playScore != 0 or (self.banker == seat.userId and self.started): return if userId == self.banker: self.xiazhuang = True inseat = False while seat is not None: self.watchSeats.remove(seat) seat = self.getWatchSeatByUserId(userId) seat = self.getSeatByUserId(userId) while seat is not None: inseat = True self.seats.remove(seat) seat = self.getSeatByUserId(userId) if userId in self.bankerList: self.bankerList.remove(userId) self.updateBankerList(messageHandle, 0) redis = gl.get_v("redis") redis.delobj(str(userId) + "_room") userExit = UserExit() userExit.playerId = userId from game.niuniu.server.server import Server Server.send_to_coordinate(EXIT_GAME, userExit) if inseat: self.recUpdateScore(messageHandle, 0) self.updateWatchSize(messageHandle, 0) if 0 == len(self.watchSeats): roomover_cmd.execute(self, messageHandle)