Pygame window is not responding after interaction with it

I need to generate circles in random place every second. Now I have this code.

import pygame as pg
from threading import Thread
import random

pg.init()

WIDTH = 600
HEIGH = 600

sc = pg.display.set_mode((WIDTH, HEIGH))
pg.display.set_caption("Bacteria")

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)

sc.fill(BLACK)
pg.display.flip()

clock = pg.time.Clock()
FPS = 24

class FoodGen(Thread):
    def run(self):
        while 1:
            clock.tick(1)
            pg.draw.circle(sc, WHITE, (random.randint(10, WIDTH-10), random.randint(10, WIDTH-10)), 10)

class Main(Thread):
    def run(self):
        running = 1
        while running:
            clock.tick(FPS)
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    running = 0
                    break
            pg.display.flip()
        pg.quit()

t1 = FoodGen()
t1.start()
t2 = Main()
t2.start()

When is move mouse on the window it turns to waiting mode. The window is running until I try to move or close it. I've already red many information about this problem, but still can't fix it.

Upvotes: 2

Views: 44

Answers (1)

Rabbid76
Rabbid76

Reputation: 210890

See How to run multiple while loops at a time in Python. If you want to control something over time in Pygame you have two options:

  1. Use pygame.time.get_ticks() to measure time and and implement logic that controls the object depending on the time.

  2. Use the timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. Change object states when the event occurs.

e.g.:

import pygame as pg
import random

WIDTH, HEIGH = 600, 600
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
FPS = 24

pg.init()
sc = pg.display.set_mode((WIDTH, HEIGH))
pg.display.set_caption("Bacteria")
clock = pg.time.Clock()

timer_interval = 100 # 0.1 seconds
timer_event_id = pg.USEREVENT + 1
pg.time.set_timer(timer_event_id, timer_interval)

circles = []
running = 1
while running:
    clock.tick(FPS)
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = 0
        if event.type == timer_event_id:
            circles.append((random.randint(10, WIDTH-10), random.randint(10, WIDTH-10)))
            
    sc.fill(BLACK)     
    for center in circles:
        pg.draw.circle(sc, WHITE, center, 10)
    pg.display.flip()

pg.quit()

Upvotes: 1

Related Questions