用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()

 

 

运行后效果:

 

posted @ 2020-06-13 08:07  Only-W  阅读(2095)  评论(0编辑  收藏  举报