On-Screen Timer

timer.py
1"""
2Show a timer on-screen.
3
4If Python and Arcade are installed, this example can be run from the command line with:
5python -m arcade.examples.timer
6"""
7import arcade
8from arcade.clock import GLOBAL_CLOCK
9
10WINDOW_WIDTH = 1280
11WINDOW_HEIGHT = 720
12WINDOW_TITLE = "Timer Example"
13
14
15class GameView(arcade.View):
16 """
17 Main application class.
18 """
19
20 def __init__(self):
21 super().__init__()
22 # What time to start the timer
23 self.start_time: float = 0.0
24 self.timer_text = arcade.Text(
25 text="00:00:00",
26 x=WINDOW_WIDTH // 2,
27 y=WINDOW_HEIGHT // 2 - 50,
28 color=arcade.color.WHITE,
29 font_size=100,
30 anchor_x="center",
31 )
32 self.background_color = arcade.color.ALABAMA_CRIMSON
33
34 def reset(self):
35 self.start_time = GLOBAL_CLOCK.time
36
37 def on_draw(self):
38 """ Use this function to draw everything to the screen. """
39 # Clear all pixels in the window
40 self.clear()
41
42 # Draw the timer text
43 self.timer_text.draw()
44
45 def on_update(self, delta_time):
46 """
47 All the logic to move, and the game logic goes here.
48 """
49 # Accumulate the total time
50 elapsed = GLOBAL_CLOCK.time_since(self.start_time)
51
52 # Calculate minutes
53 minutes = int(elapsed) // 60
54
55 # Calculate seconds by using a modulus (remainder)
56 seconds = int(elapsed) % 60
57
58 # Calculate 100ths of a second
59 seconds_100s = int((elapsed - seconds) * 100)
60
61 # Use string formatting to create a new text string for our timer
62 self.timer_text.text = f"{minutes:02d}:{seconds:02d}:{seconds_100s:02d}"
63
64def main():
65 window = arcade.Window(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE)
66 game = GameView()
67 game.reset()
68
69 window.show_view(game)
70 arcade.run()
71
72
73if __name__ == "__main__":
74 main()