Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_gradientify2.py
- import tkinter as tk
- import random
- import time
- # Constants
- WIDTH, HEIGHT = 600, 600
- CELL_SIZE = 15
- GRID_SIZE = WIDTH // CELL_SIZE
- num_steps = GRID_SIZE**2
- step_size = (256**3) // (num_steps - 1)
- root = tk.Tk()
- canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
- root.geometry("%dx%d+-10+0"%(WIDTH, HEIGHT))
- canvas.pack()
- def convert_int_to_rgb(value):
- b = value % 256
- value //= 256
- g = value % 256
- value //= 256
- r = value % 256
- return (r, g, b)
- COLORS = []
- steps = 0
- while len(COLORS) < num_steps:
- COLORS.append(convert_int_to_rgb(steps))
- steps += step_size
- COLORS[-1] = (255, 255, 255)
- def color_difference(color1, color2):
- return sum(abs(a - b) for a, b in zip(color1, color2))
- def find_best_neighbor(x, y):
- current_color = grid[x][y]
- best_neighbor = None
- target = (x, y)
- min_difference = float('inf')
- reason = ""
- 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 = grid[dx][dy]
- difference = color_difference(current_color, neighbor_color)
- if difference < min_difference:
- min_difference = difference
- best_neighbor = (x2, y2)
- target = (dx, dy)
- except:
- 0
- return best_neighbor, target, reason
- def plot():
- for y in range(GRID_SIZE):
- for x in range(GRID_SIZE):
- color = "#{:02x}{:02x}{:02x}".format(*grid[x][y])
- canvas.create_rectangle(x * CELL_SIZE, y * CELL_SIZE,
- (x + 1) * CELL_SIZE, (y + 1) * CELL_SIZE,
- fill=color, outline="", tags=("colors"))
- # Initialize the grid with random colors
- grid = [[COLORS.pop() for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]
- XYo = []
- for y in range(GRID_SIZE):
- for x in range(GRID_SIZE):
- XYo += [(x, y)]
- delay = 1
- plot()
- while 1:
- random.shuffle(XYo)
- for x, y in XYo:
- best_neighbor, target, reason = find_best_neighbor(x, y)
- if best_neighbor:
- nx, ny = best_neighbor
- dx, dy = target
- grid[x][y], grid[nx][ny] = grid[nx][ny], grid[x][y]
- canvas.delete("swap")
- canvas.delete("colors")
- plot()
- canvas.update()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement