Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

python - window in pygame freeze while waiting

I'm using pygame for my game and its online but the problem is that whenever the main loop of the game waits for the socket from the server its freezes. so unless you are doing your turn, the client wait for a socket from the server and its doing nothing while waiting and freeze until its get the socket and do its turn.

So I read few answers and solutions on this site and on some others and from what I understood after 5 seconds of doing nothing the OS thinks the window (locked itself)? so I created the thread keep_run but it does not make any change and the window still freeze while its not his turn.

Also to mention the server works with select library if its help in anyway because keep_run() is the only thread I used.

I did not include many lines in my code because there are too much but its a basic conclusion of the important stuff that maybe cause it?

import sockets
import pygame
from threading import Thread
def keep_run():
    clock = pygame.time.Clock()
    fps = 60
    while True:
        pygame.event.pump()
        clock.tick(fps)

pygame.init()
keep_running = Thread(target=keep_run)
keep_running.setDaemon(True)
keep_running.start()


while Game_run:

   #the main loop
   server_command = client_socket.recv(1024)
   if server_command == "move":
       # make your turn
       do_turn()
   elif server_command == "over":
       # finish the game
       finish_game()

image of the example: https://i.stack.imgur.com/b4Qx8.png

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You must call pygame.event.pump() (which is implicitly called by pygame.event.get(), pygame.event.clear(), pygame.event.poll(), pygame.event.wait() or pygame.event.peek()) regularly in the thread that initialized the video subsystem (Pygame is built on SDL, hence the link to SDL documentation).

I would also suggest that you don't use pygame.event.pump() and instead handle all events properly with pygame.event.get() or pygame.event.poll(). More about this here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...