如何从群组中的精灵调用函数? [英] How to call functions from sprites in groups?

查看:99
本文介绍了如何从群组中的精灵调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Sprite 类,我拥有,但在一个组。每次点击鼠标按钮,我想从类中调用一个函数。应该为组中的每个项目调用该函数。

I have a Sprite class that I have but in a group. Every time the mouse button is clicked I want to call a function from the class. The function should be called for every item in the group.

我只知道如何调用更新函数每个项目在组,但代码将非常缓慢,如果不是每次点击鼠标点击调用函数,我会在每个框架上调用它。

I only know how to call the update function from every item in the group but the code would be very slow if instead of calling the function on every mouse click I would call it on every frame.

使其更加清晰我会举个例子:

To make it more clear I'll give an example:

class sprite_object(pygame.sprite.Sprite):
    def __init__(self):
        super(sprite_object, self).__init__()

    def on_mouse_click(self):
        #when the mouse is clicked to some stuff
        pass

    def update(self):
        #do some stuff every frame
        pass

sprite_object_1 = sprite_object()
sprite_object_2 = sprite_object()

group_of_sprites = pygame.sprite.Group()

group_of_sprites.add(sprite_object_1, sprite_object_2)

现在,我可以在t中调用 on_mouse_click 函数他更新函数,但会使代码效率低下。

Now, I could call the on_mouse_click function in the update function but that would make the code inefficient.

如何调用 on_mouse_click 函数来自组中的每个对象?

How do I call the on_mouse_click function from every object in the group?

推荐答案

sprites ) sprite组对象的方法返回此sprite组对象包含的精灵列表。

The sprites() method of a sprite group object returns a list of sprites this sprite group object contains.

您可以遍历此列表(即所有sprite您的精灵组 groupe_of_sprites 持有)调用每个人 on_mouse_click()在groupe_of_sprites.sprites()中,sprite_object

You could iterate through this list (i.e. all sprites your sprite group groupe_of_sprites holds) to call the on_mouse_click() method of each individual sprite_object:

for sprite_object in groupe_of_sprites.sprites():
    sprite_object.on_mouse_click()

这篇关于如何从群组中的精灵调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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