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

Question:

I want the main character to continue to move in the specific direction I chose until I press another key.
This is the code for what I did:

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
Asked By: qwertyui

||

Answers:

It is a matter of Indentation. You have to move Pacman continuously in the application loop instead of the event loop:

# 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

    # [...]
Answered By: Rabbid76
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.