原始帖子:使用pygame,可以从群组中识别随机的精灵吗?
我正在尝试学习Python,并一直在尝试增强Alien Invasion程序。对于外星人自己来说,是一个外星人阶级的外星人,并以此为基础创建了一个由4行8人组成的小组。
我想定期让一个随机的外星人飞到屏幕底部。是否可以与一个小组一起执行此操作,或者如果我想拥有此功能,是否还必须想出其他方法来创建我的车队?
我遇到过一些其他人似乎在尝试类似尝试的情况,但是没有任何信息说明他们是否成功。
更新:我已经对此进行了进一步的研究。我尝试在中创建alien_attack
函数game_functions.py
。内容如下:
def alien_attack(aliens):
for alien in aliens:
alien.y += alien.ai_settings.alien_speed_factor
alien.rect.y = alien.y
我从while循环称之为alien_invasion.py
有gf.alien_attack(aliens)
。不幸的是,这导致三行消失,另一行以我想要的方式攻击,除了整个行而不是单个精灵执行此操作。
我还尝试了更改aliens = Group()
为aliens = GroupSingle()
in alien_attack.py
。这导致游戏仅在屏幕上显示一个精灵。它以我想要的方式攻击,但我希望所有其他精灵也出现但不攻击。怎么做?
您可以通过调用选择随机精灵random.choice(sprite_group.sprites())
(sprites()
返回组中精灵的列表)。将此精灵分配给变量,然后对其执行任何操作。
这是一个最小的示例,在该示例中,我仅在选定的sprite上绘制一个橙色rect并调用其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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句