TWISTED серверная позиция игрока - PullRequest
0 голосов
/ 25 июня 2018

В настоящее время я делаю многопользовательскую игру, я отправляю позиции пользователей X через InputStream и OutputStream ... Я получаю много запаздываний на приеме на стороне клиента. Вот код:

Первая проверка данных:

def dataReceived(self, data):
    self.inBuffer = self.inBuffer + data
    while(True):
        if (len(self.inBuffer) < 4):
            return;

        msgLen = unpack('!I', self.inBuffer[:4])[0]
        # checks whether we do have a message.type which is 4bytes long, thats we are only checking the first 4 bytes then comparing it to see where the message is valid.
        if (len(self.inBuffer) < msgLen):
            return;

        messageString = self.inBuffer[4:msgLen+4]
        #emptys the buffer out
        self.inBuffer = self.inBuffer[msgLen+4:]
        message = MessageReader(messageString)
        self.processMessage(message)
        if PLAYERS_CONNECTED >= 2:
            self.startMatch(PLAYERIDS_CONNECTED)

проверка типа сообщения:

def processMessage(self, message):
    messageId = message.readByte()
    if messageId == MESSAGE_PLAYER_CONNECTED:
        return self.playerConnected(message)
    if messageId == MESSAGE_START_MATCH:
        return self.startMatch(message)
    if messageId == MESSAGE_NOTIFY_READY:
        return self.notifyReady(message)
    if messageId == MESSAGE_MOVED_SELF:
        return self.movedSelf(message)
    if messageId == MESSAGE_YPOSITION:

обработка сообщения:

def movedSelf(self, message):
    posX = message.readInt()
    self.player.match.movedSelf(posX, self.player)

вторая часть:

def movedSelf(self, posX, player):
    for i in range(0, len(self.players)):
        matchPlayer = self.players[i]
        if matchPlayer != player:
            if (matchPlayer.protocol):
                index = 0
                for i in PLAYERIDS_CONNECTED:
                    if(i == player.playerId):
                        matchPlayer.protocol.sendPlayerMoved(index, posX)
                    index = index + 1
                print("Player moved %s " % (index))

затем отправка фактического сообщения:

def sendPlayerMoved(self, playerIndex, posX):
    message = MessageWriter()
    message.writeByte(MESSAGE_PLAYER_MOVED)
    message.writeInt(playerIndex)
    message.writeInt(posX)
    #self.log("Sent PLAYER_MOVED %d %d" % (playerIndex, posX))
    self.sendMessage(message)

актуальный конвертер сообщений

class MessageWriter:

def __init__(self):
    self.data = ""

def writeByte(self, value):
    self.data = self.data + pack('!B', value)

def writeInt(self, value):
    self.data = self.data + pack('!I', value)

def writeString(self, value):
    self.writeInt(len(value))
    packStr = '!%ds' % (len(value))
    self.data = self.data + pack(packStr, value)

Честно говоря, я не имею ни малейшего понятия, почему существует задержка, это может быть причиной того, что клиент, отправляющий позицию, постоянно отправляет переменные? какой будет лучший подход? Я исследовал, чтобы убедиться, что Twisted был асинхронным, и это так. Чтобы справиться, скажем, 50 игроков.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...