Reputation: 43
Essentially I am using pygame. My gameloop has a lot of event handling and controls the position of the sprite and such.
Every 1 second snowball sprites will come in from the left of the screen, however when inputting this while loop in the game function, only that while loop is run, and the game just freezes because it is only waiting 1 second and updating the sprite, not focusing on the event handling or anything.
Even when using two different functions, when running the snowball function the program simply can't focus on both functions, and remains stuck on the snowball function.
I don't want to use anything complicated, just a simply elegant solution. I have looked at threading but it looks too complicated and i'm new to python.
Upvotes: 2
Views: 632
Reputation: 101072
Don't use the time
module.
Simply create an event, and tell pygame to put that event into the event queue every second (using the pygame.time.set_timer
function). Then you can handle it in your mainloop like every other event.
Here's a simple example. It is using custom events with pygame.time.set_timer
and a single main loop, without needing the time
module:
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((300, 300))
player, dir, size = pygame.Rect(100,100,20,20), (0, 0), 20
MOVEEVENT, APPLEEVENT, trail = pygame.USEREVENT+1, pygame.USEREVENT+2, []
pygame.time.set_timer(MOVEEVENT, 250)
pygame.time.set_timer(APPLEEVENT, 1000)
apples=[]
while True:
keys = pygame.key.get_pressed()
if keys[pygame.K_w]: dir = 0, -1
if keys[pygame.K_a]: dir = -1, 0
if keys[pygame.K_s]: dir = 0, 1
if keys[pygame.K_d]: dir = 1, 0
if pygame.event.get(pygame.QUIT): break
for e in pygame.event.get():
if e.type == MOVEEVENT: # this event happens every 250 ms
trail.append(player.inflate((-10, -10)))
trail = trail[-5:]
player.move_ip(*[v*size for v in dir])
if e.type == APPLEEVENT: # this event happens every 1000 ms
apples.append(pygame.rect.Rect(random.randint(0, 30) * 10, random.randint(0, 30) * 10, 10, 10))
screen.fill((0,120,0))
for t in trail:
pygame.draw.rect(screen, (255,0,0), t)
for a in apples:
pygame.draw.rect(screen, (0,255,100), a)
pygame.draw.rect(screen, (255,0,0), player)
pygame.display.flip()
This should give you an idea on how about resolving your issue. Don't use time.sleep
, it just blocks your loop.
Upvotes: 1