Advertisement
here2share

# tk_Langtons_Ant_9_Color.py

May 4th, 2025 (edited)
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. # tk_Langtons_Ant_9_Color.py
  2.  
  3. import tkinter as tk
  4. from PIL import Image, ImageTk
  5.  
  6. WW, HH = 600, 600
  7. GRID_SIZE = 10
  8. ROWS, COLS = HH // GRID_SIZE, WW // GRID_SIZE
  9.  
  10. root = tk.Tk()
  11. root.geometry(f"{WW}x{HH}+0+0")
  12.  
  13. canvas = tk.Canvas(root, width=WW, height=HH)
  14. canvas.pack()
  15.  
  16. grid = [[0] * COLS for _ in range(ROWS)]
  17. colors = [(255, 255, 255),  # White
  18.           (255, 255, 0),    # Yellow
  19.           (0, 255, 0),      # Green
  20.           (255, 165, 0),    # Orange
  21.           (128, 128, 128),  # Gray
  22.           (0, 0, 255),      # Blue
  23.           (255, 0, 0),      # Red
  24.           (128, 0, 128),    # Purple
  25.           (0, 0, 0)]        # Black
  26.  
  27. num_colors = len(colors)
  28. ants = {i: (ROWS // 2, COLS // 2) for i in range(num_colors)}
  29.  
  30. image = Image.new("RGB", (COLS, ROWS), "white")
  31. image_data = [(255, 255, 255)] * (ROWS * COLS)
  32. ant_direction = 0
  33. xy = {}
  34.    
  35. def darken_color(color):
  36.     factor = 0.9
  37.     return tuple(int(c * factor) for c in color)
  38.  
  39. while True:
  40.     for i in range(num_colors):
  41.         ant_x, ant_y = ants[i]
  42.         grid[ant_x][ant_y] ^= 1
  43.  
  44.         idx = ant_x * COLS + ant_y
  45.         current_color = image_data[idx]
  46.  
  47.         if colors[i] != xy.get((ant_x, ant_y)):
  48.             image_data[idx] = colors[i]
  49.         else:
  50.             image_data[idx] = darken_color(current_color)
  51.         xy[(ant_x, ant_y)] = colors[i]
  52.  
  53.         ant_direction = (ant_direction + 1) % 4 if grid[ant_x][ant_y] else (ant_direction - 1) % 4
  54.  
  55.         if ant_direction == 0:
  56.             ant_x -= 1
  57.         elif ant_direction == 1:
  58.             ant_y += 1
  59.         elif ant_direction == 2:
  60.             ant_x += 1
  61.         elif ant_direction == 3:
  62.             ant_y -= 1
  63.  
  64.         ant_x %= ROWS
  65.         ant_y %= COLS
  66.         ants[i] = (ant_x, ant_y)
  67.  
  68.     image.putdata(image_data)
  69.     photo = ImageTk.PhotoImage(image.resize((WW, HH), resample=Image.NEAREST))
  70.     canvas.create_image(0, 0, image=photo, anchor=tk.NW)
  71.     root.update()
  72.  
  73. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement