def __init__(self):
"""Initialize the game and create game resources"""
pygame.init()
self.screen = pygame.display.set_mode((1200, 600))
self.screen_rect = self.screen.get_rect()
pygame.display.set_caption("Pew Pew")
self.bg_color = (204, 255, 255)
self.ship = Ship(self)
self.moving_up = False
self.moving_down = False
self.moving_left = False
self.moving_right = False
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._create_fleet()
def _create_fleet(self):
""""Create a fleet of aliens"""
alien = Alien(self)
self.aliens.add(alien)
def _update_aliens(self):
self.aliens.update()
def run_game(self):
while True:
self._ship_movement_andfiring()
self.ship.blitme()
self._update_screen()
self._update_bullets()
self._update_aliens()
def _update_bullets(self):
self.bullets.update()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
for bullet in self.bullets.copy():
if bullet.rect.right > 1200:
self.bullets.remove(bullet)
def _update_screen(self):
pygame.display.flip()
self.screen.fill(self.bg_color)
self.aliens.draw(self.screen)
def _ship_movement_andfiring(self):
if self.moving_up == True:
self.ship.rect.y -= 1
if self.moving_down == True:
self.ship.rect.y += 1
if self.moving_right == True:
self.ship.rect.x += 1
if self.moving_left == True:
self.ship.rect.x -= 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.moving_up = True
elif event.key == pygame.K_DOWN:
self.moving_down = True
elif event.key == pygame.K_RIGHT:
self.moving_right = True
elif event.key == pygame.K_LEFT:
self.moving_left = True
elif event.key == pygame.K_SPACE:
self._fire_bullet()
elif event.key == pygame.K_ESCAPE:
sys.exit()
elif event.type == pygame.KEYUP:
if event.key != pygame.K_SPACE:
self.moving_up = False
self.moving_down = False
self.moving_left = False
self.moving_right = False
if self.ship.rect.midleft <= self.ship.screen_rect.midleft:
self.moving_left = False
if self.ship.rect.bottom > self.ship.screen_rect.bottom:
self.moving_down = False
if self.ship.rect.midright >= self.ship.screen_rect.midright:
self.moving_right = False
if self.ship.rect.top <= 0:
self.moving_up = False
def _fire_bullet(self):
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
I'm following the python crash course book and trying to create a spin on it. I'm creating a game in Pygame that has a ship firing bullets to the right and I created an enemy that will move gradually to the left.
How do I create multiple enemies at a certain interval (e.g. after 5 seconds another enemy will spawn)? I've tried adding while loops to self._create_fleet() and to self.aliens.add(alien) but that breaks the game.