圣诞节教你用Python绘制爱心圣诞树

Selena ·
更新时间:2024-09-21
· 1492 次阅读

心血来潮的一个想法,分享一下代码

代码

# -*- coding: utf-8 -*- """ Created on Sat Dec 12 12:29:09 2020 @author: haoyu """ import turtle as t import 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 = 100 t.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 = 5 stars = 1 for i in range(height): print((' ' * (height - i)) + ('*' * stars)) stars += 2 print((' ' * 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 = 0 for 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绘制爱心圣诞树的文章就介绍到这了,更多相关Python圣诞树内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



用python 爱心 圣诞节 圣诞树 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号