Last active
August 22, 2025 12:59
-
-
Save arraytools/de8115a56a5f6cff01932c5461032a29 to your computer and use it in GitHub Desktop.
Create a simple digital clock using the pygame module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import time | |
import pygame | |
# Initialize pygame | |
pygame.init() | |
# Set up display (resizable) | |
WIDTH, HEIGHT = 400, 200 | |
window = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE) | |
pygame.display.set_caption("Digital Clock") | |
# Colors | |
BLACK = (0, 0, 0) | |
WHITE = (255, 255, 255) | |
GREY = (150, 150, 150) | |
clock = pygame.time.Clock() | |
running = True | |
while running: | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT: | |
running = False | |
elif event.type == pygame.VIDEORESIZE: | |
WIDTH, HEIGHT = event.size | |
window = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE) | |
# Calculate font size based on window height | |
font_size = int(HEIGHT * 0.5) | |
font = pygame.font.SysFont("Helvetica", font_size) | |
# Get current time | |
current_time = time.strftime("%H:%M:%S") | |
hours_minutes, seconds = current_time.rsplit(":", 1) | |
# Render text | |
hm_text = font.render(hours_minutes, True, WHITE) | |
sec_text = font.render(":" + seconds, True, GREY) | |
# Clear screen | |
window.fill(BLACK) | |
# Position text in the center with proper spacing | |
total_width = hm_text.get_width() + sec_text.get_width() | |
hm_x = (WIDTH - total_width) // 2 | |
sec_x = hm_x + hm_text.get_width() | |
y_pos = HEIGHT // 2 - hm_text.get_height() // 2 | |
window.blit(hm_text, (hm_x, y_pos)) | |
window.blit(sec_text, (sec_x, y_pos)) | |
# Update display | |
pygame.display.flip() | |
clock.tick(1) | |
pygame.quit() | |
sys.exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment