1

sorry this question may be a duplicate but i have been searching a lot about this topic and i couldn't do anything. So how can i blit to the screen a new enemy every 10 sec ? btw i want to implement that using the USEREVENTS as i'm learning them newly. I'm really having trouble with this kind of events, i can't get them, this is what i tried :

a = 10000
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_e:
            pygame.time.set_timer(pygame.USEREVENT+1, a)
if a == 0:
    screen.blit(enemy, (enemyX, enemyY))
    a = 5000
Developeeer
  • 110
  • 1
  • 1
  • 10

1 Answers1

1

In pygame exists a timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. The time has to be set in milliseconds. e.g.:

timer_interval = 10000 # 10 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, timer_interval)

Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case pygame.USEREVENT+1 is the event id for the timer event.

Receive the event in the event loop:

run = True
while run:

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

         elif event.type == timer_event:
             # [...]

The timer event can be stopped by passing 0 to the time argument of pygame.time.set_timer.


Note, you have to use a list to manage the enemies. Add a new enemy position to a list when the event occurs. Iterate through the enemies in a loop. Move and draw the enemies in the loop:

timer_interval = 10000 # 10 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, timer_interval)

enemy_list = []

run = True
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

         elif event.type == timer_event:
             # [...]

             enemy_list.append([enemyX, enemyY])  

    # [...]

    for enemy_pos in enemy_list:
        screen.blit(enemy, enemy_pos)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Thank you, but will the timer be set automatically to 10000 ms again every time the time_interval becomes equal to zero ? or should i do it myself? and btw what's that pygame.NUMEVENTS? – Developeeer Apr 28 '21 at 16:19
  • 1
    @Developeeer Yes, as I mentioned in the answer *"Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue."* - Reading the documentation would help as well. – Rabbid76 Apr 28 '21 at 16:21