用turtle画国旗
参考了python用turtle画国旗-CSDN博客,进行了改造和图形优化
import turtle as t
import math
ratio = 2 # 比例大小
flag_width = 240 * ratio
flag_height = 160 * ratio
def mk_start(mini=False):
# 为了使中心点在原点,计算初始移动,然后向右划
radius = 24 # 圆的半径
# 角度(转换为弧度)
angle_degrees = 18
angle_radians = math.radians(angle_degrees)
# 计算 a 点的坐标(即需要移动的距离点坐标)
y = radius * math.sin(angle_radians)
x = radius * math.cos(angle_radians)
y = y / 3 if mini else y
x = x / 3 if mini else x
# 计算五角星划线长
radius = 3*8 * ratio # 直角边长
# 非直角角度(15度),将其转换为弧度
angle_degrees = 72
angle_radians = angle_degrees * math.pi / 180
# 使用正弦函数计算弦长
hypotenuse = math.sin(angle_radians) * 2 * radius
t.up()
t.goto(-x * ratio, y * ratio)
t.down()
# print(f"{flag_width / (2 * 15) * 6}::{hypotenuse}")
t.begin_poly()
t.pencolor("yellow")
for i in range(5):
t.forward(hypotenuse/3 if mini else hypotenuse)
t.right(144)
t.end_poly()
t.register_shape("start_mini" if mini else "start", t.get_poly())
def mk_frame():
t.pencolor("white")
t.up()
# print(-flag_width / 2, flag_height/2)
t.goto(-flag_width / 2, flag_height/2)
t.down()
t.begin_poly()
t.forward(flag_width)
t.right(90)
t.forward(flag_height)
t.right(90)
t.forward(flag_width)
t.right(90)
t.forward(flag_height)
t.end_poly()
t.register_shape("frame", t.get_poly())
def shape_exists(shape_name):
try:
t.shape(shape_name)
return True
except t.TurtleGraphicsError:
return False
def draw_start(x, y, heading=0.0, is_mini= False):
if is_mini:
if not shape_exists("start_mini"):
mk_start(is_mini) # 获取星形的顶点列表
else:
mk_start(is_mini) # 获取星形的顶点列表
t.reset()
t.hideturtle()
start = t.Turtle()
start.shape("start_mini" if is_mini else "start")
start.color("yellow")
start.fillcolor("yellow")
# t.dot(5, "black")
start.up()
# print(x, y)
start.goto(x, y) # 顶点的位置
# print(heading)
if heading:
start.setheading(heading)
start.down()
if __name__ == '__main__':
t.speed('fastest')
# t.tracer(0) # 关闭自动刷新
# 画框框
mk_frame()
t.reset()
t.hideturtle()
frame = t.Turtle()
frame.shape("frame")
frame.color("white")
frame.fillcolor("red")
frame.setheading(90)
# t.dot(5, "black")
draw_start(-flag_width / (2 * 15) * 10, flag_height / (2 * 10) * 5, 18)
# 小星星
# 先计算偏转角度
initial = 54 # 初始西南角角度
theta = math.degrees(math.atan(5/3)) # 目标位置的角度
draw_start(-flag_width / (2 * 15) * 5, flag_height / (2 * 10) * 8, initial-theta, True)
theta = math.degrees(math.atan(7/1)) # 目标位置的角度
draw_start(-flag_width / (2 * 15) * 3, flag_height / (2 * 10) * 6, initial-theta, True)
initial = 36 # 初始西北角角度
theta = math.degrees(math.atan(2 / 7)) # 目标位置的角度
draw_start(-flag_width / (2 * 15) * 3, flag_height / (2 * 10) * 3, initial-theta, True)
theta = math.degrees(math.atan(4 / 5)) # 目标位置的角度
draw_start(-flag_width / (2 * 15) * 5, flag_height / (2 * 10) * 1, initial-theta, True)
t.done()
运行后的效果如图