Python使⽤Turtle模块绘制五星红旗代码⽰例
在Udacity上课时学到了python的turtle⽅法,这是⼀个很经典的⽤来教⼩孩⼉编程的图形模块,最早起源于logo语⾔。python 本⾝内置了这个模块,其可视化的⽅法可以帮助⼩孩⼉对编程的⼀些基本理念有所理解。
在作业提交的论坛⾥看到很多turtle画出来的精美图形,想不出什么要画的东西,于是决定拿五星红旗来练练⼿。
前期准备
五星红旗绘制参数
Turtle官⽅⽂档
turtle的基本操作
# 初始化屏幕
window = turtle.Screen()
# 新建turtle对象实例
import turtle
aTurtle = turtle.Turtle()
# 海龟设置
aTurtle.hideturtle() # 隐藏箭头
aTurtle.speed(10) # 设置速度
# 前进后退,左转右转
aTurtle.fd(100) # 前进100像素
aTurtle.right(90) # 右转90°
aTurtle.back(100)
aTurtle.left(90)
# 填充颜⾊
aTurtle.begin_fill()
aTurtle.fillcolor('yellow')
DoSomethinghere()
# 抬起笔和放下笔,这样进⾏的操作不会留下痕迹
aTurtle.penup()
<(start_pos)
aTurtle.fd(radius)
aTurtle.pendown()
绘制五星红旗代码
#!/usr/bin/env python
# -*- coding: utf-8 –*-
''' 对于turtle类的⼀些封装⽅法,包括画正多边形,正多⾓形和五星红旗。'''
__author__ = 'Hu Wenchao'
import turtle
import math
def draw_polygon(aTurtle, size=50, n=3):
''' 绘制正多边形
args:
aTurtle: turtle对象实例
size: int类型,正多边形的边长
n: int类型,是⼏边形
'''
for i in xrange(n):
aTurtle.forward(size)
aTurtle.left(360.0/n)
def draw_n_angle(aTurtle, size=50, num=5, color=None):
''' 绘制正n⾓形,默认为黄⾊
args:
aTurtle: turtle对象实例
size: int类型,正多⾓形的边长
n: int类型,是⼏⾓形
color: str,图形颜⾊,默认不填⾊
'''
if color:
aTurtle.begin_fill()
aTurtle.fillcolor(color)
for i in xrange(num):
aTurtle.forward(size)
aTurtle.left(360.0/num)
aTurtle.forward(size)
aTurtle.right(2*360.0/num)
if color:
def draw_5_angle(aTurtle=None, start_pos=(0,0), end_pos=(0,10), radius=100, color=None):
''' 根据起始位置、结束位置和外接圆半径画五⾓星
python新手代码示例args:
aTurtle: turtle对象实例
start_pos: int的⼆元tuple,要画的五⾓星的外接圆圆⼼
end_pos: int的⼆元tuple,圆⼼指向的位置坐标点
radius: 五⾓星外接圆半径
color: str,图形颜⾊,默认不填⾊
'''
aTurtle = aTurtle or turtle.Turtle()
size = radius * math.sin(math.pi/5)/math.sin(math.pi*2/5)
aTurtle.left(math.degrees(math.atan2(end_pos[1]-start_pos[1], end_pos[0]-start_pos[0])))
aTurtle.penup()
<(start_pos)
aTurtle.fd(radius)
aTurtle.pendown()
aTurtle.right(math.degrees(math.pi*9/10))
draw_n_angle(aTurtle, size, 5, color)
def draw_5_star_flag(times=20.0):
''' 绘制五星红旗
args:
times: 五星红旗的规格为30*20, times为倍数,默认⼤⼩为10倍,即300*200
'''
width, height = 30*times, 20*times
# 初始化屏幕和海龟
window = turtle.Screen()
aTurtle = turtle.Turtle()
aTurtle.hideturtle()
aTurtle.speed(10)
# 画红旗
aTurtle.penup()
<(-width/2, height/2)
aTurtle.pendown()
aTurtle.begin_fill()
aTurtle.fillcolor('red')
aTurtle.fd(width)
aTurtle.right(90)
aTurtle.fd(height)
aTurtle.right(90)
aTurtle.fd(width)
aTurtle.right(90)
aTurtle.fd(height)
aTurtle.right(90)
# 画⼤星星
draw_5_angle(aTurtle, start_pos=(-10*times, 5*times), end_pos=(-10*times, 8*times), radius=3*times, color='yellow')
# 画四个⼩星星
stars_start_pos = [(-5, 8), (-3, 6), (-3, 3), (-5, 1)]
for pos in stars_start_pos:
draw_5_angle(aTurtle, start_pos=(pos[0]*times, pos[1]*times), end_pos=(-10*times, 5*times), radius=1*times, color='yellow') # 点击关闭窗⼝
if __name__ == '__main__':
draw_5_star_flag()
结果:
总结
以上就是本⽂关于Python使⽤Turtle模块绘制五星红旗代码⽰例的全部内容,希望对⼤家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不⾜之处,欢迎留⾔指出。感谢朋友们对本站的⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论