Build a Game #3
This lesson follows on from the previous one, where we create an enemy and track the score.
The Timer
As well as the score, we want to display a countdown timer. For this, we'll use window.time which tracks the seconds since our game started.
Start by creating a timer variable and the text (to display the timer).
timer = 30 timer_text = Text(size = 30)
Then in the game loop, update the text.
time_left = timer - window.time timer_text.content = str(time_left)
Finally, position the text in the top right corner.
timer_text.top = window.top - 10 timer_text.right = window.right - 10
Let's integrate this with our game.
Use Python's round function to round the time to one decimal place.
Game Over
When the countdown gets to 0, we'll display the final score in the centre of the screen.
if time_left < 0: score_text.position = 0 score_text.draw()
Also, to prevent the game from running forever, we can use return to exit our game loop early.
if time_left < 0: score_text.position = 0 score_text.draw() return
Let's add this logic to our game.
As a bonus, we'll display different messages if the player won, drew, or lost. First, create the text with the SERIF font.
status_text = Text(size = 50, font = SERIF)
In the game loop, change the colour and content based on the score.
if score < 0: status_text.content = "You lose" status_text.color = RED elif score > 0: status_text.content = "You win" status_text.color = GREEN else: status_text.content = "Tie" status_text.color = GOLD
Finally, position the text and draw it.
status_text.y = 50 status_text.draw()
Let's add this to our game.