简体   繁体   中英

Pygame Snake Game

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:

  1. Compare the len(bodyparts) to a previously-set variable.
  2. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM