Code: Select all
import turtle
import math
def getPolygonVertices(numVertices): #get polygon vertices function
vertices = []
for i in range(numVertices):
x = int(input(f"Enter x coordinate of vertex {i+1}: "))
y = int(input(f"Enter y coordinate of vertex {i+1}: "))
vertices.append((x, y))
return vertices
def polygon(vertices): #draw polygon function
turtle.up()
turtle.goto(vertices[0])
turtle.down()
for vertex in vertices:
turtle.goto(vertex)
turtle.goto(vertices[0])
def pointInsidePolygon(point, vertices): #function to check if a point is inside polygon
x, y = point
inside = False
for i in range(len(vertices)):
j = (i + 1) % len(vertices)
if ((vertices[i][1] > y) != (vertices[j][1] > y)) and \
(x < (vertices[j][0] - vertices[i][0]) * (y - vertices[i][1]) / (vertices[j][1] - vertices[i][1]) + vertices[i][0]):
inside = not inside
return inside
def hatchPolygon(vertices, line_spacing=10, angle=0):
turtle.speed(0)
turtle.hideturtle()
#draw polygon
polygon(vertices)
#compute and draw hatch lines
min_x = min(v[0] for v in vertices)
max_x = max(v[0] for v in vertices)
min_y = min(v[1] for v in vertices)
max_y = max(v[1] for v in vertices)
#convert angle to radians
radAngle = math.radians(angle)
#compute line spacing in x and y direction
line_spacing_x = lineSpacing * math.cos(radAngle)
line_spacing_y = lineSpacing * math.sin(radAngle)
#compute start point
start_x = math.floor((min_x + line_spacing_x/2) / line_spacing_x) * line_spacing_x
start_y = math.floor((min_y + line_spacing_y/2) / line_spacing_y) * line_spacing_y
#compute end point
end_x = math.ceil((max_x - line_spacing_x/2) / line_spacing_x) * line_spacing_x
end_y = math.ceil((max_y - line_spacing_y/2) / line_spacing_y) * line_spacing_y
#draw hatch lines
turtle.penup()
for y in range(int(start_y), int(end_y), int(line_spacing_y)):
for x in range(int(start_x), int(end_x), int(line_spacing_x)):
if pointInsidePolygon((x, y), vertices):
turtle.goto(x, y)
turtle.pendown()
turtle.goto(x - line_spacing_x * math.tan(radAngle), y + line_spacing_y)
turtle.penup()
turtle.done()
#Main
n = int(input("Enter number of polygon vertices: ")) #get number of vertices
polygonVertices = getPolygonVertices(n) #get polygon vertices
#hatch line
lineSpacing = 10
angle = 45
hatchPolygon(polygonVertices, lineSpacing, angle)
Meine Ausgabe:

Ich bin mir nicht sicher, wo der Fehler bei der Berechnung der Start- und Endpunkte liegt. Das Ergebnis, das ich erwarte, ist ungefähr so:

Wenn an anderer Stelle ein Fehler auftritt, lassen Sie es mich bitte wissen.
Mobile version