2014-01-31 29 views
2

對Python的select.select文檔說:可以在select.select輸入列表中處理pygame事件嗎?

需要注意的是在Windows上,它僅適用於插座;在其他操作 系統上,它也適用於其他文件類型(特別是在Unix上, 它在管道上工作)。

我的團隊正在開發一個簡單的多人遊戲,使用pygame和sockets。 (我們不是使用Twisted或zeromq或任何類似的庫;這是唯一的約束)。

現在,爲遊戲設計;我們希望播放器在pygame屏幕中發生關鍵事件時將數據發送到服務器。客戶端/播放器端的套接字將被掛接到服務器,並監聽其他玩家端發生的變化。對於這個任務,我需要pygame和socket並行工作。我被推薦使用來自#python的幾個用戶的select模塊。

我可以這樣做:

inp = [self.sock, pygame.event.get] 
out = [self.server] 
i, o, x = select.select(inp, out, []) 

如果不是,應該用什麼方式去?

+0

這不起作用。 'select.select'需要文件描述符(或代表它們的整數)或在'fileno()'調用上返回描述符的對象。 'pygame.event.get'函數不會這樣做。爲什麼不使用非阻塞套接字? – sloth

+0

@DominicKexel我看到的非阻塞套接字的所有示例都與'select'有關。你能把我鏈接到相關文章嗎? – hjpotter92

回答

2

您可以使用線程執行此任務。是否需要處理系列服務器消息和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()""" 

如果沒有,你可以處理PygameHandlerSocketListener類的運行方法中的事件。

相關問題