Created
September 21, 2023 15:56
-
-
Save shravanasati/cc03f14c7305b8d26ccc4ddd77d86996 to your computer and use it in GitHub Desktop.
a simple analog clock using pygame
This file contains 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
from datetime import datetime | |
from math import cos, sin, radians | |
import pygame | |
WIDTH, HEIGHT = 800, 600 | |
ORIGIN = (WIDTH // 2, HEIGHT // 2) | |
def polar_to_cartesian(length: float, theta: float): | |
return (length * cos(radians(theta)), length * sin(radians(theta))) | |
def scale_coordinate(coordinate: tuple[float, float]): | |
x, y = coordinate | |
return (ORIGIN[0] + x, -y + ORIGIN[1]) | |
pygame.init() | |
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT)) | |
pygame.display.set_caption("analOGUE Clock") | |
HOUR_HAND_LENGTH = 50 | |
MINUTE_HAND_LENGTH = 80 | |
SECOND_HAND_LENGTH = 100 | |
if __name__ == "__main__": | |
clock = pygame.time.Clock() | |
running = True | |
while running: | |
clock.tick(30) | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT: | |
running = False | |
SCREEN.fill("black") | |
pygame.draw.circle(SCREEN, "pink", ORIGIN, SECOND_HAND_LENGTH + 20) | |
pygame.draw.circle(SCREEN, "red", ORIGIN, 5) | |
now = datetime.now() | |
hand_data = { | |
HOUR_HAND_LENGTH: -30 * (now.hour % 12) - 0.5 * now.minute + 90, | |
MINUTE_HAND_LENGTH: now.minute * -6 - now.second * 0.1 + 90, | |
SECOND_HAND_LENGTH: now.second * -6 + 90 | |
} | |
for length, angle in hand_data.items(): | |
pygame.draw.line( | |
SCREEN, "white", ORIGIN, scale_coordinate(polar_to_cartesian(length, angle)), 4 | |
) | |
pygame.display.update() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment