我正在做一件简单的事情,并且一直在跟随YouTube上的教程。我已经能够使用WASD移动Banshee(我用了Halo中的图像作为我的飞船),但我必须反复点击按键,而我希望能够通过按住按键来移动它。以下是代码;
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1440,900))
pygame.display.update()
black=(0,0,0)
white=(255,255,255)
##loads the background
background = pygame.image.load("G:/starfield.jpg")
###loads sprite of a spaceship that will move.
banshee = pygame.image.load("G:/banshee.png")
x=1
y=1
while True:
gamexit = False
while not gamexit:
screen.blit(background,(0,0))
screen.blit(banshee,(x,y))
pygame.display.update()
# if it touches the sides of the window, the window closes
if x==1440 or x==0 or y==900 or y==0:
pygame.quit()
quit()
else:
for event in pygame.event.get():
pressed= pygame.key.get_pressed()
if event.type == pygame.QUIT:
gamexit=True
pygame.quit()
quit()
elif event.type==KEYDOWN:
# moves banshee up if w pressed, same for the other WASD keys below
if event.key==K_w:
y=y-5
x=x
screen.blit(banshee,(x,y))
pygame.display.update()
elif event.key==K_a:
x=x-5
y=y
screen.blit(banshee,(x,y))
pygame.display.update()
elif event.key==K_d:
x=x+5
y=y
screen.blit(banshee,(x,y))
pygame.display.update()
elif event.key==K_s:
y=y+5
x=x
screen.blit(banshee,(x,y))
pygame.display.update()
我已经尝试了许多不同的方法(在这里和其他地方),但效果很小。是否有什么方法可以在这里做到这一点,而无需重写大量代码?
谢谢。