Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_crowded_random_walk.py
- from PIL import Image, ImageDraw, ImageTk
- import tkinter as tk
- import math
- import random
- ww = 600
- hh = 600
- particle_size = 5
- root = tk.Tk()
- root.title("tk_crowded_random_walk")
- root.geometry(f"{ww}x{hh}+10+10")
- canvas = tk.Canvas(root, width=ww, height=hh)
- canvas.pack()
- img = Image.new('RGB', (ww, hh), color='white')
- draw = ImageDraw.Draw(img)
- COLORS = [
- (255, 0, 0), # Red
- (255, 165, 0), # Orange
- (255, 255, 0), # Yellow
- (0, 128, 0), # Green
- ]
- def initialize_particles():
- particles = {}
- for y in range(0, hh, 20):
- for x in range(0, ww, 20):
- color = random.choice(COLORS)
- particles[(x, y)] = color
- return particles
- particles = initialize_particles()
- def update_particles(): # angle for fluid motion potentially in next project
- new_particles = {}
- for (x, y), color in particles.items():
- angle = random.uniform(0, 2*math.pi)
- dx = int(math.cos(angle) * particle_size)
- dy = int(math.sin(angle) * particle_size)
- new_pos = (x + dx, y + dy)
- if 0 <= new_pos[0] < ww and 0 <= new_pos[1] < hh:
- new_particles[new_pos] = color
- else:
- new_particles[(x, y)] = color
- return new_particles
- def draw_particles():
- for (x, y), color in particles.items():
- draw.rectangle([(x, y), (x + particle_size, y + particle_size)], fill=color)
- while True:
- particles = update_particles()
- draw_particles()
- photo = ImageTk.PhotoImage(img)
- canvas.create_image(0, 0, anchor=tk.NW, image=photo)
- root.update()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement