Reputation: 123
I'm having trouble with getting new sprites to be added. I'm looking for something along the lines of:
def duplicate(sprites):
for d in sprites:
if d.energy >= d.max_energy * 0.9:
d.energy = d.energy / 2
new_d = d.duplicate()
so if 1 sprite had its 'energy' above 90% of its 'max_energy', its energy would be cut in half and now there would be a second sprite that was identical to the first. I'm not sure how to pull that off though.
Upvotes: 2
Views: 1325
Reputation: 211210
In general, you need to implement the duplicate
method and construct a new instance of the Sprite object in the method.
Another solution is to use the Python copy
module. deepcopy
can create a deep copy of an object. Unfortunately this cannot be used for pygame.sprite.Sprite
objects, as theimage
attribute is a pygame.Surface
, which cannot be copied deeply. Therefore, a deepcopy
of a Sprite will cause an error.
Unless you have nor any other attribute that needs to be copied deeply, you can make a shallow copy
of the Sprite. The rect
attribute is a pygame.Rect
object. The copy of the Sprite needs its own rectangle, so you have to generate a new rectangle instance. Fortunately a pygame.Rect
object can be copied by pygame.Rect.copy
:
import copy
new_d = copy.copy(d)
new_d.rect = d.rect.copy()
Upvotes: 3