Skip to content Skip to sidebar Skip to footer

Pygame Seems To "avoid" Loop

I am just getting started with Pygame and I am currently trying out some basic movement functions. I ran into a problem when trying to code my movement conditions into my object cl

Solution 1:

Your code has a race condition (to use the term really loosely).

The reason that your characters are not moving is that the first pygame.event.get call (when you are checking for a QUIT event) consumes all the KEYDOWN events that are on the queue. Then (unless you manage to press a key while the first loop is running), there are no KEYDOWN events in the queue when the first GameObject checks for events. Diddo for all other GameObjects.

You need to handler all pygame events in one loop. Example code:

class GameObject():
    #rest of class
    def move(self,event):
        if event.key == K_DOWN:
             screen.blit(background, self.pos, self.pos) #erases players by bliting bg 
             self.speed = 4
             self.move_south() #moves player
             self.speed = 0
        #repeat for all other directions
        screen.blit(self.image, self.pos) #draws player
#initialize objects
while True:
    for event in pygame.event.get():
         if event.type == QUIT: #handle quit event
         elif event.type == KEYDOWN:
            for o in objects:
                o.move(event)
    #do non-eventhandling tasks.

Post a Comment for "Pygame Seems To "avoid" Loop"