George V
George V

Reputation: 19

How can I fix the timer to avoid values below 0 seconds?

while gamerunning:
    timerstart = time.time()

    posy2 += 3
    if posy2 >= window_height:
        posy2 = -50
        randomx = random.randrange(0, window_width - 50)

    if health == 0:
        gameover = True

    while gameover:
        timerend = time.time()
        timer = timerend - timerstart
        print timer
        screentext("Game over, press esc to quit or press R to retry", black)
        pygame.display.update()

I'm trying to figure out how to correctly implement a timer in python but I get values below 0 seconds when I print it out so I'm assuming that the timer variable is only printing out the time it takes for the python interpreter to run the code inside my gameover loop. My question is how can I fix this problem and make a proper timer that runs while the gamerunning loop is going and end once it's game over. I'm rather new to Python so I'm not sure what other modules I can really use to accomplish this other than time.

Upvotes: 1

Views: 35

Answers (1)

DarkCygnus
DarkCygnus

Reputation: 7838

Try moving timerstart = timer.time() outside the loop that runs your game. In your example that is before while gamerunning:. The problem was that in every loop the variable was being reset, thus the results you got.

We can't see the rest of your code in that image, but in this case in order to update the start time between games you have to update timerstart after/if the player selects 'R' to retry the game. Otherwise your game ends.

Upvotes: 1

Related Questions