Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_streaking_fireworks.py
- import tkinter as tk
- from PIL import Image, ImageDraw, ImageTk, ImageChops
- import time
- import random
- import math
- root = tk.Tk()
- root.title("Fireworks")
- ww = 400
- hh = 400
- root.geometry(f"{ww}x{hh}+0+0")
- canvas = tk.Canvas(root, width=ww, height=hh, bg='black')
- canvas.pack()
- fireworks = []
- gravity = 0.03
- def create_firework():
- r = random.randint(0, 255)
- g = random.randint(0, 255)
- b = min(255, max(0, 500 - r - g))
- x = random.randint(50, ww - 50)
- y = hh
- angle = random.uniform(1.2, 0.7)
- if x > ww // 2:
- angle *= -1
- firework = {
- 'x': x,
- 'y': y,
- 'exploded': False,
- 'angle': angle,
- 'color': (r, g, b),
- 'peak': random.randint(100, 300),
- 'particles': []
- }
- fireworks.append(firework)
- def update():
- for firework in fireworks[::-1]:
- if not firework['exploded']:
- firework['y'] -= 5
- firework['x'] += firework['angle']
- render(firework)
- if firework['y'] <= firework['peak']:
- firework['exploded'] = True
- explode(firework)
- else:
- if firework['particles']:
- for i in range(len(firework['particles']) - 1, -1, -1):
- particle = firework['particles'][i]
- particle['color'] = [max(0, i - 3) for i in particle['color']]
- particle['y'] += particle['y0'] * 3
- particle['x'] += particle['x0'] * 3
- particle['y'] += particle['gravity']
- particle['x'] += random.choice([-0.1, 0.1])
- particle['gravity'] += gravity
- render(particle)
- if sum(particle['color']) < 20:
- firework['particles'].pop(i)
- else:
- fireworks.remove(firework)
- def explode(firework):
- for _ in range(25):
- angle = random.uniform(0, 2 * math.pi)
- distance = random.uniform(0, 1.0)
- x_offset = distance * math.cos(angle)
- y_offset = distance * math.sin(angle)
- particle = {
- 'x': firework['x'],
- 'y': firework['y'],
- 'x0': x_offset,
- 'y0': y_offset,
- 'gravity': gravity,
- 'color': firework['color'],
- }
- firework['particles'].append(particle)
- def random_rgb_hex(rgb):
- return '#{:02x}{:02x}{:02x}'.format(*rgb)
- def render(firework):
- color = random_rgb_hex(firework['color'])
- draw.ellipse((firework['x'], firework['y'], firework['x'] + 5, firework['y'] + 5), fill=color)
- timer = 0
- fade = Image.new("RGBA", (ww, hh), (0, 0, 0, 0))
- image = Image.new("RGBA", (ww, hh), (0, 0, 0, 0))
- while 1:
- canvas.delete('all')
- draw = ImageDraw.Draw(image)
- update()
- if timer < time.time():
- timer = time.time() + random.uniform(0.5, 5)
- if len(fireworks) < 3:
- create_firework()
- photo_image = ImageTk.PhotoImage(image)
- canvas.create_image(0, 0, anchor=tk.NW, image=photo_image)
- root.update()
- image = ImageChops.blend(image, fade, 0.009)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement