6

私はpygame-clientsでツイストサーバーを実行しようとしています:

class ChatClientProtocol(LineReceiver):
    def lineReceived(self,line):
        print (line)

class ChatClient(ClientFactory):
    def __init__(self):
        self.protocol = ChatClientProtocol

def main():
    flag = 0
    default_screen()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
               return
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                pos = pygame.mouse.get_pos()
                # some rect.collidepoint(pos) rest of loop... 

そして、ここにサーバーがあります:

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class Chat(LineReceiver):
    def __init__(self, users, players):
        self.users = users
        self.name = None
        self.players = players

    def connectionMade(self):
        new = 'player_' + str(len(self.players) + 1)
        self.players.append(new)
        self.sendLine(str(self.players,))

class ChatFactory(Factory):
    def __init__(self):
        self.users = {} #maps instances to clients 
        self.players = []

    def buildProtocol(self, addr):
        return Chat(self.users,self.players)


reactor.listenTCP(6000, ChatFactory())
reactor.run()

私は、reactor.CallLater() メソッドと pygames コードを使用せずにクライアント コードを使用してこのサーバーを実行しています。クライアントは正常に接続します。リアクター メソッドを間違って使用していますか、それとも pygames コードに構造的に問題がありますか? どんな助けでも大歓迎です。

だから、pygamesビット内のループが壊れてリアクターを再度呼び出すかどうかはわかりませんか?

4

1 に答える 1

8

twisted を使用するときは、独自のメイン ループ ( を使用) を記述しないでください。whiletwisted はメイン ループを制御する必要があり、pygame は気にしないほど柔軟です (独自のループは必要ありません)。

メインループ内にあるすべてのものを関数に入れ、呼び出してねじれたリアクターでそれをスケジュールする必要がありますreactor.CallLater()

def main():
    flag = 0
    default_screen()
    reactor.callLater(0.1, tick)

def tick():
   for event in pygame.event.get():
        if event.type == pygame.QUIT:
            reactor.stop() # just stop somehow
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            reactor.stop() # just stop somehow
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            pos = pygame.mouse.get_pos()
            # some stuff
   reactor.callLater(0.1, tick)

このようにして、reactor が確実に実行され、ネットワーク イベントを処理できるようにします。


受信した最後の行をレンダリングするだけのクライアントの小さな動作例を次に示します。

from twisted.internet import reactor
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineReceiver

import pygame

class ChatClientProtocol(LineReceiver):

    def __init__(self, recv):
        self.recv = recv

    def lineReceived(self,line):
        self.recv(line)

class ChatClient(ClientFactory):
    def __init__(self, recv):
        self.protocol = ChatClientProtocol
        self.recv = recv

    def buildProtocol(self, addr):
        return ChatClientProtocol(self.recv)

class Client(object):

    def __init__(self):
        self.line = 'no message'
        pygame.init()
        self.screen = pygame.display.set_mode((200, 200))
        reactor.callLater(0.1, self.tick)

    def new_line(self, line):
        self.line = line

    def tick(self):
        self.screen.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                reactor.stop() # just stop somehow
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                reactor.stop() # just stop somehow
        self.screen.blit(pygame.font.SysFont('mono', 12, bold=True).render(self.line, True, (0, 255, 0)), (20,20))
        pygame.display.flip()
        reactor.callLater(0.1, self.tick)

if __name__ == '__main__':
    c = Client()
    reactor.connectTCP('127.0.0.1',6000, ChatClient(c.new_line))    
    reactor.run()

Glyph が提案したように、を使用した簡単な例を次に示しLoopingCallます (上記と同じであるため、プロトコル/ファクトリ クラスを省略しました)。

from twisted.internet.task import LoopingCall

class Client(object):

    def __init__(self):
        self.line = 'no message'
        pygame.init()
        self.screen = pygame.display.set_mode((200, 200))

    def new_line(self, line):
        self.line = line

    def tick(self):
        self.screen.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                reactor.stop() # just stop somehow
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                reactor.stop() # just stop somehow
        self.screen.blit(pygame.font.SysFont('mono', 12, bold=True).render(self.line, True, (0, 255, 0)), (20,20))
        pygame.display.flip()

if __name__ == '__main__':
    c = Client()

    lc = LoopingCall(c.tick)
    lc.start(0.1)
    reactor.connectTCP('127.0.0.1',6000, ChatClient(c.new_line))    
    reactor.run()
于 2012-09-12T06:25:04.660 に答える