python写一个星空浪漫表白烟花代码
时间: 2023-08-25 15:34:55 浏览: 411
好的,下面是一个用 Python 编写的星空浪漫表白烟花代码:
```python
import turtle
import random
# 设置画布大小
turtle.setup(800, 600)
# 设置画笔颜色和大小
turtle.pensize(3)
turtle.colormode(255)
# 定义函数绘制烟花
def draw_firework(x, y):
# 随机生成烟花颜色
r = random.randint(100, 255)
g = random.randint(100, 255)
b = random.randint(100, 255)
turtle.pencolor(r, g, b)
# 随机生成烟花形状
shape = random.randint(1, 4)
if shape == 1: # 圆形
size = random.randint(30, 50)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.circle(size)
elif shape == 2: # 方形
size = random.randint(30, 50)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
for i in range(4):
turtle.forward(size)
turtle.right(90)
elif shape == 3: # 三角形
size = random.randint(30, 50)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
for i in range(3):
turtle.forward(size)
turtle.right(120)
else: # 线条
size = random.randint(50, 100)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.forward(size)
# 绘制星空背景
turtle.penup()
turtle.goto(-400, 300)
turtle.pendown()
turtle.pencolor(255, 255, 255)
turtle.begin_fill()
for i in range(2):
turtle.forward(800)
turtle.right(90)
turtle.forward(600)
turtle.right(90)
turtle.end_fill()
# 绘制星星
for i in range(50):
x = random.randint(-400, 400)
y = random.randint(-200, 200)
size = random.randint(1, 3)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.pencolor(255, 255, 255)
turtle.begin_fill()
for j in range(5):
turtle.forward(size * 10)
turtle.right(144)
turtle.end_fill()
# 绘制烟花
for i in range(50):
x = random.randint(-400, 400)
y = random.randint(-200, 200)
draw_firework(x, y)
# 隐藏画笔
turtle.hideturtle()
# 等待用户关闭窗口
turtle.done()
```
这个代码会在画布上绘制一个星空背景,并随机生成多个星星和烟花效果,让整个场景更加浪漫。你可以运行这个代码,尝试一下效果。
阅读全文