在pygame主循环中使用Twisted客户端?

6

我正在尝试使用pygame客户端运行twisted服务器:

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代码,客户端连接正常。我是使用reactor方法有误还是pygames代码结构有问题?任何帮助都将不胜感激。
所以我不知道pygames部分内部的循环是否会中断以再次调用reactor呢?

有什么问题?你的问题在哪里? - sloth
我会编辑以更详细地解释。 - tijko
1个回答

8

在使用Twisted时,您不应该编写自己的主循环(使用while),因为Twisted需要控制主循环,而Pygame足够灵活,不需要自己的循环。

您应该将主循环中的所有内容放入一个函数中,并通过调用reactor.CallLater()将其添加到Twisted反应器中进行调度。

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)

这样,您可以确保反应堆运行并可以处理网络事件。


以下是一个小型的工作示例,客户端只会呈现收到的最后一行:

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()

我应该在tick和main之后调用reactor.run()吗?我原以为需要启动它,否则会阻止main和tick的运行。因为如果没有它,pygame屏幕会启动然后退出,而有了它,pygame屏幕根本不会出现(所以main没有被调用)。 - tijko
1
只需调用 main() 一次(或者你调用来初始化客户端的任何代码)。重要的是,在调用 reactor.run() 之前,确保 reactor.callLater(0.1, tick) 只被调用一次。 - sloth
我还需要在main()调用之后运行reactor.ConnectTcp('192.168.1.2',6000, ChatClient())reactor.run吗?我已经尝试过了,但现在pygame事件没有响应? - tijko
3
twisted.internet.task.LoopingCallCooperator更符合你的需求。你需要在帧之间放一些实际的时间 - 如果没有返回一个DeferredCooperator会假设总有更多的工作要做,并且速度非常快。此外,LoopingCallwithCount,它允许你调整输入的幅度(例如,如果用户按下'上'键4帧,也许你想让他们移动4个像素)。 - Glyph
@BigYellowCactus 我希望我能再多给你十个赞,非常有帮助! - tijko
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接