Kode Python Membuat Timer
KODE PYTHON MEMBUAT TIMER
1. Format Biasa
import pygame
import time
import sys
# Inisialisasi pygame
pygame.init()
# Ukuran layar
WIDTH, HEIGHT = 400, 200
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Countdown Timer")
# Warna
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
TEXT_COLOR = (255, 0, 0) # Warna merah agar jelas
# Font dan ukuran teks
font = pygame.font.Font(None, 80)
# Waktu awal dalam detik (misalnya 5 menit = 300 detik)
start_time = 7200
current_time = start_time
last_update = time.time()
# Fungsi menggambar timer di layar
def draw_timer():
SCREEN.fill(WHITE) # Bersihkan layar dengan warna putih
minutes = current_time // 60
seconds = current_time % 60
timer_text = font.render(f"{minutes:02}:{seconds:02}", True, TEXT_COLOR)
SCREEN.blit(timer_text, (WIDTH // 3, HEIGHT // 3))
pygame.display.flip()
# Loop utama
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update timer setiap detik
now = time.time()
if now - last_update >= 1:
current_time -= 1
last_update = now
if current_time <= 0:
print("Waktu habis!")
running = False
draw_timer()
pygame.quit()
sys.exit()
2. Format Jam:Menit:Detik
import pygame
import time
import sys
# Inisialisasi pygame
pygame.init()
# Ukuran layar
WIDTH, HEIGHT = 400, 200
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Countdown Timer")
# Warna
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
TEXT_COLOR = (255, 0, 0) # Warna merah agar jelas
# Font dan ukuran teks
font = pygame.font.Font(None, 60)
# Waktu awal dalam detik (2 jam = 7200 detik)
start_time = 3600
current_time = start_time
last_update = time.time()
# Fungsi menggambar timer di layar
def draw_timer():
SCREEN.fill(WHITE) # Bersihkan layar dengan warna putih
hours = current_time // 3600
minutes = (current_time % 3600) // 60
seconds = current_time % 60
timer_text = font.render(f"{hours:02}:{minutes:02}:{seconds:02}", True, TEXT_COLOR)
SCREEN.blit(timer_text, (WIDTH // 4, HEIGHT // 3))
pygame.display.flip()
# Loop utama
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update timer setiap detik
now = time.time()
if now - last_update >= 1:
current_time -= 1
last_update = now
if current_time <= 0:
print("Waktu habis!")
running = False
draw_timer()
pygame.quit()
sys.exit()
Comments
Post a Comment