Python Turtle 绘制多种复杂烟花效果示例代码
时间: 2025-01-01 21:23:06 浏览: 166
### Python Turtle 实现复杂烟花效果
为了实现更加复杂的烟花效果,可以在基础版本上增加更多特性,比如多层爆炸、渐变色彩以及随机化参数等。下面是一个增强版的例子:
```python
import turtle
import random
from math import sin, cos, radians
def setup_screen():
screen = turtle.Screen()
screen.bgcolor('black')
screen.title("Complex Fireworks Show")
def draw_firework(x, y):
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
# Randomly choose a color and set up the initial position.
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
chosen_color = random.choice(colors)
t.penup()
t.goto(x, y)
t.pendown()
# Draw multiple layers of explosion with varying sizes and angles.
for layer in range(3): # Three layers for complexity.
angle_step = 360 / (random.randint(12, 24)) # Varying number of petals per layer.
size_factor = (layer + 1) * 2
for degree in range(int(360/angle_step)):
radian_angle = radians(degree * angle_step)
if layer % 2 == 0:
current_color = chosen_color
else:
other_colors = list(set(colors)-set([chosen_color]))
current_color = random.choice(other_colors)
t.color(current_color)
t.setheading(radian_angle*180/pi)
t.forward(size_factor * 50*sin(radian_angle))
t.backward(size_factor * 50*cos(radian_angle))
t.clear() # Clear previous layer before drawing next one.
def main():
setup_screen()
fireworks_count = 7
for _ in range(fireworks_count):
x_pos = random.uniform(-300, 300)
y_pos = random.uniform(-200, 200)
draw_firework(x_pos, y_pos)
if __name__ == '__main__':
main()
```
此代码通过引入额外的循环和条件语句来构建多层次的烟花图案,并且每一层都具有不同的角度分布和颜色变化[^1]。
阅读全文
相关推荐

















