【问题标题】:Identify individual sprite from group in Pygame在 Pygame 中从组中识别单个精灵
【发布时间】:2018-07-26 13:51:24
【问题描述】:

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

我正在尝试学习 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 行消失,而 1 行以我想要的方式进行攻击,除了整行而不是单个精灵这样做。

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

【问题讨论】:

  • 如果您的问题是是否可以与一个小组一起做这个?,那么是的
  • 太棒了。以为我将不得不重新开始。任何建议如何做到这一点?如果您甚至可以将我指向一个概述如何执行此操作的页面,我会非常感激。

标签: python python-3.x pygame sprite


【解决方案1】:

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

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

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

【讨论】:

  • 干杯。这似乎行得通。现在添加某种计时器以对其进行更多控制。
猜你喜欢
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-14
  • 1970-01-01
相关资源
最近更新 更多