3

The way my current program works is that when the snake eats an apple, length gets added to the snake. But the way the length follows the snake is that it is always behind the head in a straight line. How would I make it follow the snake or follow the length in front of it like a normal snake game?

This is my code when I am adding length to the snake.

for i in range(lengthAmount):
        if i == 0:
            previousx = snakex - (30 * i)
            previousy = snakey
        if direction == "left":
            previousx = snakex + (30 * i)
            previousy = snakey
        elif direction == "right":  
            previousx = snakex - (30 * i)
            previousy = snakey
        elif direction == "up":
            previousx = snakex 
            previousy = snakey + (30 * i)
        elif direction == "down":
            previousx = snakex  
            previousy = snakey - (30 * i)

        pygame.draw.rect(window, (0, 175, 0), (previousx, previousy, 30, 30))
Lore
  • 103
  • 1
  • 6

1 Answers1

1

What you need is a list of snake body parts rather than a variable which knows the number of parts. The list contains the positions of the snake body, excluding the head. The has of the snake is stored in snakex and snakey. At the begin of the game the list of body parts is empty:

snake_body = []

Before you move the snake in the game loop, append the head position of to the snake to the body list.

while run:

    # [...]

    snake_body.append((snakex, snakey))

After that move the snake by changing the position. Validate if the snake has eat an apple and store the result to a state variable (eat_appel):

# move sanke
snakex += # [...]
snakey += # [...]
eat_appel = # True if snake eats an apple else False

The next step is to evaluate the length of the snake.
If the snake has eat an apple, then the length of the body has to be increase by 1. This is fulfilled, since we've add a part to the snakes body.
If the snake didn't eat at an apple, the length of the bod should be stay equal. In this case we've to remove the first part of the body list. An element of a list can be deleted by the del statement. Note, since we've add an element at the tail of the body list, but we've deleted the first element of the list, this cause that the body parts continuously change and keep "follow" the snakes head.

if not eat_appel:
    del snake_body[0]

When you draw the snake, then it is sufficient to draw rectangles at the stored positions:

# draw body
for body in snake_body:
    pygame.draw.rect(window, (0, 175, 0), (*body, 30, 30))
# draw head (in a different color)
pygame.draw.rect(window, (175, 175, 0), (snakex, snakey, 30, 30)) 
Rabbid76
  • 202,892
  • 27
  • 131
  • 174