Home > Software engineering >  pygame - while loop makes pygame window freeze / how do I shoot the bullets out of the player?
pygame - while loop makes pygame window freeze / how do I shoot the bullets out of the player?

Time:10-24

so I was programming again this morning and I wanted to write that the player in my small game can shoot bullets. That worked fine but theres an issue: I wrote for the x and the y coordinates of the 'bullet spawner' player.x and player.y and I thought that the bullets would shoot from the player's position. but they don't. They shoot from the position, where the player was in the beginning of the game and the spawner doesn't move. So I tried to do this with a while loop and the bool isMoving, that only is True if the player moves:

...
isMoving = False
...
bullets = []
position = (player.x, player.y)
while isMoving:
   position = (player.x, player.y)
...
if keys[pygame.K_d] or keys[pygame.K_a] or keys[pygame.K_w] or keys[pygame.K_s] or keys[pygame.K_UP] or keys[pygame.K_DOWN] or keys[pygame.K_LEFT] or keys[pygame.K_RIGHT]:
    isMoving = True
else:
    isMoving = False

But if I run pygame now, the window just freezes. If I remove the while loop again, it works but it shoots from the player's first position again. Oh, and I get the error " while isMoving: UnboundLocalError: local variable 'isMoving' referenced before assignment " Any ideas how to fix that?

CodePudding user response:

Pygame should run in a main while loop which has all the main actions inside it. Try setting the position at the start, then inside the while loop check for pygame events that trigger the isMoving change. Nested while loops will cause issues with pygame. Use if functions inside the while loop instead of another while loop. For example,

position = (player.x, player.y) # initial position
while isRunning:
    isMoving = False
    # PyGame event interaction
    for event in pygame.event.get():
        # Exits loop
        if event.type == pygame.QUIT:
            isRunning = False
        # Check if key is pressed
        if event.type == pygame.KEYDOWN:
            keys = [pygame.K_a, pygame.K_w, pygame.K_s, pygame.K_d, pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]
            if event.key in keys:
                isMoving = True
        
    if isMoving:
        position = (player.x, player.y)
        # do other stuff
  • Related