python 的文档select.select说:
Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes).
我的团队正在使用 pygame 和 sockets 开发一个简单的多人游戏. (我们没有使用 Twisted 或 zeromq 或任何类似的库;这是唯一的限制)。
现在,对于游戏设计;我们希望玩家在 pygame 屏幕中发生按键事件时向服务器发送数据。客户端/玩家端的套接字将 Hook 到服务器并监听其他玩家端发生的变化。对于这个任务,我需要 pygame 和 socket 并行工作。我被推荐使用来自 #python 上多个用户的 select 模块。
我可以做类似的事情吗:
inp = [self.sock, pygame.event.get]
out = [self.server]
i, o, x = select.select( inp, out, [] )
如果没有,应该怎么走?
请您参考如下方法:
您可以使用线程来完成这项任务。是否有必要串联(不是同时)处理服务器消息和pygame事件?如果是这样,您可以这样做:
class SocketListener(threading.Thread):
def __init__(self, sock, queue):
threading.Thread.__init__(self)
self.daemon = True
self.socket = sock
self.queue = queue
def run(self):
while True:
msg = self.socket.recv()
self.queue.put(msg)
class PygameHandler(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
self.daemon = True
def run(self):
while True:
self.queue.put(pygame.event.wait())
queue = Queue.Queue()
PygameHandler(queue).start()
SocketListener(queue).start()
while True:
event = queue.get()
"""Process the event()"""
如果没有,您可以在 PygameHandler 和 SocketListener 类的运行方法中处理事件。
