千家信息网

怎么用Python绘制爱心圣诞树

发表于:2024-09-24 作者:千家信息网编辑
千家信息网最后更新 2024年09月24日,这篇文章主要介绍了怎么用Python绘制爱心圣诞树,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。代码# -*- coding: utf
千家信息网最后更新 2024年09月24日怎么用Python绘制爱心圣诞树

这篇文章主要介绍了怎么用Python绘制爱心圣诞树,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

代码

# -*- coding: utf-8 -*-"""Created on Sat Dec 12 12:29:09 2020@author: haoyu"""import turtle as timport random# 爱心函数# 将爱心分为两个半圆与一个正方形# r为半圆半径,l = 2r为正方形边长# 调整半径即可调整爱心大小def loving_heart(r):    l = 2 * r    t.left(45)    t.forward(l)    t.circle(r, 180)    t.right(90)    t.circle(r, 180)    t.forward(l)# 树函数(递归)def tree(d, s):    if d <= 0:        return    t.forward(s)    tree(d - 1, s * .8)    t.right(120)    tree(d - 3, s * .5)    t.right(120)    tree(d - 3, s * .5)    t.right(120)    t.backward(s) #回退函数     #画爱心部分t.penup()t.goto(0,200) #设置起点位置t.pendown()t.pencolor('pink') #设置画笔颜色t.color('pink') t.begin_fill() #对图形进行填充loving_heart(20) #执行画爱心函数t.end_fill()#画树部分n = 100t.speed('fastest')#t.Turtle().screen.delay(0)t.right(225)t.color("dark green")t.backward(n * 4.8)tree(15, n)t.backward(n / 5)#绘制落叶for i in range(200):    a = 200 - 400 * random.random()    b = 10 - 20 * random.random()    t.up()    t.forward(b)    t.left(90)    t.forward(a)    t.down()    if random.randint(0, 1) == 0:        t.color('tomato')    else:        t.color('wheat')    t.circle(2)    t.up()    t.backward(a)    t.right(90)    t.backward(b)t.hideturtle()

结果

参考:https://www.cnblogs.com/felixwang2/p/10177515.html

介绍下其他方法如何用Python画一个圣诞树呢?

最简单:

height = 5stars = 1for i in range(height):    print((' ' * (height - i)) + ('*' * stars))    stars += 2print((' ' * height) + '|')

效果:

哈哈哈哈,总有一种骗了大家的感觉。

其实本文是想介绍Turtle库来画圣诞树。

方法:

 import turtle screen = turtle.Screen() screen.setup(800,600) circle = turtle.Turtle() circle.shape('circle') circle.color('red') circle.speed('fastest') circle.up() square = turtle.Turtle()square.shape('square')square.color('green')square.speed('fastest')square.up()circle.goto(0,280)circle.stamp()k = 0for i in range(1, 17):    y = 30*i   for j in range(i-k):       x = 30*j      square.goto(x,-y+280)       square.stamp()      square.goto(-x,-y+280)       square.stamp()   if i % 4 == 0:      x = 30*(j+1)      circle.color('red')      circle.goto(-x,-y+280)        circle.stamp()        circle.goto(x,-y+280)       circle.stamp()       k += 2    if i % 4 == 3:        x = 30*(j+1)       circle.color('yellow')        circle.goto(-x,-y+280)      circle.stamp()       circle.goto(x,-y+280)       circle.stamp()square.color('brown')for i in range(17,20):    y = 30*i   for j in range(3):       x = 30*j        square.goto(x,-y+280)       square.stamp()        square.goto(-x,-y+280)        square.stamp()turtle.exitonclick()

效果:

感谢你能够认真阅读完这篇文章,希望小编分享的"怎么用Python绘制爱心圣诞树"这篇文章对大家有帮助,同时也希望大家多多支持,关注行业资讯频道,更多相关知识等着你来学习!

0