用turtle畫五星紅旗


如需轉載請注明原文出處:

 

 

 

 1 import turtle  2 import math  3  4 def draw_polygon(aTurtle, size=50, n=3):  5 ''' 繪制正多邊形 args: aTurtle: turtle對象實例 size: int類型,正多邊形的邊長 n: int類型,是幾邊形 '''  6 for x in range(n):  7  aTurtle.forward(size)  8 aTurtle.left(360.0/n)  9 10 def draw_n_angle(aTurtle, size=50, num=5, color=None): 11 ''' 繪制正n角形,默認為黃色 args: aTurtle: turtle對象實例 12  size: int類型,正多角形的邊長 n: int類型,是幾角形 color: str, 圖形顏色,默認不填色 ''' 13 if color: 14  aTurtle.begin_fill() 15  aTurtle.fillcolor(color) 16 for y in range(num): 17  aTurtle.forward(size) 18 aTurtle.left(360.0/num) 19  aTurtle.forward(size) 20 aTurtle.right(2*360.0/num) 21 if color: 22  aTurtle.end_fill() 23 24 def draw_5_angle(aTurtle=None, start_pos=(0,0), end_pos=(0,10), radius=100, color=None): 25 ''' 根據起始位置、結束位置和外接圓半徑畫五角星 args: aTurtle: turtle對象實例 start_pos: int的二元tuple, 26  要畫的五角星的外接圓圓心 end_pos: int的二元tuple,圓心指向的位置坐標點 radius: 五角星外接圓半徑 27  color: str,圖形顏色,默認不填色 ''' 28 aTurtle = aTurtle or turtle.Turtle() 29 size = radius * math.sin(math.pi/5)/math.sin(math.pi*2/5) 30 aTurtle.left(math.degrees(math.atan2(end_pos[1]-start_pos[1], end_pos[0]-start_pos[0]))) 31  aTurtle.penup() 32  aTurtle.goto(start_pos) 33  aTurtle.fd(radius) 34  aTurtle.pendown() 35 aTurtle.right(math.degrees(math.pi*9/10)) 36 draw_n_angle(aTurtle, size, 5, color) 37 38 def draw_5_star_flag(times=20.0): 39 ''' 繪制五星紅旗 args: times: 五星紅旗的規格為30*20, 40  times為倍數,默認大小為10倍, 即300*200 ''' 41 width, height = 30*times, 20*times 42 # 初始化屏幕和海龜 43 window = turtle.Screen() 44 aTurtle = turtle.Turtle() 45  aTurtle.hideturtle() 46 aTurtle.speed(10) 47 # 畫紅旗 48  aTurtle.penup() 49 aTurtle.goto(-width/2, height/2) 50  aTurtle.pendown() 51  aTurtle.begin_fill() 52 aTurtle.fillcolor('red') 53  aTurtle.fd(width) 54 aTurtle.right(90) 55  aTurtle.fd(height) 56 aTurtle.right(90) 57  aTurtle.fd(width) 58 aTurtle.right(90) 59  aTurtle.fd(height) 60 aTurtle.right(90) 61  aTurtle.end_fill() 62 # 畫大星星 63 draw_5_angle(aTurtle, start_pos=(-10*times, 5*times), end_pos=(-10*times, 8*times), radius=3*times, color='yellow') 64 # 畫四個小星星 65 stars_start_pos = [(-5, 8), (-3, 6), (-3, 3), (-5, 1)] 66 for pos in stars_start_pos: 67 draw_5_angle(aTurtle, start_pos=(pos[0]*times, pos[1]*times), end_pos=(-10*times, 5*times), radius=1*times, color='yellow') 68 # 點擊關閉窗口 69  window.exitonclick() 70 71 if __name__ == '__main__': 72 draw_5_star_flag()

 

 

運行后效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM