1
\$\begingroup\$

I'm doing a game in which i have a ball which is controlled by the keyboard and the goal is to get is out of a maze without touching the walls.

I've added my ball sprite to GroupSprite

vehicle = pygame.sprite.GroupSingle(Vehicle(70,470))

since at the time, i thought that was the right way of doing it. However, i found that all the interaction always goes with the sprite directlly not with the GroupSingle. So I end with constantly accessing the sprite throug the GroupSingle.sprite:

vehicle.sprite.desired_speed_up_down

Is there a reason why i shouldn't just remove 'GroupSingle' and define:

vehicle = Vehicle(70,470)
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

No. If you don't use any features of the Group, you can just stop using it.


However, nothing is stoping you from storing your player Sprite in a seperate field and using your GroupSingle for stuff like collision detection/drawing/updating if you maintain a list of SpriteGroups for example to have your code look more uniformly:

# initialize
vehicle = Vehicle(70,470)

vehicle_group     = pygame.sprite.GroupSingle(vehicle) # make it clear there's only one vehicle (player) by using GroupSingle
wall_group        = pygame.sprite.Group(YourWallSpritesOrSomething)
other_stuff_group = pygame.sprite.Group(OtherStuffSprites)
all_groups        = (vehicle_group, wall_group, other_stuff_group)
...

# drawing eveything, including player, walls, and stuff...
for g in all_groups:
    g.draw(screen)
...

# updating eveything, including player, walls, and stuff...
for g in all_groups:
    g.update(...)

# test if 'somesprite' collides with anything, including player:
if any(spritecollideany(somesprite, g) for g in all_groups):
    do_stuff(somesprite)

# test if player (vehicle) hits a wall:
if spritecollideany(vehicle, wall_group):
    lose_game()

But if the Sprite in your GroupSingle never changes, a regular Group would also be fine, but a GroupSingle would nonetheless make the fact clearer that there's always a single vehicle.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .