复制精灵 [英] Duplicating a sprite

查看:31
本文介绍了复制精灵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在添加新精灵时遇到问题.我正在寻找类似以下内容的内容:

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

因此,如果 1 个精灵的能量"高于其max_energy"的 90%,其能量将减半,现在将有第二个精灵与第一个精灵相同.不过我不知道如何做到这一点.

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.

推荐答案

一般情况下,需要实现duplicate方法并构造Sprite对象的新实例在方法中.

In general, you need to implement the duplicate method and construct a new instance of the Sprite object in the method.

另一种解决方案是使用 Python copy模块.deepcopy 可以创建对象的深层副本.不幸的是,这不能用于 pygame.sprite.Sprite 对象,因为 image 属性是一个 pygame.Surface,无法深度复制.因此,Spritedeepcopy 会导致错误.
除非你没有或者任何其他需要深度复制的属性,你可以对Sprite做一个浅的copy.rect 属性是一个 pygame.Rect 对象.Sprite 的副本需要自己的矩形,因此您必须生成一个新的矩形实例.幸运的是,pygame.Rect 对象可以通过 pygame.Rect.copy:

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

这篇关于复制精灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆