Pygame多线程 [英] Pygame Multithreading

查看:249
本文介绍了Pygame多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在pygame上运行的多人游戏.我在单独的线程中运行游戏/客户端/服务器,并且有一个简单的回显服务器.玩家每次广播消息时,其他所有玩家都会收到该消息.我遇到的问题是pygame有一个while(true)循环,该循环每10毫秒重新绘制一次屏幕.此循环导致游戏世界无法更新,因为它无法在循环之外执行任何操作.我尝试使用队列,以便在while循环中,它可以使队列出队并处理命令,但是似乎不起作用(q.put()不在队列中放置任何内容).

I have a multiplayer game that runs on pygame. I am running the game/client/server in separate threads and have a simple echo server. Each time a player broadcasts a message, every other player will get it. The problem I am experiencing is pygame has a while(true) loop that redraws the screen every 10 milliseconds. This loop causes the game world to not get updated since it cannot do anything outside the loop. I tried using a queue so that in the while loop, it can dequeue and process the commands however that doesnt seem to work (q.put() places nothing in the queue).

任何帮助表示赞赏!谢谢

Any help appreciated! Thanks

以下是该体系结构的摘要:

Here is a snippet of the architecture:

class Client(Thread, Observer):
    #waits for notifications from ClientSocket
    #starts the game loop
    #enqueue commands in the Game

class ClientSocket(Thread, Observable):
    #observes the socket and notifies the Client

class Server(Thread):
    #simply broadcasts commands to ClientSocket(s)

class Game(Thread):
    def __init__(self):
        self.q = queue.Queue()

    while True:
        #delay 10 ms
        #redraw
        #see if u need to process queue

推荐答案

我建议您仔细阅读Queue docs http://docs.python.org/2/library/queue.html 和线程文档 http://www.tutorialspoint. com/python/python_multithreading.htm ,我相信您将能够创建更好的多线程体系结构.

I suggest you to read carefully Queue docs http://docs.python.org/2/library/queue.html and threading docs http://docs.python.org/2/library/threading.html. Your decision to use while True: does not look very well. Please read about locks/semaphores/mutex/events and check these simple examples http://www.tutorialspoint.com/python/python_multithreading.htm and I am sure that you will be able to create better multithreading architecture.

这篇关于Pygame多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆