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()
我还是 Pygame 的新手。我怎样才能解决这个问题?
解决方案
它是缩进的问题。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
# [...]