Штрихуйте линии с использованием черепахи для заполнения многоугольников.Python

Программы на Python
Ответить
Anonymous
 Штрихуйте линии с использованием черепахи для заполнения многоугольников.

Сообщение Anonymous »

Код: Выделить всё

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)
Выше приведен мой код для рисования параллельных линий для затенения многоугольника. Однако с помощью этого кода мои линии выходят за пределы границы многоугольника.
Мой результат:
Изображение

Я не уверен, где находится ошибка при вычислении начальной и конечной точек. Я ожидаю примерно такого результата:
Изображение

Если где-то есть ошибка, дайте мне знать.

Подробнее здесь: https://stackoverflow.com/questions/758 ... l-polygons
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»