- 1 year ago
I want to draw a line but change some things and use a class to keep drawing new lines
Comment
1 / 1
To draw a line with custom properties and using a class to keep drawing new lines, you can follow these steps:
- Import the necessary libraries: You will need to import the
pygame
library to create a graphical window and handle user input.
pythonimport pygame
- Define the Line class: The Line class will represent a line that can be drawn on the screen. It should have properties such as the starting and ending points, color, and width.
pythonclass Line:
def __init__(self, start, end, color=(255, 255, 255), width=1):
self.start = start
self.end = end
self.color = color
self.width = width
def draw(self, surface):
pygame.draw.line(surface, self.color, self.start, self.end, self.width)
- Initialize pygame: Before you can create a window and draw on it, you need to initialize the pygame library.
pythonpygame.init()
- Create a window: Use the
pygame.display.set_mode()
function to create a window with the desired size.
pythonscreen = pygame.display.set_mode((800, 600))
- Create a Line object and draw it: Create an instance of the Line class with the desired properties and call its
draw()
method to draw it on the screen.
pythonline = Line((0, 0), (800, 600), (255, 0, 0), 5)
line.draw(screen)
- Keep the window open: Use a while loop to keep the window open until the user closes it.
pythonwhile True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
Putting it all together, here is an example program that draws a red line on a white background:
pythonimport pygame
import sys
class Line:
def __init__(self, start, end, color=(255, 255, 255), width=1):
self.start = start
self.end = end
self.color = color
self.width = width
def draw(self, surface):
pygame.draw.line(surface, self.color, self.start, self.end, self.width)
pygame.init()
screen = pygame.display.set_mode((800, 600))
screen.fill((255, 255, 255))
line = Line((0, 0), (800, 600), (255, 0, 0), 5)
line.draw(screen)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
To draw multiple lines, you can create a list to store Line objects and loop through the list to draw them all. You can also add functionality to handle user input, such as clicking to create new lines or changing the properties of existing lines.