Search code examples
pythonpygamepacman

Pac-Man - keep pacman moving in a direction once one key is pressed and released


So, I want to code pac-man in python3 with the pygame module. However I do not know how to keep pac-man moving once a single key is pressed. The aim is to press for example the "up" key and pac-man will continue to move in that direction until he hits a boundary, even if I release the key. As of right now I have not coded these boundaries as I am prioritising the continuous movement of pac-man. I attempted to nest a while loop which should've worked but that obviously gave me a phat run-time error. Any ideas on how I can do this?

if keys[pygame.K_UP] and (pac.y - pac.radius) > 0:
        pac.y -= pac.speed
        pac.direction = "UP"
    elif keys[pygame.K_DOWN] and (pac.y + 2*(pac.radius) + pac.speed) < height:
        pac.y += pac.speed
        pac.direction = "DOWN"
    elif keys[pygame.K_LEFT] and (pac.x - pac.radius) > 0:
        pac.x -= pac.speed
        pac.direction = "LEFT"
        left = True
    elif keys[pygame.K_RIGHT] and (pac.x + 2*pac.radius + pac.speed) < width:
        pac.x += pac.speed
        pac.direction = "RIGHT"
        right = True

The expected result is to input a single direction and pac man will move in that direction by himself without needing to hold the key down. In reality what happens is I end up having to hold the key down so that pac man will move in the wanted direction.


Solution

  • Moving your pacman directly when the key is pressed is not going to work for your program. You should set pacman's speed or something here and apply that each frame in another function.

    def update():
        pac.y += pac.yspeed
        pac.x += pac.xspeed
    
    
    while True:
        clock.tick(60)
        if keys[pygame.K_UP] and (pac.y - pac.radius) > 0:
            pac.yspeed = 1
        elif keys[pygame.K_DOWN] and (pac.y + 2*(pac.radius) + pac.speed) < height:
            pac.yspeed = -1
        elif keys[pygame.K_LEFT] and (pac.x - pac.radius) > 0:
            pac.xspeed = -1
            left = True
        elif keys[pygame.K_RIGHT] and (pac.x + 2*pac.radius + pac.speed) < width:
            pac.xspeed = 1
            right = True
        if keys[pygame.K_ESC]:
            break
        update()
        # Do all your other stuff