Pygame 中的连续运动

Rya*_*n P 3 python pygame

我试图让表面上的一艘船在屏幕上连续移动,但它一次只接受一个按键。我已经在网上尝试了所有解决方案,但它们都不起作用。

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()
Run Code Online (Sandbox Code Playgroud)

我还是 Pygame 的新手。我怎样才能解决这个问题?

Rab*_*d76 5

它是缩进的问题pygame.key.get_pressed()必须在应用程序循环而不是事件循环中完成。注意,事件循环仅在事件发生时执行,而应用程序循环在每一帧中执行:

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

    # [...]
Run Code Online (Sandbox Code Playgroud)