Advertisement
here2share

# tk_Langtons_Ant_Color_Gradient.py

May 4th, 2025
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. # tk_Langtons_Ant_Color_Gradient.py
  2.  
  3. import tkinter as tk
  4.  
  5. WW, HH = 600, 600
  6.  
  7. root = tk.Tk()
  8. root.geometry(f"{WW}x{HH}+0+0")
  9. canvas = tk.Canvas(root, width=WW, height=HH, bg="white")
  10. canvas.pack()
  11.  
  12. GRID_SIZE = 10
  13. ROWS, COLS = HH // GRID_SIZE, WW // GRID_SIZE
  14.  
  15. grid = [[0] * COLS for _ in range(ROWS)]
  16. ant_x, ant_y = ROWS // 2, COLS // 2
  17. ant_direction = 0  # 0: up, 1: right, 2: down, 3: left
  18. painting = {}
  19.  
  20. r, g, b = 128, 0, 0
  21. color_step = 15
  22.  
  23. while True:
  24.     grid[ant_x][ant_y] ^= 1
  25.  
  26.     try:
  27.         r0, g0, b0 = painting[ant_x, ant_y]
  28.     except:
  29.         r0, g0, b0 = 128, 0, 0
  30.  
  31.     if ant_direction == 0:
  32.         r = (r + color_step) % 512
  33.     elif ant_direction == 1:
  34.         g = (g + color_step) % 512
  35.     elif ant_direction == 2:
  36.         b = (b + color_step) % 512
  37.     elif ant_direction == 3:
  38.         r = (r + color_step) % 512
  39.         g = (g + color_step) % 512
  40.         b = (b + color_step) % 512
  41.        
  42.     painting[ant_x, ant_y] = r, g, b
  43.  
  44.     rx, gx, bx = [255 - abs(255 - i) for i in (r, g, b)]
  45.  
  46.     color = f"#{rx:02x}{gx:02x}{bx:02x}"
  47.    
  48.     r, g, b = r0, g0, b0
  49.  
  50.     canvas.create_rectangle(ant_x * GRID_SIZE, ant_y * GRID_SIZE,
  51.                             (ant_x + 1) * GRID_SIZE, (ant_y + 1) * GRID_SIZE,
  52.                             fill=color, outline="")
  53.  
  54.     if grid[ant_x][ant_y]:  # White -> Right turn
  55.         ant_direction = (ant_direction + 1) % 4
  56.     else:  # Black -> Left turn
  57.         ant_direction = (ant_direction - 1) % 4
  58.  
  59.     if ant_direction == 0:
  60.         ant_x -= 1
  61.     elif ant_direction == 1:
  62.         ant_y += 1
  63.     elif ant_direction == 2:
  64.         ant_x += 1
  65.     elif ant_direction == 3:
  66.         ant_y -= 1
  67.  
  68.     ant_x %= ROWS
  69.     ant_y %= COLS
  70.  
  71.     root.update()
  72.  
  73. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement