我想這大概是不可能的。
你低估龜的進取心。這裏是我表現出你希望解決不對稱問題最初的例子:
import math
from itertools import cycle
from turtle import Turtle, Screen
COLORS = cycle(['red', 'green', 'blue', 'yellow'])
def rotate_polygon(polygon, angle):
theta = math.radians(angle)
sin, cos = math.sin(theta), math.cos(theta)
return [(x * cos - y * sin, x * sin + y * cos) for x, y in polygon]
def fill_polygon(turtle, polygon, color):
turtle.color(color)
for vertex in polygon:
turtle.goto(vertex)
if not turtle.filling():
turtle.begin_fill()
turtle.end_fill()
# triangle cursor 5x in size and X translated 50 pixels
polygon = ((100, -28.85), (50, 57.75), (0, -28.85))
screen = Screen()
yertle = Turtle(visible=False)
yertle.penup()
for angle in range(0, 360, 30):
rotated_polygon = rotate_polygon(polygon, angle)
color = next(COLORS)
fill_polygon(yertle, rotated_polygon, color)
screen.exitonclick()
輸出
我們真的希望最終的黃色三角形整齊下初始紅色貼身攜帶,像一個不斷上升的埃舍爾樓梯。我選擇了這個插圖,因爲它有多個重疊,最後的黃色三角不僅在紅色下面,而且在紅色後面是綠色和藍色。同樣,最後的黃色之前的藍色和綠色應低於紅色。等
上面我的代碼要複雜得多,需要吸取這個特殊的示意圖,但需要額外的結構支持以下改進:
一種辦法是制定出路口,而不是畫出最新三角形的那部分。另一種方法是繪製新的三角形,但在應該被遮蓋的三角形交叉點處重新着色。這後一種方法是我實現下,使用現有的Python函數來獲取通過薩瑟蘭-Hodgman多邊形裁剪算法的交集:
import math
from itertools import cycle
from turtle import Turtle, Screen
COLORS = cycle(['red', 'green', 'blue', 'yellow'])
def clip(subjectPolygon, clipPolygon):
# obtain this code from:
# https://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping#Python
return outputList
def rotate_polygon(polygon, angle):
theta = math.radians(angle)
sin, cos = math.sin(theta), math.cos(theta)
return [(x * cos - y * sin, x * sin + y * cos) for x, y in polygon]
def fill_polygon(turtle, polygon, color):
turtle.color(color)
for vertex in polygon:
turtle.goto(vertex)
if not turtle.filling():
turtle.begin_fill()
turtle.end_fill()
# triangle cursor 5x in size and X translated 50 pixels
polygon = ((100, -28.85), (50, 57.75), (0, -28.85))
screen = Screen()
yertle = Turtle(visible=False)
yertle.speed('slowest') # slowly so we can see redrawing
yertle.penup()
polygons = []
POLYGON, COLOR = 0, 1
for angle in range(0, 360, 30):
rotated_polygon = rotate_polygon(polygon, angle)
color = next(COLORS)
fill_polygon(yertle, rotated_polygon, color)
polygons.append((rotated_polygon, color))
# The -3 here is empirical and really should be calculated, an exercise for the reader
for forward, backward in enumerate(range(-3, 1 - len(polygons), -1)):
if polygons[forward] != polygons[backward]:
try:
intersection_polygon = clip(rotated_polygon, polygons[forward][POLYGON])
except (IndexError, ZeroDivisionError):
break # because clip() can throw an error when no intersection
if intersection_polygon:
fill_polygon(yertle, intersection_polygon, polygons[forward][COLOR])
else:
break # if no intersection, don't look any further
else:
break # avoid testing against polygons clockwise from this one (needs work)
screen.exitonclick()
輸出
這是因爲'turtle'把每個形狀在最後。你將不得不重繪第一個形狀的一部分來重疊最後一個形狀。 (另外:你的帖子可能並不完全清楚,如果你發佈了一些截圖,這可能會有所幫助) –