0

I have the following code to demonstrate my problem:

import pygame
import random
import time

def randPoint(w,h):
    p = int(random.random()*w),int(random.random()*h)
    return p


width=1000
height=1000
screenColor=(0,0,0)
lineColor=(255,255,255)
pygame.init()
screen=pygame.display.set_mode((width,height))
count = 0
while True:
    screen.fill(screenColor)
    start = randPoint(width,height)
    end = randPoint(width,height)
    pygame.draw.line(screen, (255, 255, 255), start, end)
    pygame.display.flip()
    print(count)
    count += 1
    time.sleep(0.05)

After about 100 frames the pygame window freezes although the console continues to print new frame counts. What am I missing here?

kpie
  • 9,588
  • 5
  • 28
  • 50

2 Answers2

0

You'll need to call the pygame.event.get() method within the while loop:

while True:
    pygame.event.get()
    screen.fill(screenColor)
    start = randPoint(width,height)
    end = randPoint(width,height)
    pygame.draw.line(screen, (255, 255, 255), start, end)
    pygame.display.flip()
    print(count)
    count += 1
    time.sleep(0.05)

The above stops the program from freezing, but if you want the X button to work on the window, allowing it to close upon command, simply add this for loop:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
Red
  • 26,798
  • 7
  • 36
  • 58
0

You have to handle the events in the application loop. See pygame.event.get() respectively pygame.event.pump():

For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.

If you don't handle the events, the application stops responding.

clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.fill(screenColor)
    start = randPoint(width,height)
    end = randPoint(width,height)
    pygame.draw.line(screen, (255, 255, 255), start, end)
    pygame.display.flip()
    print(count)
    count += 1
    clock.tick(20)

The typical PyGame application loop has to:

Rabbid76
  • 202,892
  • 27
  • 131
  • 174