2016-10-22 182 views
0

我認爲(假設)如果形狀是「關閉」,begin_fill()/ end_fill()命令只會「填充」一個形狀。考慮以下幾點: 進口龜Python龜圖形填充非封閉多邊形

turtle.color("red") 
turtle.begin_fill() 
turtle.forward(100) 
turtle.left(90) 
turtle.forward(100) 
turtle.end_fill() 

Python的完成圖,填補它 - 這是不是我想要的。我如何確保只有一個封閉的多邊形會被填充?

回答

0

我想我們可以繼承龜和改變規則:

from turtle import Turtle, Screen 

class Yertle(Turtle): 
    def end_fill(self): 
     if len(self._fillpath) > 3 and self._fillpath[0] == self._fillpath[-1]: 
      super().end_fill() # warning, Python3 syntax! 
     else: 
      self.end_poly() 

現在我們可以這樣做:

turtle = Yertle() 
screen = Screen() 

turtle.color("red") 

turtle.begin_fill() 
turtle.forward(100) 
turtle.left(90) 
turtle.forward(100) 
turtle.end_fill() 

turtle.penup() 
turtle.home() 
turtle.pendown() 

turtle.color("green") 

turtle.begin_fill() 
turtle.backward(100) 
turtle.right(90) 
turtle.backward(100) 
turtle.home() 
turtle.end_fill() 

screen.exitonclick() 

enter image description here

警告,該解決方案是脆弱!它取決於在未來版本中可能會改變的底層實現的知識。但是,如果你絕對必須擁有它......

+0

所以你告訴我,我需要定義一個類來做我認爲是「正常」操作的類,即只填充一個形狀關閉? – Simon

+0

@Simon,你的模型可能不是每個人的常態 - 有些人可能會認爲'begin_fill()'和'end_fill()'實際上會填充某些東西。我同意這是一個文檔缺陷,'end_poly()'提到自動連接返回到第一個頂點,而'end_fill()'沒有。也許它應該是一個可選的標誌來設置。但是,您使用的是OOP語言,修復此問題所需的類很少,並且可以與您的代碼放在同一個文件中。這就是OOP的一個要點,即覆蓋默認行爲的能力。 – cdlane

+0

謝謝,我會做相應的調整。我可能應該在一開始就提到我的職業 - 我是一名教師。當我給一個任務繪製一個形狀並填充它時,我想確保程序能夠正常工作,因爲學生已經正確計算了距離和角度,而不是因爲Python的慷慨。 – Simon