Pygame Multithreading

[亡魂溺海] 提交于 2020-01-06 10:15:33

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/15755500/pygame-multithreading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!