Duplicating a sprite

大憨熊 提交于 2021-02-05 07:33:13

问题


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.


回答1:


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()


来源:https://stackoverflow.com/questions/64377099/duplicating-a-sprite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!