Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_4x2_Color_Gradient_Alive.py
- from tkinter import *
- from PIL import Image, ImageTk
- import math
- import random
- import time
- root = Tk()
- root.title("# Tk_4x2_Color_Gradient_Alive")
- ww = 1200
- hh = 600
- zz = 40
- w0 = int(ww / zz)
- h0 = int(hh / zz)
- root.geometry("%dx%d+-10+0"%(ww,hh))
- canvas = Canvas(root, width=ww, height=hh)
- canvas.pack()
- colors = [(0, 0, 0), (255, 0, 0), (255, 165, 0), (255, 255, 0),
- (75, 0, 130), (0, 0, 255), (0, 128, 0), (255, 255, 255)]
- rx = (4 - 1) / ww
- ry = (2 - 1) / hh
- def bicubic(c00, c10, c01, c11, x, y):
- w00 = (1 - x) * (1 - y)
- w10 = x * (1 - y)
- w01 = (1 - x) * y
- w11 = x * y
- r = int(w00 * c00[0] + w10 * c10[0] + w01 * c01[0] + w11 * c11[0])
- g = int(w00 * c00[1] + w10 * c10[1] + w01 * c01[1] + w11 * c11[1])
- b = int(w00 * c00[2] + w10 * c10[2] + w01 * c01[2] + w11 * c11[2])
- return (r, g, b)
- def transition_color(x, y):
- x *= zz
- y *= zz
- x_ratio = x * rx
- y_ratio = y * ry
- x_index = int(x_ratio)
- y_index = int(y_ratio) * 4
- c00 = colors[x_index + y_index]
- c10 = colors[(x_index + 1) + y_index]
- c01 = colors[x_index + (y_index + 4)]
- c11 = colors[(x_index + 1) + (y_index + 4)]
- x_fraction = x_ratio - x_index
- y_fraction = y_ratio - y_index
- return bicubic(c00, c10, c01, c11, x_fraction, y_fraction)
- def color_difference(color1, color2):
- return sum(abs(a - b) for a, b in zip(color1, color2))
- def make_alive():
- current_color = rgb[xy2rgb[x, y]]
- min_difference = float('inf')
- xx, yy = x, y
- for x0, y0 in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
- x2, y2 = x0 + x, y0 + y
- ttt = [((x2 + j * x0 if x0 else x + i), (y2 + j * y0 if y0 else y + i)) for i in (-1, 0, 1) for j in [1, 2, 3]]
- for dx, dy in ttt:
- if min(dx, dy) > -1:
- try:
- neighbor_color = rgb[xy2rgb[x0, y0]]
- rgb[xy2rgb[x2, y2]] # dblchk
- difference = color_difference(current_color, neighbor_color)
- if difference < min_difference:
- min_difference = difference
- xx, yy = x2, y2
- except:
- 0
- rgb[xy2rgb[x, y]], rgb[xy2rgb[xx, yy]] = rgb[xy2rgb[xx, yy]], rgb[xy2rgb[x, y]]
- return xx, yy
- def toggle_mode(event):
- random.shuffle(rgb)
- root.bind("<space>", toggle_mode)
- img = Image.new('RGB', (ww, hh))
- img2 = Image.new('RGB', (w0, h0))
- rgb = [(128, 128, 128)] * (w0 * h0)
- xy2rgb = {}
- XYo = []
- for y in range(h0):
- for x in range(w0):
- rgb[x + y * w0] = transition_color(x, y)
- xy2rgb[x, y] = len(xy2rgb)
- XYo += [(x, y)]
- while 1:
- swapped = {}
- random.shuffle(XYo)
- for (x, y) in XYo:
- x, y = make_alive()
- img2.putdata(rgb)
- img = img2.crop((0, 0, w0, h0))
- img = img.resize((ww, hh))
- imgTk = ImageTk.PhotoImage(img)
- canvas.create_image(0, 0, anchor=NW, image=imgTk)
- root.update()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement