Advertisement
here2share

# tk_crowded_random_walk.py

Jul 11th, 2024
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. # tk_crowded_random_walk.py
  2.  
  3. from PIL import Image, ImageDraw, ImageTk
  4. import tkinter as tk
  5. import math
  6. import random
  7.  
  8. ww = 600
  9. hh = 600
  10. particle_size = 5
  11.  
  12. root = tk.Tk()
  13. root.title("tk_crowded_random_walk")
  14. root.geometry(f"{ww}x{hh}+10+10")
  15.  
  16. canvas = tk.Canvas(root, width=ww, height=hh)
  17. canvas.pack()
  18.  
  19. img = Image.new('RGB', (ww, hh), color='white')
  20. draw = ImageDraw.Draw(img)
  21.  
  22. COLORS = [
  23.     (255, 0, 0),     # Red
  24.     (255, 165, 0),   # Orange
  25.     (255, 255, 0),   # Yellow
  26.     (0, 128, 0),     # Green
  27. ]
  28.  
  29. def initialize_particles():
  30.     particles = {}
  31.     for y in range(0, hh, 20):
  32.         for x in range(0, ww, 20):
  33.             color = random.choice(COLORS)
  34.             particles[(x, y)] = color
  35.     return particles
  36.  
  37. particles = initialize_particles()
  38.  
  39. def update_particles(): # angle for fluid motion potentially in next project
  40.     new_particles = {}
  41.     for (x, y), color in particles.items():
  42.         angle = random.uniform(0, 2*math.pi)
  43.         dx = int(math.cos(angle) * particle_size)
  44.         dy = int(math.sin(angle) * particle_size)
  45.         new_pos = (x + dx, y + dy)
  46.         if 0 <= new_pos[0] < ww and 0 <= new_pos[1] < hh:
  47.             new_particles[new_pos] = color
  48.         else:
  49.             new_particles[(x, y)] = color
  50.     return new_particles
  51.  
  52. def draw_particles():
  53.     for (x, y), color in particles.items():
  54.         draw.rectangle([(x, y), (x + particle_size, y + particle_size)], fill=color)
  55.  
  56. while True:
  57.     particles = update_particles()
  58.     draw_particles()
  59.  
  60.     photo = ImageTk.PhotoImage(img)
  61.     canvas.create_image(0, 0, anchor=tk.NW, image=photo)
  62.     root.update()
  63.  
  64. root.mainloop()
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement