Draw the flag with Python

We were born under the red flag and grew up in the spring breeze. When the people have faith, the country has strength.

Use python (turlte library) to draw our five-star red flag.

import turtle
import math

t = turtle.Pen()
width = 1000
height = 700
t.speed(6)
# 设置画笔的绘制速度 值为 --> 1(慢)-->10(快) ,0为最快
t.screen.title('祖国万岁')
# 设置图画的名称
t.screen.setup(width, height)
# 设置画布的大小 宽 高 (正好等于五星红旗的 宽高)
t.screen.bgcolor('red')
# 设置画布的颜色,此处设为五星红旗的底色红色
t.fillcolor('yellow')
# 五角星的填充颜色
t.pencolor('yellow')
# 画笔颜色 和五角星颜色一致


# 计算不同直径外接圆的五角星的边长(比如6) 当被调用的时候直接返回结果(具体的边长)
def side_length(diameter):  # diameter:直径
    return math.sin(math.radians(72)) * diameter * 30


# 将画布平均分为 宽30个单位正方形  高20个单位正方形 的坐标参考系
# 计算每一个小正方形格子的实际宽度 用以移动画笔 当被调用的时候直接返回结果
def scale(diameter):  # scale:比例尺   diameter代表格子数(五角星外接圆的直径)
    return width / 30 * diameter  # width/30代表每一个格子的实际长度


# 绘制不同大小的五角星 每个五角星的画法轨迹是一样的
def star(diameter, angle):
    # star:星星  第一个参数代表五角星的外接圆直径 第二个代表画笔旋转角度
    t.setheading(angle)
    # 当画笔来到某个五角星的中心点后,对画笔的指向进行调整,以使小五角星一角指向大五角星的中心
    t.forward(scale(diameter) / 2)
    # 画笔从五角星的中心点前进到五角星的起始绘制点 距离为外接圆直径的一半 所以要除以2
    t.setheading(angle - 180)
    # 使画笔指向180°反转 本来都是向左的 现在调成向右
    t.left(18)
    # 画笔再次进行微调18度(五角星内角的一半) 准确指向将要开始绘制第一条边的方向
    t.begin_fill()
    # 准备颜色填充  填充将要绘制出的五角星
    for i in range(5):
        t.forward(side_length(diameter))
        t.right(144)
    t.end_fill()  # 颜色填充 直到结束


def spin(x, y):
    # spin:旋转 主要是为了4个小五角星都有1个角都能对准大五角星的中心
    return math.degrees(math.atan2(x, y))


def national_flag(x, y, z, h):
    # x:从往左移格数 y:往上移格数 z:五角星直径 h:画笔旋转角度
    t.up()
    t.goto(-scale(x), scale(y))
    t.down()
    star(z, h)


national_flag(10, 5, 6, 180 - 18)
# (五角星中心点位置:从画布中心左移距离,上移格数,尺寸,画笔旋转角度)
national_flag(5, 8, 2, spin(3, 5) + 180)
# 第一个小五角星
national_flag(3, 6, 2, spin(1, 7) + 180)
# 第二个小五角星
national_flag(3, 3, 2, 180 - spin(2, 7))
# 第三个小五角星
national_flag(5, 1, 2, 180 - spin(4, 5))
# 第四个小五角星

t.hideturtle()
turtle.done()

Guess you like

Origin blog.csdn.net/Z_CH8648/article/details/126920089