少儿学编程系列 --- 如何使用 turtle 画风车
发布于: 2021 年 02 月 22 日

介绍
"大风车吱呀吱哟哟地转,这里的风景呀真好看,天好看,地好看,还有一起快乐的小伙伴,大风车转啊转悠悠,快乐的伙伴手牵着手,牵着你的手,牵着我的手,今天的小伙伴,明天的好朋友,好朋友"
小时候,一到晚上,就安静的坐在电视机前,看大风车电视节目。今天我们就使用 turtle 来画大风车
思路
画大风车的思路如下:
画多边形,然后从多边形的各个顶点到中心画 spiral(螺旋), 最后填充颜色即可。
效果
 
 源代码
from turtle import *import mathfrom random import *
def draw_spiral(x, y, r, direction, num = 4,alpha=5):    pensize(1)    if r < 10: return    d = direction    r_ratio = math.cos(math.radians(36)) / math.cos(math.radians(36 - alpha))    d_ratio = math.sin(math.radians(36)) - r_ratio * math.sin(math.radians(36 - alpha))    lastpx = -1;    lastpy = -1;    firstpx = 0;    firstpy = 0;    lastcolor='red';    for i in range(num):        color = colors[randint(0, 7) % 8]        while(lastcolor == color):            color = colors[randint(0, 7) % 8]        lastcolor = color
        fillcolor(color)        up()        if (lastpx != -1):            goto(lastpx, lastpy)        down()        px = x + r * math.cos(math.radians(d))        py = y + r * math.sin(math.radians(d))        print(px, py, lastpx, lastpy)        lastpx = px;        lastpy = py;        if i == 0:            firstpx = px;            firstpy = py;
        pencolor(color)        if (i == 0):            up()        goto(px, py)        down()        seth(d + 180 - 54)        dist = r * d_ratio        r2 = r        begin_fill()        while dist > 0.1:            fd(dist)            r2 = r2 * r_ratio            dist = r2 * d_ratio            left(alpha)        d += 360 / num        end_fill()    up()    goto(px, py)    down()    goto(firstpx, firstpy)    up()    goto(firstpx, firstpy - r)    down()    pencolor("#652e15")    pensize(5)    pencolor("black")    goto(firstpx, firstpy - r * 3)
colors = ["red", "purple", "blue", "green", "orange", "yellow", "white", "black"]if __name__ == '__main__':    screen = Screen()    screen.setup(800, 600)    screen.title('今日头条-cloudcoder出品')    speed("fastest")    # hideturtle()    screen.tracer(-1, 0)    bgcolor('#9ebdeb')    for h in range(2):        for i in range(4):            draw_spiral(-300 + i * 170, 200 - h * 250, 80, 90,randint(4,6))    done()复制代码
 划线
评论
复制
发布于: 2021 年 02 月 22 日阅读数: 22
版权声明: 本文为 InfoQ 作者【cloudcoder】的原创文章。
原文链接:【http://xie.infoq.cn/article/9c9428eeab81d8bcb37257224】。文章转载请联系作者。
cloudcoder
关注
10+IT行业老兵,熟悉大数据处理,分布式编程 2020.10.30 加入
InfoQ主页:https://www.infoq.cn/u/cloudcoder 头条主页: https://www.toutiao.com/c/user/token/MS4wLjABAAAAgqsp3gTUFRwr49uODP0W6XdaDB2vI5d_9yPDC1Nzmds/











 
    
评论