Skip to main content
 首页 » 编程设计

python之从 Pygame 中的组中识别单个 Sprite

2024年12月31日8telwanggs

原帖: 使用 pygame 是否可以从组中识别随机 Sprite ?

我正在尝试学习 Python 并一直在努力增强 Alien Invasion程序。对于外星人本身,一个具有外星人类别的外星人,并由此创建一个组,其中有 4 行,每行 8 个外星人。

我想让一个随机的外星人定期飞到屏幕底部。如果我想拥有此功能,是否可以与团队一起执行此操作,或者我是否必须想出一些其他方法来创建我的车队?

我遇到过一些案例,其他人似乎一直在尝试类似的东西,但没有任何信息说明他们是否成功。

更新: 我已经对此进行了更深入的研究。我尝试在 game_functions.py 中创建一个 alien_attack 函数。内容如下:

def alien_attack(aliens): 
    for alien in aliens: 
        alien.y += alien.ai_settings.alien_speed_factor 
        alien.rect.y = alien.y 

我在 alien_invasion.py 的 while 循环中用 gf.alien_attack(aliens) 调用了它。不幸的是,这导致 3 排消失,其中一排以我想要的方式进行攻击,只是整排都这样做而不是单个 Sprite 。

我还尝试在 alien_attack.py 中将 aliens = Group() 更改为 aliens = GroupSingle()。这导致游戏开始时屏幕上只有一个 Sprite 。它以我想要的方式攻击,但我希望所有其他 Sprite 也出现但不攻击。这是怎么做到的?

请您参考如下方法:

您可以通过调用 random.choice(sprite_group.sprites())(sprites() 返回组中的 Sprite 列表)来选择一个随机 Sprite 。将这个 Sprite 分配给一个变量,然后用它做任何你想做的事。

这是一个最小的示例,其中我只是在选定的 Sprite 上绘制一个橙色矩形并调用其 move_down 方法(按 R 以选择另一个随机 Sprite )。

import random 
import pygame as pg 
 
 
class Entity(pg.sprite.Sprite): 
 
    def __init__(self, pos): 
        super().__init__() 
        self.image = pg.Surface((30, 30)) 
        self.image.fill(pg.Color('dodgerblue1')) 
        self.rect = self.image.get_rect(center=pos) 
 
    def move_down(self): 
        self.rect.y += 2 
 
 
def main(): 
    pg.init() 
    screen = pg.display.set_mode((640, 480)) 
    clock = pg.time.Clock() 
    all_sprites = pg.sprite.Group() 
    for _ in range(20): 
        pos = random.randrange(630), random.randrange(470) 
        all_sprites.add(Entity(pos)) 
 
    # Select a random sprite from the all_sprites group. 
    selected_sprite = random.choice(all_sprites.sprites()) 
 
    done = False 
    while not done: 
        for event in pg.event.get(): 
            if event.type == pg.QUIT: 
                done = True 
            elif event.type == pg.KEYDOWN: 
                if event.key == pg.K_r: 
                    selected_sprite = random.choice(all_sprites.sprites()) 
 
        all_sprites.update() 
        # Use the selected sprite in the game loop. 
        selected_sprite.move_down() 
 
        screen.fill((30, 30, 30)) 
        all_sprites.draw(screen) 
        # Draw a rect over the selected sprite. 
        pg.draw.rect(screen, (255, 128, 0), selected_sprite.rect, 2) 
 
        pg.display.flip() 
        clock.tick(30) 
 
 
if __name__ == '__main__': 
    main() 
    pg.quit()