Advertisement
here2share

# Tk_erosion_3.py

Mar 27th, 2022
1,040
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. # Tk_erosion_3.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. screen = []
  38. xy = {}
  39. for j in range(0,rows):
  40.     for i in range(0,cols):
  41.         xy[i,j] = len(rgb)
  42.         rgb += [(chemicals.pop())]
  43.         if (0 < i < cols-1) and  (0 < j < rows-1):
  44.             screen += [(i,j)]
  45. current = rgb[:]
  46. previous = rgb[:]
  47.  
  48. mouse_pos = []
  49. image = Image.new("RGB", (ww,hh))
  50.  
  51. def draw():
  52.     image.putdata(rgb)
  53.     photo = ImageTk.PhotoImage(image)
  54.     canvas.create_image(0,0,image=photo,anchor=NW)
  55.     canvas.update()
  56.  
  57. def sides(i,j):
  58.     return ([i-1,j],[i+1,j],[i,j-1],[i,j+1])
  59.  
  60. swap = 1
  61.  
  62. #Mainloop
  63. while 1:
  64.     rs(screen)
  65.     for i,j in screen:
  66.         if mouse_pos:
  67.             x,y = mouse_pos.pop(0)
  68.             for x2,y2 in  sides(x,y):
  69.                 try:
  70.                     t = xy[x2,y2]
  71.                     chemicals += [current[t]]
  72.                     current[t] = 0
  73.                 except:
  74.                     0
  75.                    
  76.         t = xy[i,j]
  77.        
  78.         sides2 = (sum([current[xy[x,y]] for x,y in sides(i,j)])+current[t])/5
  79.         if sides2 > 12: # the magic
  80.             current[t], swap = swap, current[t]
  81.        
  82.         val = current[t]*10
  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