Domanda

I am building a space invaders style game in Pygame. The enemies come in one at a time, and each loop sounds associated with them (this is for a psychology experiment in auditory learning, actually)

I want to put a 5 second delay in the game after a character is killed--so, when one character is shot, their sound fades out quickly, and the player must wait 5 seconds for the onset of the next character + sound

This is the script I have within my Game class, for generating enemies one at a time. I am using the core module from psychopy to measure time, but I can't seem to figure out how to delay the enemy onset without freezing the game (i.e. still allowing the player to move between onsets):

if len(self.enemyA_list) == 0 and len(self.enemyB_list) == 0 and len(self.enemyC_list) == 0:
    self.enemy = Enemy()

    #Increase speed, variability of character onset based on how many characters have been created
    if len(self.dead_enemies) == 2 or len(self.dead_enemies) == 3:
        self.enemy.x_speed *= 1.75
        self.enemy.y_speed *= 1.75
    elif len(self.dead_enemies) == 4:
        self.enemy.x_speed *= 2
        self.enemy.y_speed *= 2
    timer = core.Clock()
    timer.add(2)
    if timer.getTime()>=0:
        timer = 0
        self.enemy.generate() #generate enemy offscreen and start playing sound
        if self.enemy.enemy_type == 'A':
            self.enemyA_list.add(self.enemy)
            self.enemy.sound.out() #play enemy sound
            self.enemy.env.play()
        if self.enemy.enemy_type == 'B':
            self.enemyB_list.add(self.enemy)
            self.enemy.sound.out()
            self.enemy.env.play()
        if self.enemy.enemy_type == 'C':
            self.enemyC_list.add(self.enemy)
            self.enemy.sound.out()
            self.enemy.env.play()
            self.all_sprites_list.add(self.enemy)
È stato utile?

Soluzione

In your main game loop you should just create a variable keeping track of how much time there has been since the last spawn. Declare a variable. lastTime = 0 Then you add 1 to lastTime each time through the loop. lastTime += 1 Then you need to check how long it's been since the last time one spawned. Also you need to decide how many seconds you want between the spawns. So...

if timeElapsed == FPS * secondsBetweenSpawns:
    generateEnemy()

This will delay each spawn. Please note that this will require an FPS and an FPSClock.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top