我怎样才能让 pacman 在我停止按下特定键后继续移动?

How can I make pacman continue to move after I stopped pressing a specific key?

我希望主角继续按照我选择的特定方向移动,直到我按下另一个键。 这是我所做的代码:

for event in pygame.event.get():
    if event.type==pygame.KEYDOWN:
        if event.key==pygame.K_q:
            pygame.quit()
        elif event.key==pygame.K_w:
            dir="Up"
        elif event.key==pygame.K_s:
            dir="Down"
        elif event.key==pygame.K_d:
            dir="Right"

        if dir=="Up":
            if valid_move((ChY-45)//size, (ChX)//size):
                ChY-=15
        if dir=="Down":
            if valid_move((ChY+45)//size, (ChX)//size):
                ChY+=15
        if dir=="Right":
            if valid_move((ChY)//size, (ChX+45)//size):
                ChX+=15
        if dir=="Left":
            if valid_move((ChY)//size, (ChX-45)//size):
                ChX-=15

这是Indentation的事情。您必须在应用程序循环而不是事件循环中连续移动 Pacman:

# application loop
run = True
while run:

    # event loop 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key==pygame.K_q:
                run = False
            elif event.key==pygame.K_w:
                dir="Up"
            elif event.key==pygame.K_s:
                dir="Down"
            elif event.key==pygame.K_d:
                dir="Right"
            elif event.key==pygame.K_a:
                dir="Left"

    # INDENTATION
    #<--|

    if dir=="Up":
        if valid_move((ChY-45)//size, (ChX)//size):
            ChY-=15
    if dir=="Down":
        if valid_move((ChY+45)//size, (ChX)//size):
            ChY+=15
    if dir=="Right":
        if valid_move((ChY)//size, (ChX+45)//size):
            ChX+=15
    if dir=="Left":
        if valid_move((ChY)//size, (ChX-45)//size):
            ChX-=15

    # [...]