python - 从 Pygame Sprite Collision 生成单个随机数,目前生成多个随机数

标签 python random pygame

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

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

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

我发现使用 print(num) 会生成随机数,直到达到 num <=n。我只想每次碰撞生成一个数字。

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

Q1。我怎样才能保留子弹但每次 Sprite 碰撞只生成一个数字?

Q2。你有比使用随机数更好的建议吗?

非常感谢任何方向,谢谢

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)

最佳答案

您可以为您的 Bullet 类提供一个 self.live 属性,并将其设置为 TrueFalse,具体取决于在实例化期间的随机数上。然后遍历碰撞的 Sprite ,仅当子弹的 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()

关于python - 从 Pygame Sprite Collision 生成单个随机数,目前生成多个随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49211084/

相关文章:

python - 如何将 Sprite 从矩形更改为图像?

python - 在类中编写快速的Python代码;通过 self 论证产生的开销

java - 彩票 - 猜正确的数字

python - pytest - 使用另一个插件的插件

sql - 如何用随机值更新多行

c# - 如何创建一个包含数字数组和字符串数组的随机类

python - AttributeError: 'pygame.math.Vector2' 对象没有属性

python - 如何在 PyGame 中滚动背景表面?

python - 机器学习防止过拟合这是作弊吗?

使用 cx_Freeze 可执行的 Python 脚本,exe 不执行任何操作