【问题标题】:Generate single random number from Pygame Sprite Collision, currently multiple numbers generated从 Pygame Sprite Collision 生成单个随机数,当前生成多个数字
【发布时间】:2018-03-10 15:58:23
【问题描述】:

我正在破解 Python Crash Course 中的太空入侵者游戏。我正在使用 Python 3.5 和 Pygame 1.9.2a0,groupcollide()

在原版中,当子弹与飞船相撞时,两个精灵都会从屏幕上移除。

在我的版本中,我希望对我的移除更加随机,以便并非所有命中都成功。我使用随机模块完成了此操作,并且如果随机数低于某个阈值 (n),则碰撞成功。我在下面的代码中使用了该函数,但它没有按我的意愿工作。

使用 print(num) 我发现会生成随机数,直到达到 num

我认为这是因为在子弹穿过船只精灵矩形时检测到多次碰撞。测试这个理论,如果我在碰撞时移除子弹,那么只会生成 1 个数字。

第一季度。如何保留子弹但每次精灵碰撞只生成一个数字?

第二季度。你有比使用随机数更好的建议吗?

任何方向都非常感谢,谢谢

def check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets):

    """Respond to bullet-alien collisions."""

    #I swapped True, True to False, False below
    collisions = pygame.sprite.groupcollide(bullets, aliens, False, False)

    #I added this if statement

    if collissions:
        num = randrange(100)
        print (num) # lots of numbers generated just want 1
        if num <= 30:
            collissions = pygame.sprite.groupcollide(bullets, aliens, True, True)

    #below in original code

    if len(aliens) == 0:
        # Destroy existing bullets, and create new fleet.
        bullets.empty()
        create_fleet(ai_settings, screen, ship, aliens)
        create_fleet(mi_settings, screen, decayingNucleus, ships)

【问题讨论】:

    标签: python random pygame


    【解决方案1】:

    您可以为您的Bullet 类赋予self.live 属性并将其设置为TrueFalse,具体取决于实例化期间的随机数。然后遍历碰撞的精灵,如果子弹的 live 属性为 True,则仅调用 enemy.kill()

    import random
    import pygame as pg
    
    
    pg.init()
    
    BG_COLOR = pg.Color('gray12')
    ENEMY_IMG = pg.Surface((50, 30))
    ENEMY_IMG.fill(pg.Color('darkorange1'))
    BULLET_IMG = pg.Surface((9, 15))
    BULLET_IMG.fill(pg.Color('aquamarine2'))
    
    
    class Enemy(pg.sprite.Sprite):
    
        def __init__(self, pos):
            super().__init__()
            self.image = ENEMY_IMG
            self.rect = self.image.get_rect(center=pos)
    
    
    class Bullet(pg.sprite.Sprite):
    
        def __init__(self, pos):
            super().__init__()
            self.image = BULLET_IMG
            self.rect = self.image.get_rect(center=pos)
            self.pos = pg.math.Vector2(pos)
            self.vel = pg.math.Vector2(0, -450)
            # If `live` is True, the bullet is able to destroy an enemy.
            self.live = True if random.randrange(100) < 70 else False
    
        def update(self, dt):
            # Add the velocity to the position vector to move the sprite.
            self.pos += self.vel * dt
            self.rect.center = self.pos  # Update the rect pos.
            if self.rect.bottom <= 0:  # Outside of the screen.
                self.kill()
    
    
    class Game:
    
        def __init__(self):
            self.clock = pg.time.Clock()
            self.screen = pg.display.set_mode((800, 600))
    
            self.all_sprites = pg.sprite.Group()
            self.enemies = pg.sprite.Group()
            self.bullets = pg.sprite.Group()
    
            for i in range(15):
                pos = (random.randrange(30, 750), random.randrange(500))
                enemy = Enemy(pos)
                self.enemies.add(enemy)
                self.all_sprites.add(enemy)
    
            self.bullet_timer = .1
            self.done = False
    
        def run(self):
            while not self.done:
                # dt = time since last tick in milliseconds.
                dt = self.clock.tick(60) / 1000
                self.handle_events()
                self.run_logic(dt)
                self.draw()
    
        def handle_events(self):
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.done = True
                elif event.type == pg.MOUSEBUTTONDOWN:
                    bullet = Bullet(pg.mouse.get_pos())
                    self.bullets.add(bullet)
                    self.all_sprites.add(bullet)
                    pg.display.set_caption('This bullet is live: {}'.format(bullet.live))
    
        def run_logic(self, dt):
            mouse_pressed = pg.mouse.get_pressed()
            self.all_sprites.update(dt)
    
            # hits is a dict. The enemies are the keys and bullets the values.
            hits = pg.sprite.groupcollide(self.enemies, self.bullets, False, True)
            for enemy, bullet_list in hits.items():
                for bullet in bullet_list:
                    # Only kill the enemy sprite if the bullet is live.
                    if bullet.live:
                        enemy.kill()
    
        def draw(self):
            self.screen.fill(BG_COLOR)
            self.all_sprites.draw(self.screen)
            pg.display.flip()
    
    
    if __name__ == '__main__':
        Game().run()
        pg.quit()
    

    【讨论】:

    • 谢谢,我会在下周尝试合并,让你知道进展如何,不幸的是现在太忙了,因为它是我的周末项目,希望是相反的方式哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2023-01-03
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多