Okay, this is my first time on this site, so I hope I get this right.
I am making a snake game in Pygame, for a school assessment task, and I have a problem. I am unable to get the snake's body parts to disappear.
Currently, this is how a body part is generated:
def more_body(bodyparts, x, y, z):
body = pygame.sprite.Sprite()
body.image = pygame.image.load('body.png')
body.rect = head.image.get_rect()
body.rect.right = x
body.rect.top = y
body.timeleft = z
bodyparts.add(body)
The body deletion check, as is, works like this.
for x in bodyparts:
body.timeleft -= 1
if body.timeleft == 0:
body = False
Bodyparts is, fairly obviously, the grouping for the bodyparts. It's an OrderedUpdates sprite group.
The problem is that the code doesn't seem to like this solution. Currently, the error is listed as "NameError: name 'body' is not defined". If I try to expand it the the check to reference bodyparts.body.timeleft instead of body.timeleft, I instead get "AttributeError: 'OrderedUpdates' object has no attribute 'body'".
There is a second solution I've come up with. As bodyparts is an OrderedUpdates group, it should be possible to select and delete specific pieces based on their location in the list. Therefore, the steps planned are as follows:
- Compare the len(bodyparts) to a previously-set variable.
- If the length exceeds how long the snake should be, delete the first item added to bodyparts - I'm not sure if this would be the first or last.
My main questions are:
Is this a viable solution, and would you be able to provide code to do it? Can I just treat it like a list, and split it so that the front (or back, depending on how they're added) of the bodyparts group is dropped? Any solutions you could provide would be of great help.