Pygame Multithreading

2019-09-17 05:28发布

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条回答
对你真心纯属浪费
2楼-- · 2019-09-17 06:13

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.

查看更多
登录 后发表回答