Where in my code is the correct place to put an event in order to spawn a ship after a certain period of time?

Viewed 27

I learned about the events settings through a very helpful user here on stackoverflow already. I think I understand how that function works. I currently spawn 1 enemy on the right side of the screen that moves towards the left. I am attempting to spawn them at certain time intervals.

However, I don't know where I am supposed to put the code in for the event. I've tried adding it into def _create_fleet(self): and def __init__(self): and def __init__(self, placeholder): under the "Alien.py" separate file, but none of them seem to work. Could someone please show me where the correct area to do so is?

I am trying to add this:

FIRE_EVENT  = pygame.USEREVENT + 1  # This is just a integer.
    pygame.time.set_timer(FIRE_EVENT, 1000)  # 1000 milliseconds is 1 seconds.
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
        elif event.type == FIRE_EVENT:  # Will appear once every second.
            ***whatever the right place to add will be put in here***

and the full code is here:

import sys
import pygame
from ship import Ship
from bullets import Bullet
from alien import Alien
from time import time, sleep

class Sideways:
    """Overall class to manage game assets"""

    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 > self.screen_rect.width:
                self.bullets.remove(bullet)

        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)

    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)

if __name__ == '__main__':
    pewpew = Sideways()
    pewpew.run_game()

with a separate "alien.py" file to create the aliens here:

import pygame
from pygame.sprite import Sprite
from random import randint


class Alien(Sprite):
    """A class to represent a single alien in the fleet."""

    def __init__(self, placeholder):
        """Initialize the alien and set its starting position"""
        super().__init__()
        self.screen = placeholder.screen
        self.screen_rect = self.screen.get_rect()

        #load the alien image and set its rect attribute
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()

        #Start each new alien randomly on right side of screen
        random_number = randint(0, self.screen_rect.height-self.rect.height)
        self.rect.x = self.screen_rect.width - self.rect.width
        self.rect.y = random_number 

        #Store the alien's horizontal position
        self.x = float(self.rect.x)

    def update(self):
        """Move alien to the left"""
        self.x -= 0.1
        self.rect.x = self.x
1 Answers

Create the timer event in the constructor of the your class Sideways:

class Sideways:
    def __init__(self):
        # [...]
        
        self.bullets = pygame.sprite.Group()

        # self._create_fleet()                   <--- DELETE

        # create timer event
        self.FIRE_EVENT  = pygame.USEREVENT + 1  # This is just a integer.
        pygame.time.set_timer(self.FIRE_EVENT, 1000)  # 1000 milliseconds is 1 seconds.

Handle the event tin the event loop and create a new enemy when the event occurs:

class Sideways:
    # [...]

    def _ship_movement_andfiring(self):
        # [...]

        for event in pygame.event.get():    
            if event.type == pygame.QUIT:
                sys.exit()

            elif event.type == self.FIRE_EVENT:
                self._create_fleet()     

            # [...]
Related