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
415 views
in Technique[技术] by (71.8m points)

python - Why does graphical window freeze after about 5 seconds?

Code is running correctly and as I expected but after 5 seconds the display for graphics freezes forever. It shows no error, nothing, just stops responding.

This is a program to simulate a movement of a large group of objects. They have to move randomly while aimless like Brownian motion. To make this I used Pygame to draw any object as a rectangle of random location, to move them I remove everything and draw them again with their location randomly changed by 1. I am using pygame to show graphics. Could you please also suggest a better solution for this problem?

import pygame, random, sys, time, numpy
from pygame.locals import *

black = (0,0,0)
white = (255,255,255)

clock = pygame.time.Clock()

class people():

    def __init__(self):

        screen = pygame.display.get_surface()

        self.x = random.randint(0, 800)
        self.y = random.randint(0, 600)

    def move(self):
        self.x += random.randint(-1, 1)
        self.y += random.randint(-1, 1)
        if self.x < 0:
            self.x = 0
        if self.x > 800:
            self.x = 800
        if self.y < 0:
            self.y = 0
        if self.y > 600:
            self.y = 600

    def place(x, y):
        screen = pygame.display.get_surface()
        pygame.draw.rect(screen, black, [x, y, 10, 10])

def main():
    # Initialise screen
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    pygame.display.set_caption('Test')

    peoples = []

    chosepopul = 1

    while chosepopul == 1:
        try:
            population = abs(int(input("How many people would you like to have")))
            chosepopul = 0
        except:
            print("Number, please")    

    for i in range(population):
        peoples.append(people())

    while True:

        screen.fill(white)

        for obj in peoples:

            people.place(obj.x, obj.y)

            people.move(obj)

        pygame.display.update()
        clock.tick(60)

if __name__ == '__main__':
    main()

pygame.quit()
quit()

Everything is working as I expected but freezing inevitably.

UPDATE: If I change input script to constant number, everything is working correctly. So the problem is somehow linked with user interface interactions.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The program stops because the input() blocks the program flow. No further PyGame updates or events are sent & processed. Basically everything comes to a halt, waiting for the user to type.

The best way around this is to write code such that the user does some PyGame on-screen input, rather than in the console. Maybe make a slider or spinner-control to select the number, or plus/minus buttons, whatever.

Alternatively, the program can still use console input in a thread which uses the post() function to send the result to the main PyGame event-loop thread.

I must admit, this answer is of academic interest only, since using the console to input along with a PyGame window is pretty ugly!

Anyway, here is some code. The main python window simply changes colour every 0.5 seconds, while the user can input text in the console with the standard python input() function. The code uses it's own Event enumerated type for posting messages, but these could also just be plain numbers.

This works, as per the OP, because the input() function is called inside a sub-thread of execution. This leaves the main thread free to continually process the PyGame event queue, and paint updates to the window. It's important to only have a single event queue/loop (for reasons beyond the scope of this answer), so the sub-thread "posts" events back to the main thread, rather than acting on the window/events itself.

import threading
import pygame
import enum

# Window size
WINDOW_WIDTH  = 200
WINDOW_HEIGHT = 200

DARK    = (  50, 50, 50 )
WHITE   = ( 255,255,255 )
RED     = ( 255, 55, 55 )
GREEN   = (   5,255, 55 )
BLUE    = (   5, 55,255 )


colour_cycle = [ DARK, WHITE, RED, GREEN, BLUE ]


class UserEvents( enum.IntEnum ):
    CLIENT_NUMBER = pygame.USEREVENT + 1
    CLIENT_QUIT   = pygame.USEREVENT + 2
    # ...



class ConsoleInputThread( threading.Thread ):
    """ A thread that handles user input on the console.
        Waits for user input, then posts messages
        to the main PyGame thread for processing """
    def __init__( self, prompt ):
        threading.Thread.__init__(self)
        self.daemon         = True # exit with parent
        self.done           = False
        self.prompt         = prompt

    def stop( self ):
        self.done = True

    def run( self ):
        """ Loops until the user hangs-up """
        while ( not self.done ):
            # Get some input from the user
            user_input = input( self.prompt ).strip()
            new_event = None
            if ( user_input == 'quit' ):
                new_event = pygame.event.Event( UserEvents.CLIENT_QUIT, { } )
            else:
                try:
                    user_input = int( user_input )
                    new_event = pygame.event.Event( UserEvents.CLIENT_NUMBER, { "value":user_input } )
                except:
                    print( "Syntax Error" )
            # If we received valid input post it to the main thread
            if ( new_event ):
                pygame.event.post( new_event )




###
### MAIN
###

# Create the window
pygame.init()
pygame.display.set_caption("Socket Messages")
SURFACE = pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE
WINDOW  = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), SURFACE )


# Start the console-input thread
input_thread = ConsoleInputThread( "How many people would you like to have: " )
input_thread.start()

# Main paint / update / event loop
done = False
clock = pygame.time.Clock()
colour_index = 0
while ( not done ):

    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True

        elif ( event.type == UserEvents.CLIENT_QUIT ):
            print("
CLIENT ASKED TO QUIT " )
            done = True

        elif ( event.type == UserEvents.CLIENT_NUMBER ):
            print( "
VALUE WAS INPUT: %d " % ( event.value, ) )


    WINDOW.fill( colour_cycle[colour_index] )
    # rotate the colours, just so the screen changes
    colour_index += 1
    if ( colour_index >= len( colour_cycle ) ):
        colour_index = 0

    pygame.display.flip()

    clock.tick_busy_loop(2)  # NOTE: 2 frames per second, no flashy-flashy

input_thread.stop()
pygame.quit()

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

1.4m articles

1.4m replys

5 comments

57.0k users

...