Advertisement
here2share

# Tk_erosion_2.py

Mar 27th, 2022
965
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. # Tk_erosion_2.py
  2.  
  3. from tkinter import *
  4. import time
  5. from PIL import Image, ImageTk
  6. from random import shuffle as rs, randint as ri
  7.  
  8. tx =  time.time
  9. ww = 180
  10. hh = 180
  11.  
  12. root = Tk()
  13. root.title("Tk_erosion")
  14. root.geometry("%dx%d+-6+-2"%(ww,hh))
  15. canvas = Canvas(width=ww, height=hh)
  16. canvas.pack()
  17.  
  18. def rgb2hex(r,g,b):
  19.     return '#%02X%02X%02X'%(r,g,b)
  20.    
  21. def motion(event):
  22.     mouse_pos.append((event.x, event.y))
  23. root.bind('<B1-Motion>', motion)
  24.  
  25. cols = ww
  26. rows = hh
  27.  
  28. chemicals = []
  29. i = 0
  30. for z in range(ww*hh):
  31.     chemicals += [(i+1)]
  32.     i = (i+1)%25
  33.    
  34. rs(chemicals)
  35.  
  36. rgb = []
  37. xy = {}
  38. for j in range(0,rows):
  39.     for i in range(0,cols):
  40.         xy[i,j] = len(rgb)
  41.         rgb += [(chemicals.pop())]
  42. current = rgb[:]
  43. previous = rgb[:]
  44.  
  45. mouse_pos = []
  46. image = Image.new("RGB", (ww,hh))
  47.  
  48. def draw():
  49.     image.putdata(rgb)
  50.     photo = ImageTk.PhotoImage(image)
  51.     canvas.create_image(0,0,image=photo,anchor=NW)
  52.     canvas.update()
  53.  
  54. def sides(i,j):
  55.     return ([i-1,j],[i+1,j],[i,j-1],[i,j+1])
  56.  
  57. swap = 1
  58.  
  59. #Mainloop
  60. while 1:
  61.     for i in range(1,cols-1):
  62.         for j in range(1,rows-1):
  63.             if mouse_pos:
  64.                 x,y = mouse_pos.pop(0)
  65.                 for x2,y2 in  sides(x,y):
  66.                     try:
  67.                         t = xy[x2,y2]
  68.                         chemicals += [current[t]]
  69.                         current[t] = 0
  70.                     except:
  71.                         0
  72.                        
  73.             t = xy[i,j]
  74.            
  75.             sides2 = (sum([current[xy[x,y]] for x,y in sides(i,j)])+current[t])/5
  76.             if sides2 > ri(10,12): # the magic
  77.                 current[t], swap = swap, current[t]
  78.            
  79.             if current[t] == previous[t]:
  80.                 val = current[t]*10
  81.             else:
  82.                 val = 255
  83.             rgb[t] = (val,val,val)
  84.            
  85.             previous[t] = current[t]
  86.  
  87.     # print(tx)
  88.  
  89.     draw()
  90.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement