烟花代码编程python

以下是一个简单的烟花代码编程示例,使用Python的turtle库绘制烟花效果:

import turtle
import random

# 设置画布大小
turtle.setup(800, 600)

# 创建画笔
pen = turtle.Turtle()
pen.speed(0)
pen.hideturtle()

# 定义烟花函数
def firework():
    # 设置画笔颜色
    colors = ["red", "orange", "yellow", "green", "blue", "purple"]
    pen.color(random.choice(colors))
    
    # 设置画笔起始位置
    x = random.randint(-400, 400)
    y = random.randint(-300, 300)
    pen.penup()
    pen.goto(x, y)
    pen.pendown()
    
    # 绘制烟花
    for _ in range(30):
        pen.forward(random.randint(10, 100))
        pen.right(random.randint(0, 360))
    
    # 清除烟花轨迹
    pen.clear()

# 循环绘制烟花
while True:
    firework()

运行以上代码,将会在窗口中不断绘制随机颜色的烟花效果。你可以根据需要调整画布大小、烟花的数量和颜色等参数。

当然,还可以进一步完善烟花代码,添加更多的效果和交互性。以下是一个更复杂的烟花代码编程示例,使用Python的turtle库和tkinter库:

import turtle
import random
import tkinter as tk

# 创建主窗口
root = tk.Tk()
root.title("Fireworks")
root.geometry("800x600")

# 创建画布
canvas = tk.Canvas(root, width=800, height=600)
canvas.pack()

# 创建画笔
pen = turtle.RawTurtle(canvas)
pen.speed(0)
pen.hideturtle()

# 定义烟花类
class Firework:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.color = color
        self.pen = turtle.RawTurtle(canvas)
        self.pen.speed(0)
        self.pen.hideturtle()
        self.pen.penup()
        self.pen.goto(x, y)
        self.pen.pendown()
    
    def explode(self):
        self.pen.color(self.color)
        for _ in range(30):
            self.pen.forward(random.randint(10, 100))
            self.pen.right(random.randint(0, 360))
        self.pen.clear()

# 创建烟花列表
fireworks = []

# 定义点击事件处理函数
def fire(event):
    x = event.x - 400
    y = 300 - event.y
    color = random.choice(["red", "orange", "yellow", "green", "blue", "purple"])
    firework = Firework(x, y, color)
    fireworks.append(firework)

# 绑定点击事件
canvas.bind("<Button-1>", fire)

# 定义动画函数
def animate():
    for firework in fireworks:
        firework.explode()
    fireworks.clear()
    canvas.after(100, animate)

# 启动动画
animate()

# 运行主窗口
root.mainloop()

运行以上代码,将会打开一个窗口,你可以点击窗口中的任意位置,触发烟花效果。每次点击会创建一个烟花对象,并在该位置绘制烟花效果。烟花会在窗口中不断绽放,直到消失。你可以根据需要调整窗口大小、烟花的数量和颜色等参数。