how to make the enemy shoot bullets randomly with small delay in pygame

Question:

I’ve looked at other threads but they said to use pygame.time.set_timer(x, y) but this doesn’t seem to work for me, it still shoots super fast with zero delay and I have no idea why. What i want is for the enemy to shoot randomly but with at least a half second delay. (nme_game is the rect of the enemy and nme_game_bullet is supposed to be the bullets coming from the enemy)

Here’s the code:

def nme_shooting(nme_game, nme_game_bullet):
    bullet = pygame.Rect(nme_game.x + nme_game.width / 2.2 + 1, nme_game.y, 5, 25)
    nme_game_bullet.append(bullet)
    nme_game_bullet = USEREVENT + 1
    pygame.time.set_timer(nme_game_bullet, 500)
Asked By: Linuse

||

Answers:

nme_game_bullet cannot be a list (or Group) and an event type at once.

You must handle this in the event loop. Create a nme_game_bullet_event event type. Only spawn a bullet when you receive an event with the type nme_game_bullet_event:

nme_game_bullet_event = USEREVENT + 1
pygame.time.set_timer(nme_game_bullet_event, 500)

# application loop
run = True
while run: 
    
    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

        if event.type == nme_game_bullet_event:
            bullet = pygame.Rect(nme_game.x + nme_game.width / 2.2 + 1, nme_game.y, 5, 25)
            nme_game_bullet.append(bullet)

    # [...]

Alternatively pass the event or list of events to the nme_shooting function:

def nme_shooting(nme_game_bullet, event_list):
    for event in event_list:
        if event.type == nme_game_bullet_event:
            bullet = pygame.Rect(nme_game.x + nme_game.width / 2.2 + 1, nme_game.y, 5, 25)
            nme_game_bullet.append(bullet)
    
nme_game_bullet_event = USEREVENT + 1
pygame.time.set_timer(nme_game_bullet_event, 500)

# application loop
run = True
while run: 

    # event loop
    event_list = pygame.event.get():
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    nme_shooting(nme_game_bullet, event_list)

    # [...]
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.