我是编码的新手,如果我显得愚蠢,我很抱歉。我为初学者购买了教程,并按照他在屏幕上的操作。此代码来自教程
`import pygame
pygame.init()
screen = pygame.display.set_mode((900,700))
finished = False
x = 380
y = 300
index = [0,1,2,3,4]
array = [0,1.2,4.5]
playerImage = pygame.image.load("Player.png")
playerImage.set_colorkey((0, 0, 0))
playerImage = pygame.transform.scale(playerImage, (90,120))
playerImage = playerImage.convert_alpha()
backgroundImage = pygame.image.load("ground.png")
backgroundImage = pygame.transform.scale(backgroundImage,(900,700))
screen.blit(backgroundImage,(0,0))
frame = pygame.time.Clock()
while finished == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
pressedKeys = pygame.key.get_pressed()
if pressedKeys[pygame.K_SPACE] == 1:
y -= 5
#rectOne = pygame.Rect(x,y,100,100)
color = (0,0,255)
black = (0,0,0)
screen.blit(backgroundImage,(0,0))
screen.blit(playerImage,(x,y))
#pygame.draw.rect(screen,color,rect)
pygame.display.flip()
frame.tick(30)`
我在视频中写的完全相同的代码。一切正常,除了我的播放器图像在按下按钮时按下,但没有任何反应。我完全按照他的解释做了。对他而言,它有效但不适合我。我的Python版本是“2.7.14”。 Pygame是“1.9.3”。感谢。
答案 0 :(得分:1)
这是Indentation的问题。连续移动必须在应用程序循环中,而不是在事件循环中。应用程序循环每帧运行一次,但事件循环每个事件只运行一次。按下键时会发生 KEYDOWN
事件,释放键时会发生 KEYUP
事件,但按住键时不会发生任何事件:
while finished == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
# INDENTATION
#<--|
pressedKeys = pygame.key.get_pressed()
if pressedKeys[pygame.K_SPACE] == 1:
y -= 5
#rectOne = pygame.Rect(x,y,100,100)
color = (0,0,255)
black = (0,0,0)
screen.blit(backgroundImage,(0,0))
screen.blit(playerImage,(x,y))
#pygame.draw.rect(screen,color,rect)
pygame.display.flip()
frame.tick(30)`
在您的代码中,缩进问题几乎不明显,因为缩进只有 1 个空格。您应该至少使用 2 个空格。