Advertisement
here2share

# tk_Walk_8_Colors.py

May 4th, 2025
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. # tk_Walk_8_Colors.py
  2.  
  3. import tkinter as tk
  4. from PIL import Image, ImageTk
  5. import random
  6.  
  7. WW, HH = 600, 600
  8. GRID_SIZE = 10
  9. ROWS, COLS = HH // GRID_SIZE, WW // GRID_SIZE
  10.  
  11. root = tk.Tk()
  12. root.geometry(f"{WW}x{HH}+0+0")
  13.  
  14. canvas = tk.Canvas(root, width=WW, height=HH)
  15. canvas.pack()
  16.  
  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.  
  26. num_colors = len(colors)
  27.  
  28. image = Image.new("RGB", (COLS, ROWS), "white")
  29.  
  30. xy = {}
  31.  
  32. def reset_canvas(event=None):
  33.     global image_data, ants, directions
  34.     image_data = colors * (ROWS * COLS // num_colors)
  35.     random.shuffle(image_data)
  36.  
  37.     ants = {i: (ROWS // 2, COLS // 2) for i in range(num_colors)}
  38.  
  39.     directions = {}
  40.     for color in colors:
  41.         directions[color] = random.sample(colors, len(colors))
  42.  
  43. root.bind("<space>", reset_canvas)
  44.  
  45. reset_canvas(0)
  46. while True:
  47.     for i in range(num_colors):
  48.         ant_x, ant_y = ants[i]
  49.         idx = idx = ant_y * COLS + ant_x
  50.         color = image_data[idx]
  51.         if color == "white":
  52.             ant_direction = colors.index(colors[i]) % 4
  53.         else:
  54.             ant_direction = directions[colors[i]].index(color) % 4
  55.  
  56.         if ant_direction == 0:
  57.             ant_x += 1
  58.         elif ant_direction == 1:
  59.             ant_x -= 1
  60.         elif ant_direction == 2:
  61.             ant_y += 1
  62.         elif ant_direction == 3:
  63.             ant_y -= 1
  64.  
  65.         ant_x %= ROWS
  66.         ant_y %= COLS
  67.         ants[i] = (ant_x, ant_y)
  68.         image_data[idx] = colors[i]
  69.  
  70.     image.putdata(image_data)
  71.     photo = ImageTk.PhotoImage(image.resize((WW, HH), resample=Image.NEAREST))
  72.     canvas.create_image(0, 0, image=photo, anchor=tk.NW)
  73.     root.update()
  74.  
  75. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement