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
#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


Messages In This Thread
RE: how to add segments to the snake body - by angelabarrios - Sep-13-2023, 07:33 AM

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,262 Jan-30-2022, 04:58 AM
Last Post: hajebazil
  help with snake game blacklight 3 2,712 Jul-30-2020, 01:13 AM
Last Post: nilamo
  Snake Game - obstacle problem Samira 3 5,811 Oct-31-2019, 02:58 PM
Last Post: Samira
  [PyGame] Made my first Python program: Snake. Please help me improve it andrerocha1998 7 6,367 Feb-19-2019, 07:08 PM
Last Post: Windspar
  Creating Snake game in Turtle Shadower 1 8,723 Feb-11-2019, 07:00 PM
Last Post: woooee
  [PyGame] Basic Snake game (using OOP) PyAlex 1 12,687 Sep-10-2018, 09:02 PM
Last Post: Mekire
  [PyGame] Snake not changing directions in Snake Game Bjdamaster 4 5,093 Aug-13-2018, 05:09 AM
Last Post: Bjdamaster
  [PyGame] Snake controls not working jakegold98 5 6,608 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