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 Answer
\$\begingroup\$
\$\endgroup\$
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 10
s with a speed variable.
javascript
? \$\endgroup\$