Screensaver/screensaver.py

134 lines
3.5 KiB
Python

#!/usr/bin/python3
import os
import math
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((1000, 600), pygame.RESIZABLE)
pygame.display.set_caption("Screensaver")
gray = (20, 20, 20)
red = (255, 20, 20)
working_directory = os.path.abspath(__file__)
wobblers = []
max_wobbler_size = 50
clock = pygame.time.Clock()
running = True
class Wobbler:
def __init__(self, position: tuple=(100, 100), rotation: int=0):
self.size = 1
self.width = self.size
self.height = self.size
self.x, self.y = position
self.color = red
self.rotation = rotation
self.speed = 4
self.age = 0
self.cube = pygame.Surface((self.height, self.width))
self.cube.fill(self.color)
self.cube_no_rot = self.cube
self.cube.set_colorkey(gray)
self.cube = pygame.transform.rotate(self.cube, self.rotation)
self.cube_rect = self.cube.get_rect(center=self.cube_no_rot.get_rect(center=(self.x, self.y)).center)
def draw(self):
screen.blit(self.cube, self.cube_rect)
def update(self):
self.width = self.size
self.height = self.size
self.cube = pygame.Surface((self.height, self.width))
self.cube.fill(self.color)
self.cube_no_rot = self.cube
self.cube.set_colorkey(gray)
self.cube = pygame.transform.rotate(self.cube, self.rotation)
self.cube_rect = self.cube.get_rect(center=self.cube_no_rot.get_rect(center=(self.x, self.y)).center)
def move(self):
x_offset, y_offset = deg_to_offset(self.rotation, self.speed)
self.x += x_offset
self.y += y_offset
def deg_to_offset(degrees, offset):
radians = math.radians(degrees)
x = math.sin(radians) * offset
y = math.cos(radians) * offset
return x, y
def update():
screen.fill(gray)
for event in pygame.event.get():
if event.type == pygame.QUIT:
global running
pygame.quit()
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
print(wobblers)
print(len(wobblers))
if running:
new_wobbler = random.randrange(1, 121) == 1
if new_wobbler:
x = random.randrange(0, screen.get_width() + 1)
y = random.randrange(0, screen.get_height() + 1)
rot = random.randrange(0, 360)
wobblers.append(Wobbler((x, y), rot))
for wobbler in wobblers:
if not wobbler.x < 0 or not wobbler.x > screen.get_width() or not wobbler.y < 0 or not wobbler.y > screen.get_height():
wobbler.move()
wobbler.update()
wobbler.draw()
if wobbler.speed > 1:
decrease_speed = random.randrange(1, 101 - wobbler.speed) == 1
if decrease_speed:
wobbler.speed -= 1
change_rot = random.randrange(1, 101 - wobbler.speed) == 1
if change_rot:
wobbler.rotation = random.randrange(0, 360)
if wobbler.age < max_wobbler_size:
wobbler.size += 1
wobbler.age += 1
if wobbler.age >= 300:
wobbler.size -= 1
if wobbler.size == 0:
wobblers.remove(wobbler)
if wobbler.x < -5 or wobbler.x > screen.get_width() + 5 or wobbler.y < -5 or wobbler.y > screen.get_height() + 5:
wobbler.rotation -= 180
pygame.display.update()
clock.tick(60)
while running:
update()