1

Fairly new at Python programming.

I now need to add these sprites to groups so I can update, the problem is I don't understand how to pull the references of these sprites out. In the sample program below you'll notice the instantiation of the robot creates a box and the instantiation of a box creates a bug. My questions are: 1. How do I add the objects buried in other objects to the sprite group. 2. The box objects will move with the robot, but at some time in the future the box will get handed off to another robot and this first robot may go away. How do I manage this given the box was created by the first robot.

class Robot(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.numBox = random.randint(1,5)
        for box in self.numBox:
            box = Box():
class Box(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        bug = Bug()
class Bug(pygame.sprite.Sprite):
    ...

def main():
    robot = Robot()
    groups = pygame.sprite.Group()
    while TRUE:
        groups.update()
1
  • Did the class Bug inherit the Sprite? Commented Mar 26, 2017 at 14:22

1 Answer 1

1

Assuming that all classes inherits pygame.sprite.Sprite you could make it so all classes take a parameter group which they add themselves to. You can pass an arbitrary number of groups to the init method of the superclass pygame.sprite.Sprite which will add the object to the group. Then you just pass along this parameter to all the other classes. For example:

class Robot(pygame.sprite.Sprite):

    def __init__(self, group):
        super(Robot, self).__init__(group)
        self.num_box = random.randint(1,5)
        for box in self.numBox:
            box = Box(group):

class Box(pygame.sprite.Sprite):

    def __init__(self, group):
        super(Box, self).__init__(group)
        bug = Bug(group)

class Bug(pygame.sprite.Sprite):

    def __init__(self, group):
        super(Bug, self).__init__(group)
        ...

def main():
    group = pygame.sprite.Group()
    robot = Robot(group)
    while True:
        group.update()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.