Search code examples
pythonpython-2.7pygamerect

event IDs and pygame.time.set_timer


i'm trying to make a simple basic program with pygame. one of the things im trying to make it do is create a randomly sized rectangle somewhere random on the screen in 6 seconds. i'm very new to all of this, and I am also pretty new to python 2.7(I was learning 3.5 in class)

so far I have:

mob2_spawn = 0

def create_mob():
    mob2 = pygame.Rect(random.randint(0,800), random.randint(0,600), random.randint(20,60), random.randint(30,50))
    pygame.draw.rect(window_surface, mob_color, mob2)
    pygame.display.update()
    mob2_spawn = 1

if mob_spawn == 0:
    pygame.time.set_timer(25,6000)
    mob2_spawn = 1

how do I attach an event ID to something? I understand that the first variable in pygame.time.set_timer is the event id, and should be an integer between 25 and 32. and essentially the timer should run that function associated with that event id every X milliseconds correct


Solution

  • You need to check for an event, for example a button press. First you need to make pygame check for any button presses:

    keystate = pygame.key.get_pressed()
    

    Then you need to put this in your code, so that you have an event in your timer:

    pygame.time.set_timer(keystate[pygame.K_SPACE], (25, 6000))
    

    That's at least what I think should happen, by the way i'm using the example with the space button. I hope it works for you!