0
\$\begingroup\$

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.

\$\endgroup\$
2
  • 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
    Commented Mar 11, 2017 at 13:39
  • 1
    \$\begingroup\$ Why did you tag this question with javascript? \$\endgroup\$
    – Bálint
    Commented Mar 11, 2017 at 15:01

1 Answer 1

1
\$\begingroup\$

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:
            sys.exit()
        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.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .