Python Forum
how to add segments to the snake body
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to add segments to the snake body
#1
Hi so I don't really understand how to add a segment to the correct position after the snake has eaten the fruit.
Can someone assist me with this? note: look in the conditional for if the snake has made contact with the fruit. I already have a concept for loop there.

import pygame
import time
import random
pygame.font.init()

# global variables
game = True
width, height = 500, 500
x, y = 20, 30
x2, y2 = 240, 250
lives = 3
answer = "yes"

segments = []

# setting up the font object
font = pygame.font.SysFont("comicsans", 40)
lose = font.render("You lost!", 1, (255,255,255), (250,250))
lose_width = lose.get_width()

# setting up screen
WIN = pygame.display.set_mode((500,500))
pygame.display.set_caption("Snake by Sam")

# load the background
BG = pygame.image.load("snake.png")
BG_resize = pygame.transform.scale(BG, (width, height))
WIN.blit(BG_resize,(0,0))
WIN.blit(font.render(f"Lives: {str(lives)}", 0 , (255,255,255)), (10,5))

# draw square on screen
snake = pygame.draw.rect(WIN, (255,0,0), (x,y,20,20))
key = None

# draw fruit(circle), setup
fruit = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))

def rand():
    global x2, y2
    x2 = random.randint(0, 490)
    y2 = random.randint(0, 490)

def move():
    global key
    global snake
    global x
    global y
    global fruit
    if answer == "yes" or "y" or "Yes":
        WIN.blit(font.render(f"Lives: {str(lives)}", 0 , (255,255,255)), (10,5))
        snake = pygame.draw.rect(WIN, (255,0,0), (x,y,20,20))
        fruit = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))

    if key == "d":        
        x = snake.left
        time.sleep(0.02)
        x = x + 10
        WIN.blit(BG_resize,(0,0))
        WIN.blit(font.render(f"Lives: {str(lives)}", 0 , (255,255,255)), (10,5))

        snake = pygame.draw.rect(WIN, (255,0,0), (x,y,20,20))
        fruit = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))

    if key == "s":        
        y = snake.top
        time.sleep(0.02)
        y = y + 10
        WIN.blit(BG_resize,(0,0))
        WIN.blit(font.render(f"Lives: {str(lives)}", 0 , (255,255,255)), (10,5))

        snake = pygame.draw.rect(WIN, (255,0,0), (x,y,20,20))
        fruit = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))
    if key == "w":        
        y = snake.top
        time.sleep(0.02)
        y = y - 10
        WIN.blit(BG_resize,(0,0))
        WIN.blit(font.render(f"Lives: {str(lives)}", 0 , (255,255,255)), (10,5))

        snake = pygame.draw.rect(WIN, (255,0,0), (x,y,20,20))
        fruit = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))

    if key == "a":        
        x = snake.left
        time.sleep(0.02)
        x = x - 10
        WIN.blit(BG_resize,(0,0))
        WIN.blit(font.render(f"Lives: {str(lives)}", 0 , (255,255,255)), (10,5))

        snake = pygame.draw.rect(WIN, (255,0,0), (x,y,20,20))
        fruit = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))

# mainloop
while game:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_d:
                WIN.blit(BG_resize,(0,0))
                key = "d"
            if event.key == pygame.K_w:
                WIN.blit(BG_resize,(0,0))
                key = "w"
            if event.key == pygame.K_s:
                WIN.blit(BG_resize,(0,0))
                key = "s"
            if event.key == pygame.K_a:
                WIN.blit(BG_resize,(0,0))
                key = "a"
    move()

    # border control
    if snake.left > 490:
        WIN.blit(BG_resize,(0,0))
        snake = pygame.draw.rect(WIN, (255,0,0), (250,250,20,20))
        fruit = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))
        x,y = 250, 250
        key = None
        lives -= 1
    if snake.left == 0:
        WIN.blit(BG_resize,(0,0))
        snake = pygame.draw.rect(WIN, (255,0,0), (250,250,20,20))
        fruit = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))
        x,y = 250, 250
        key = None
        lives -= 1
    if snake.top > 490:
        WIN.blit(BG_resize,(0,0))
        snake = pygame.draw.rect(WIN, (255,0,0), (250,250,20,20))
        fruit = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))
        x,y = 250, 250
        key = None
        lives -= 1
    if snake.top == 0:
        WIN.blit(BG_resize,(0,0))
        snake = pygame.draw.rect(WIN, (255,0,0), (250,250,20,20))
        fruit = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))
        x,y = 250, 250
        key = None
        lives -= 1

    # check if the snake has made contact with the fruit.   
    if snake.left < fruit.left + 20 and snake.left > fruit.left - 20 and snake.top < fruit.top + 25 and snake.top > fruit.top - 25: 
        WIN.blit(BG_resize,(0,0))
        WIN.blit(font.render(f"Lives: {str(lives)}", 0 , (255,255,255)), (10,5))        
        rand()
        fruit = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))
        # add a segment
        new_segment = pygame.draw.rect(WIN, (0,0,255), (x2,y2,20,20))
        segments.append(new_segment)

    # move the following segment to the next position
        for index in range(len(segments) -1, 0, -1):
            pass
                     

    
    if lives == 0:
        WIN.blit(BG_resize,(0,0))
        WIN.blit(font.render("You lost!", 0, (255,255,255)), (250 - (lose_width/2),250))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                WIN.blit(BG_resize,(0,0))
                lives = 3
                rand()

    pygame.display.update()
Reply
#2
Hello,
To add segments to the snake's body after it has eaten the fruit, you can modify the following parts of your code:
1. Create a new segment object for each segment you want to add to the snake's body. You can use the pygame.Rect class to represent each segment. In your code, you can add the following line after generating a new fruit position: pizza tower
python
new_segment = pygame.Rect(x, y, 20, 20)
segments.append(new_segment)
2. This creates a new segment with the same position as the fruit and adds it to the segments list. Move the existing segments of the snake's body towards the head. This ensures that each segment follows the previous segment. You can do this by iterating over the segments list in reverse order and updating the position of each segment to match the position of the segment in front of it. Add the following code after adding the new segment:
python
for index in range(len(segments) - 1, 0, -1):
    segments[index].x = segments[index - 1].x
    segments[index].y = segments[index - 1].y
This loop starts from the last segment and moves each segment towards the position of the segment in front of it.
3. Finally, update the position of the first segment (the one closest to the snake's head) to match the current position of the snake's head. This ensures that the snake's body moves along with the head. Add the following code after the previous loop:
python
segments[0].x = x
segments[0].y = y
This updates the position of the first segment to match the current position of the snake's head.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGame] Snake game: how to get an instance for my snake's body multiple times? hajebazil 2 2,113 Jan-30-2022, 04:58 AM
Last Post: hajebazil
  help with snake game blacklight 3 2,551 Jul-30-2020, 01:13 AM
Last Post: nilamo
  Snake Game - obstacle problem Samira 3 5,423 Oct-31-2019, 02:58 PM
Last Post: Samira
  [PyGame] Made my first Python program: Snake. Please help me improve it andrerocha1998 7 6,040 Feb-19-2019, 07:08 PM
Last Post: Windspar
  Creating Snake game in Turtle Shadower 1 8,617 Feb-11-2019, 07:00 PM
Last Post: woooee
  [PyGame] Basic Snake game (using OOP) PyAlex 1 12,445 Sep-10-2018, 09:02 PM
Last Post: Mekire
  [PyGame] Snake not changing directions in Snake Game Bjdamaster 4 4,853 Aug-13-2018, 05:09 AM
Last Post: Bjdamaster
  [PyGame] Snake controls not working jakegold98 5 6,293 Dec-12-2017, 01:45 AM
Last Post: Windspar

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020