Python Forum
[PyGame] Snake game: how to get an instance for my snake's body multiple times?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Snake game: how to get an instance for my snake's body multiple times?
#2
self.body can only reference one Body object, so self.body is only the last Body sprite.
        for pos in BODY_LIST:
         self.body = Body(self,pos[0],pos[1])
If you wanted all the Body sprites you could do something like this:
self.body = [Body(self, x, y) for x, y in  POS_LIST[1:-1]]
But I don't think this matters because you don't ever use self.body, you use self.all_sprites.

The real problem is this code in Body.
    def update(self):
 
        self.pos_list=POS_LIST[1:-1]
        self.movement()
 
    def movement(self):
      if self.game.head.move != [0, 0]:  # Indenting should always be 4 spaces, never 1
             for pos in self.pos_list:
              self.rect = pos[0]*10,pos[1]*10
             print(self.pos_list)
If there are 3 positions in self.pos_list this code moves the same Body sprite 3 times. If you have 3 Body sprites all three are moved 3 times TO THE SAME FINAL POSITION (self.pos_list[-1]). That is why it looks like all but one of the Body sprites have disappeared, they are all sitting on top of each other.

To fix the problem you need to change how Body works. If it is only a single sprite it will have to know what index to use from the position list and it only updates itself. No "for pos in self.pos_list".
Reply


Messages In This Thread
RE: Snake game: how to get an instance for my snake's body multiple times? - by deanhystad - Jan-25-2022, 05:53 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  how to add segments to the snake body blacklight 1 2,973 Sep-13-2023, 07:33 AM
Last Post: angelabarrios
  help with snake game blacklight 3 2,678 Jul-30-2020, 01:13 AM
Last Post: nilamo
  Adding persistent multiple levels to game michael1789 2 2,473 Nov-16-2019, 01:15 AM
Last Post: michael1789
  Snake Game - obstacle problem Samira 3 5,778 Oct-31-2019, 02:58 PM
Last Post: Samira
  [PyGame] Made my first Python program: Snake. Please help me improve it andrerocha1998 7 6,333 Feb-19-2019, 07:08 PM
Last Post: Windspar
  Creating Snake game in Turtle Shadower 1 8,706 Feb-11-2019, 07:00 PM
Last Post: woooee
  [PyGame] Basic Snake game (using OOP) PyAlex 1 12,655 Sep-10-2018, 09:02 PM
Last Post: Mekire
  [PyGame] Snake not changing directions in Snake Game Bjdamaster 4 5,062 Aug-13-2018, 05:09 AM
Last Post: Bjdamaster
  [PyGame] Snake controls not working jakegold98 5 6,573 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