0

I am creating a a simple shooting game with Pygame. I want my targets to move around the screen rather than be static, but can't seem to be able to do so. The code I am using flags up "AttributeError: 'Group' object has no attribute 'move'", but I don't understand why. The relevant sections are as below:

class Target(pygame.sprite.Sprite):
    leftwards = False
    rightwards = False
    upwards = False
    downwards = False
    new_x = 0
    new_y = 0
    def __init__(self, pos_x, pos_y):
        super().__init__()
        self.image = pygame.image.load("al.png").convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.center = [pos_x, pos_y]
        Target.new_x = pos_x
        Target.new_y = pos_y
        if pos_x > screen_width/2:
            Target.leftwards = True
        else:
            Target.rightwards = True
        if pos_y > screen_height/2:
            Target.upwards = True
        else:
            Target.downwards = True
    def move(self):
        if Target.new_x == screen_width:
            Target.leftwards = True
            Target.rightwards = False
        if Target.new_x == 0:
            Target.rightwards = True
            Target.leftwards = False
        if Target.new_y == screen_height:
            Target.upwards = True
            Target.downwards = False
        if Target.new_y == 0:
            Target.downwards = True
            Target.downwards = False
        if Target.leftwards:
            Target.new_x -= 20
        if Target.rightwards:
            Target.new_x += 20
        if Target.upwards:
            Target.new_y -= 15
        if Target.downwards:
            Target.new_y += 15
        self.rect.center = [Target.new_x, Target.new_y]

And:


target_group = pygame.sprite.Group()
for target in range(20):
    new_target = Target(random.randrange(0, screen_width), random.randrange(0, screen_height))
    target_group.add(new_target)

Running = True
while Running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            crosshair.shoot()

  

    pygame.display.flip()
    screen.blit(background, (0, 0))
    target_group.draw(screen)
    target_group.move()
    score = len(target_group.sprites())
    stats(score)
    crosshair_group.draw(screen)
    crosshair_group.update()
    clock.tick(60)

Have I gone about it the completely wrong way?

  • I see you mentioned the specific error. Do you have a full stack trace? As far as Group not having attribute move, check the docs [here](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group). I think it is happening with this line `target_group.move()` – Smurphy0000 Dec 24 '20 at 19:56
  • Ah, OK, I renamed the method to update(), but now all of the targets immediately disappear behind the background image. – Joel Pearce Dec 24 '20 at 20:02

0 Answers0