Reputation: 157
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:
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.
Upvotes: 3
Views: 988
Reputation: 101052
for x in bodyparts:
body.timeleft -= 1
if body.timeleft == 0:
body = False
Here, you iterate over the sprite group, storing each sprite in the variable x
. You never define body
, so an exception is raised.
Even if you did, setting body
to False
would not magically remove the sprite from the sprite group. To do so, you the remove
method.
So you should change your loop to:
for body in bodyparts:
body.timeleft -= 1
if body.timeleft == 0:
bodyparts.remove(body)
Instead of using a sprite group, you could also use a simple list, and remove elements once it gets too big:
max_len = 4 # current max length of snake
bodyparts = []
def more_body(bodyparts, x, y, z):
body = ...
bodyparts.append(body)
bodyparts=bodyparts[-max_len:]
Also, you should load your image 'body.png'
only once and reuse it, instead of loading it everytime.
Upvotes: 2