varied spawn timer pygame bug

Question:

i try to make varied spawn timer (for rythm game)
it worked but if i move the mouse the timer get paused

import sys, pygame, pygame.mixer
from pygame.locals import *

pygame.init()

size = width, height = 1280, 720
screen = pygame.display.set_mode(size)

clock = pygame.time.Clock()

bullets = []
enemys  = []
tc      = 0
start   = 0
timer   = [500,100,2000,4000,1000,2000,3000,300,300,300,300,300,300,1000,1000,1000,1000,1000,1000,1000,1000,1000]
where   = [1  ,2  ,3   ,4   ,5   ,1   ,2]
neutral = False
spawn_enemy = pygame.USEREVENT + 0


background = pygame.image.load("png/arenabutbetter.png").convert()


bulletpicture = pygame.image.load("png/arrow144p.png").convert_alpha()
enemypicture  = pygame.image.load("png/enemy.png").convert_alpha()

tc = time counter
timer store time in ms/ 1/1000second

while True:
    mx, my = pygame.mouse.get_pos()
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        
        #the problem
        pygame.time.set_timer(spawn_enemy,timer[tc])
        if event.type == spawn_enemy:
            spawner.e1()
            tc +=1
        #the problem
        
        elif event.type == MOUSEBUTTONDOWN:
            #shot.play()
            if my > 0 and my < 144 :
                bullets.append([-100, 0])
                
            elif my > 144 and my < 288: 
                bullets.append([-100, 144])
                
            elif my > 288 and my < 432: 
                bullets.append([-100, 288])
                
            elif my > 432 and my < 576: 
                bullets.append([-100, 432])
        #enemy testing
            elif my > 576 and my < 720: 
                bullets.append([-100, 576])

the problem probably in here /

pygame.time.set_timer(spawn_enemy,timer[tc])
        if event.type == spawn_enemy:
            spawner.e1()
            scores +=1

should spawned enemy every timer[tc]
(get paused by mouse movement)

Asked By: pedi

||

Answers:

Since pygame.time.set_timer is called on every event, the timer is reset on every event (including mouse events). You must start the timer before the application loop and change the timer when the timer event occurs:

pygame.time.set_timer(spawn_enemy,timer[tc])
run = True
while run:
    mx, my = pygame.mouse.get_pos()
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        
        if event.type == spawn_enemy:
            pygame.time.set_timer(spawn_enemy,timer[tc])
            spawner.e1()
            tc +=1
        
        elif event.type == MOUSEBUTTONDOWN:
            # [...]
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.