Adding a Timer using Python

In this blog post we will investigate how we implement a timer to add in any of our Python game/projects. To do so we will use the time library in Python.

So, to import the time library we will add the following line of code at the top of our code:
import time

To initialise our timer by deciding on the duration of the game (allocated time) measured in second. For instance, for a 1 minute game we will set the allocated time to 60s.
allocatedTime = 60

When the game start we will take a timestamp to record the time the game started.
startTime = time.time()

At any stage during the game, we can measure the number of seconds since the beginning of the game using the following instruction:
elapsedTime = time.time() - startTime

We can then compare this with the allocated time to see if it’s time over!

if elapsedTime >= allocatedTime:
   print("Game Over")

Let’s combine the above steps to complete our timer based on the following flowchart:

The Python code would be as follows:

import time

allocatedTime = 60
startTime = time.time()
gameOver = False

while gameOver==False:
   
  # Add Code for the game...
  time.sleep(1)

  elapsedTime = time.time() - startTime
  if elapsedTime >= allocatedTime:
     gameOver = True

print("Game over!")


Pass The Bomb

Let’s see a complete example of a game using a timer. The code below is for a game of “Pass the bomb”, where several players are passing a bomb to one another. The player holding the bomb has to answer a question. (e.g. Can you think of a word containing the letters “CO”?). The bomb is set with a random delay before it explodes. After answering the question, the game checks if the timer for the bomb has expired and hence the bomb has exploded. In this case, the player is removed from the game, the timer for the bomb is reset and the game carries on till there is only one player left.

Did you like this challenge?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 9

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!