Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continuous Movement in Pygame

Tags:

python

pygame

I am trying to make a ship on the surface move continuously on screen but it only accepts one key press at a time. I have tried all solutions online and they aren't working.

import pygame

#initialize the pygame module
pygame.init()
#set the window size 
screen =  pygame.display.set_mode((1280, 720))

#change the title of the window
pygame.display.set_caption("Space Invaders")

#change the icon of the window
icon = pygame.image.load("alien.png")
pygame.display.set_icon(icon)

#add the ship to the window
shipx = 608
shipy = 620

def ship(x, y):
    ship = pygame.image.load("spaceship.png").convert()
    screen.blit(ship, (x,y))
   
running = True
while running:
    #background screen color
    screen.fill((0, 0, 0))

    #render the ship on the window
    ship(shipx,shipy)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            shipx -= 30
        if keys[pygame.K_RIGHT]:
            shipx += 30

    pygame.display.update()

I'm still new to Pygame. How can I fix this?

like image 946
Ryan P Avatar asked Jan 29 '26 10:01

Ryan P


1 Answers

Its a matter of Indentation. pygame.key.get_pressed() has to be done in the application loop rather than the event loop. Note, the event loop is only executed when event occurs, but the application loop is executed in every frame:

running = True
while running:
    # [...]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        
    #<--| INDENTATION
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        shipx -= 30
    if keys[pygame.K_RIGHT]:
        shipx += 30

    # [...]
like image 189
Rabbid76 Avatar answered Jan 31 '26 22:01

Rabbid76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!