我正在开发一个程序,它将显示一个数组中的字母。如果用户按下向上箭头,这将在阵列中移动,如果用户按下向下箭头。 问题是,当我按下这些键中的任何一个时,字母移动得非常快,例如,如果我在A中,程序会移动到D或类似的东西。 这是我的代码
def HighScore(event):
pygame.init()
nameString=""
nameStringFinal=""
index=0
ABC=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
font=pygame.font.SysFont("Arial",30,True,False)
screen=pygame.display.set_mode((700, 700))
pygame.display.set_caption("New High Score" )
font=pygame.image.load("imagenes/paisaje.jpg").convert()
escape=False
while escape==False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.blit(fondo,(0,0))
show=fuente.render(nombreString,0,(0,0,0))
if event.type == pygame.KEYDOWN:
if control==True:
if event.key == pygame.K_UP:
if index==25:
index=25
else:
index=index+1
nameString=ABC[index]
elif event.key == pygame.K_DOWN:
if index==0:
index=0
else:
index=index-1
nameString=ABC[index]
elif event.key == pygame.K_RETURN:
nameStringFinal=nameStringFinal+nameString
screen.blit(despliegue,(200,200))
pygame.display.flip()
答案 0 :(得分:1)
您需要确保所有事件处理都正确缩进,因此它是for
循环的一部分
现在你的方式,最后的偶数将被反复处理,直到新的事件到来
例如:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if index==25:
index=25
else:
index=index+1
nameString=ABC[index]
elif event.key == pygame.K_DOWN:
if index==0:
index=0
else:
index=index-1
nameString=ABC[index]
elif event.key == pygame.K_RETURN:
nameStringFinal=nameStringFinal+nameString
screen.blit(fondo,(0,0))
show=fuente.render(nombreString,0,(0,0,0))
screen.blit(despliegue,(200,200))
在shell中,你可以看到for循环在空列表上的方式,只是将变量保留为前一个循环的值
>>> for i in [1,2,3]: # imagine this is the event list
... if i == 4:
... sys,exit()
...
>>> if i == 3:
... print "i==3"
...
i==3
>>> for i in []: # next time round the while loop, the event list is empty
... if i == 4:
... sys,exit()
...
>>> if i == 3: # but you're still processing this event again!
... print "i==3"
...
i==3