2025-03-10 18:37:53 +08:00

82 lines
2.9 KiB
Python

import pygame
import math
class Line:
def __init__(self, screen, method, pos, size, maincolor, bgcolor):
self.screen = screen
self.method = method
self.start_pos = pos
self.length = size
self.color = maincolor
self.bgcolor = bgcolor
self.angle = 0 # Angle in degrees
self.end_pos = self.calculate_end_pos()
def calculate_end_pos(self):
"""Calculate the end position of the line based on the angle and length."""
x_offset = self.length * math.cos(math.radians(self.angle))
y_offset = self.length * math.sin(math.radians(self.angle))
return (self.start_pos[0] + x_offset, self.start_pos[1] + y_offset)
def rotate(self, degree):
"""Rotate the line around its start position."""
self.angle = (self.angle + degree) % 360
self.end_pos = self.calculate_end_pos()
def resize(self, new_length):
"""Change the length of the line."""
self.length = new_length
self.end_pos = self.calculate_end_pos()
def recolor(self, color):
"""Change the color permanently."""
self.color = color
def recolor_tmp(self, color, time_):
"""Change the color temporarily."""
original_color = self.color
self.color = color
pygame.time.set_timer(pygame.USEREVENT, time_ * 1000) # Set a timer for the specified time
# Event handling for reverting color
def revert_color(event):
if event.type == pygame.USEREVENT:
self.color = original_color
pygame.time.set_timer(pygame.USEREVENT, 0) # Stop the timer
return revert_color
def move(self, degree, length):
"""Move the line by a certain degree and length."""
self.start_pos = (self.start_pos[0] + length * math.cos(math.radians(degree)),
self.start_pos[1] + length * math.sin(math.radians(degree)))
self.end_pos = self.calculate_end_pos()
def show(self):
"""Draw the line on the screen."""
pygame.draw.line(self.screen, self.color, self.start_pos, self.end_pos, 2)
def hide(self):
"""Clear the line from the screen by drawing over it with the background color."""
pygame.draw.line(self.screen, self.bgcolor, self.start_pos, self.end_pos, 2)
# Example usage:
pygame.init()
screen = pygame.display.set_mode((800, 600))
line = Line(screen, 'method', (400, 300), 100, (255, 0, 0), (0, 0, 0))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.USEREVENT:
# Handle color revert event
line.recolor_tmp((0, 255, 0), 2) # Example of temporary recoloring
screen.fill((0, 0, 0)) # Clear the screen
line.show() # Draw the line
pygame.display.flip() # Update the display
pygame.quit()