pygame-cowsay-fortune/program.py
2025-03-29 08:35:54 -07:00

97 lines
2.6 KiB
Python
Executable file

import subprocess
import pygame
import time
from threading import Thread
# Function to run the Unix command
def run_command():
result = subprocess.run("cowsay -f $(ls /usr/share/cowsay/cows/ | shuf -n1) $(fortune)", shell=True, capture_output=True, text=True)
return result.stdout
# Function to update the window with the command output
def update_output():
global scroll_y
while True:
# Get the command output
output = run_command()
# Update the text content globally
global text_content
text_content = output
scroll_y = 0
time.sleep(2)
# Initialize Pygame
pygame.init()
# Set up the window
window_width = 600
window_height = 1024
screen = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Unix Command Output")
# Set up the font and colors
font = pygame.font.SysFont("freemono", 20)
text_color = (255, 255, 255)
bg_color = (0, 0, 0)
# Initialize global variables
text_content = ""
scroll_y = 0
scroll_speed = 5
# Function to render text onto the screen
def render_text():
screen.fill(bg_color)
lines = text_content.split("\n")
current_y = scroll_y
for line in lines:
# Render each line of text
text_surface = font.render(line, True, text_color)
if current_y > window_height:
break
screen.blit(text_surface, (16, current_y))
current_y += text_surface.get_height()
pygame.display.flip()
# Handle dragging
is_dragging = False
drag_start_y = 0
def handle_drag(event):
global is_dragging, drag_start_y, scroll_y
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
is_dragging = True
drag_start_y = event.pos[1]
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
is_dragging = False
elif event.type == pygame.MOUSEMOTION and is_dragging:
drag_distance = event.pos[1] - drag_start_y
scroll_y += drag_distance
drag_start_y = event.pos[1]
scroll_y = max(min(scroll_y, 0), -(len(text_content.split("\n")) * font.get_height()-window_height))
if (len(text_content.split("\n")) * font.get_height()) < window_height:
scroll_y = 0
# Create a thread to periodically update the command output
update_thread = Thread(target=update_output)
update_thread.daemon = True
update_thread.start()
# Main game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
handle_drag(event)
render_text()
pygame.time.Clock().tick(30)
pygame.quit()