'How do I chain the movement of a snake's body?
I want to implement a snake game. The snake meanders through the playground. Every time when the snake eats some food, the length of the snake increase by one element. The elements of the snakes body follow its head like a chain.
snake_x, snake_y = WIDTH//2, HEIGHT//2
body = []
move_x, move_y = (1, 0)
food_x, food_y = new_food(body)
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT: move_x, move_y = (-1, 0)
elif event.key == pygame.K_RIGHT: move_x, move_y = (1, 0)
elif event.key == pygame.K_UP: move_x, move_y = (0, -1)
elif event.key == pygame.K_DOWN: move_x, move_y = (0, 1)
snake_x = (snake_x + move_x) % WIDTH
snake_y = (snake_y + move_y) % HEIGHT
if snake_x == food_x and snake_y == food_y:
food_x, food_y = new_food(body)
body.append((snake_x, snake_x))
# [...]
How do I accomplish, that the body parts follow the snake's head on its path, when the snake's head moves ahead?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
