为何向Pygame的sprite.Group添加对象后列表仍为空?
问题原因及解决方法
为什么bullet_group2始终为空?
你在初始化时执行了bullet_group2= pygame.sprite.Group.sprites(bullet_group),这行代码的作用是一次性获取当时bullet_group里的所有精灵,生成一个普通列表。而此时bullet_group还没有添加任何子弹,所以bullet_group2就是空列表。
关键是:这个列表是静态的——之后你向bullet_group添加新子弹时,bullet_group2不会自动同步更新,它只会保持初始化时的空状态,所以不管你加多少子弹,它都是空的。
正确的实现方式
你根本不需要bullet_group2这个中间列表,直接对bullet_group本身做判断就行。pygame的Group对象支持直接用len()获取当前包含的精灵数量,修改代码如下:
bullet_group = pygame.sprite.Group() enemy_group = pygame.sprite.Group() prev_time = time.time() game_active = False gameName = pygame.font.Font('font/Pixeltype.ttf',80).render('Asteroids',False,(51,153,255)) gameName_rect = gameName.get_rect(center = (400,70)) text2 = test_font.render('Press "space" to run',False,(51,153,255)) text2_rect = text2.get_rect(center = (400,340)) while True: dt = time.time() - prev_time prev_time = time.time() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if game_active: display_score() # 直接判断bullet_group的长度,不需要bullet_group2 if len(bullet_group) <= 3 : if event.type == pygame.MOUSEBUTTONDOWN: bullet_group.add(player.create_bullet())
这样就能实现“子弹数量不超过3个时才添加新子弹”的需求了。
内容的提问来源于stack exchange,提问作者Unix
相关产品推荐
相关产品推荐

