I am coding a snake game with pygame for Python 3.6 and wonder how I can make the snake move all the time, changing direction when buttons right, down, left and up pressed, like in the real snake game.

  • 1
    \$\begingroup\$ That's the core of the game; and the scope of this site does not cover providing full tutorials. We generally help you from where you are at. What have you done up to now, what have you tried, and with what are you stuck exactly? \$\endgroup\$ – Vaillancourt Mar 11 '17 at 13:39
  • 1
    \$\begingroup\$ Why did you tag this question with javascript? \$\endgroup\$ – Bálint Mar 11 '17 at 15:01

This is actually very simple. You don't want to zero out the velocity on frames but only change it.

speed = (0, 0)

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                speed = (-10, 0)
            if event.key == pygame.K_RIGHT:
                speed = (10, 0)
            if event.key == pygame.K_UP:
                speed = (0,-10)
            if event.key == pygame.K_DOWN:
                speed = (0, 10)

    snake.position.x += speed[0]
    snake.position.y += speed[1]

As you can see, the speed is changed when a button is pressed, and the speed stays constant until a new button is pressed. You can replace the 10s with a speed variable.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.