Calling button only ticks for one second and can't display text?

Viewed 26

I am making a game and I want when I am in the garage if I buy more speed and I am already max, a text to pop up saying "Max speed reached!". But when I click on the button and have max speed, it doesn't stay but goes away after 1 tick. I can't figure out how to make it stay for longer because of how the button works. Any help is appreciated. Here is the code for the button:

            elif event.type == pygame.MOUSEBUTTONDOWN:
                # 1 is the left mouse button, 2 is middle, 3 is right.
                if event.button == 1:
                    # `event.pos` is the mouse position.
                    if button2.collidepoint(event.pos):
                        print('we been clicked')
                        current_time = time.strftime("%S")
                        # Increment the number
                        if player.vel < 20:
                            if player.coins >= 50:
                                player.vel += 5
                                player.coins -= 50
                                print('speed =' + str(player.vel))
                                player.vel1 = player.vel
                                player.grassvel = player.vel // 2
                                player.save()
                            else:
                                print("ur poor")
                        else:
                            MaxSpeedReached()

And here is the code for the function it calls:

def MaxSpeedReached():
    display_crash_text = False
    print("Max speed reached")
    if display_crash_text == False:
        start_time = time.strftime("%S")
        display_crash_text = True
    maxspeedtext = pygame.font.Font("freesansbold.ttf", 20)
    maxspedd, maxspeedr = text_objects("Max Speed  Reached!", maxspeedtext, BLACK)
    maxspeedr.center = ((205, 270))
    print(current_time, start_time)
    if display_crash_text == True:
        win.blit(maxspedd, maxspeedr)
        if int(start_time) - int(current_time) < 3:
            display_crash_text = False
            print("yo we checking the time difference")
1 Answers

Obviously you're seeing this because the message is drawn once when MaxSpeedReached() is called, but the only possible path to reach this function is on pygame.MOUSEBUTTONDOWN event.

You need to paint the message in the main loop, whenever the conditions for max-speed are occurring.

MAX_VELOCITY = 20

maxspeedtext = pygame.font.Font("freesansbold.ttf", 20)
maxspedd, maxspeedr = text_objects("Max Speed  Reached!", maxspeedtext, BLACK)
maxspeedr.center = ((205, 270))

[ ... ]

# Main loop
while not finished:

    [...]

    if ( player.vel >= MAX_VELOCITY ):
        win.blit( maxspedd, maxspeedr )
Related