Advertisement
here2share

# tk_Gradient_Life.py

May 14th, 2024
1,000
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. # tk_Gradient_Life.py
  2.  
  3. import tkinter as tk
  4. import random
  5. import math
  6.  
  7. ww, hh = 600, 600
  8.  
  9. root = tk.Tk()
  10. root.title("Gradient Life")
  11. canvas = tk.Canvas(root, width=ww, height=hh, bg="black")
  12. canvas.pack()
  13.  
  14. CELL_SIZE = 10
  15. GRID_WIDTH = ww // CELL_SIZE
  16. GRID_HEIGHT = hh // CELL_SIZE
  17. SPEED = 1
  18.  
  19. r = 255
  20. g = 255
  21. b = 0
  22. rgb = []
  23. idx = {}
  24. for i in range(200):
  25.     r -= 1
  26.     g -= 1.2
  27.     b += 1.2
  28.     rgb.append('#{0:02x}{1:02x}{2:02x}'.format(*tuple(int(i) for i in (r, g, b))))
  29.     idx[rgb[-1]] = i
  30. L = len(rgb)
  31.  
  32. DEFAULT_GRID = [[rgb[-1] for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
  33.  
  34. grid = rgb * (GRID_WIDTH * GRID_HEIGHT // L)
  35. grid = grid[:GRID_WIDTH*GRID_HEIGHT]
  36. random.shuffle(grid)
  37. grid = [grid[i:i+GRID_WIDTH] for i in range(0, GRID_WIDTH*GRID_HEIGHT, GRID_HEIGHT)]
  38.  
  39. while 1:
  40.     canvas.delete("all")
  41.     new_grid = DEFAULT_GRID[:]
  42.     for y in range(GRID_HEIGHT):
  43.         for x in range(GRID_WIDTH):
  44.             i = idx[grid[y][x]]
  45.             if i < 100:
  46.                 for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
  47.                     ny, nx = (y + dy) % GRID_HEIGHT, (x + dx) % GRID_WIDTH
  48.                     if idx[grid[ny][nx]] > L-2:
  49.                         new_grid[ny][nx] = rgb[0]
  50.                         break
  51.  
  52.             if i < L-1:
  53.                 new_grid[y][x] = rgb[i+1]
  54.             color = new_grid[y][x]
  55.             canvas.create_rectangle(
  56.                 x * CELL_SIZE, y * CELL_SIZE,
  57.                 (x + 1) * CELL_SIZE, (y + 1) * CELL_SIZE,
  58.                 fill=color, outline=color
  59.             )
  60.  
  61.     grid = new_grid
  62.     root.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement