Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_Walk_8_Colors.py
- import tkinter as tk
- from PIL import Image, ImageTk
- import random
- WW, HH = 600, 600
- GRID_SIZE = 10
- ROWS, COLS = HH // GRID_SIZE, WW // GRID_SIZE
- root = tk.Tk()
- root.geometry(f"{WW}x{HH}+0+0")
- canvas = tk.Canvas(root, width=WW, height=HH)
- canvas.pack()
- colors = [(255, 255, 255), # White
- (255, 255, 0), # Yellow
- (0, 255, 0), # Green
- (255, 165, 0), # Orange
- (128, 128, 128), # Gray
- (0, 0, 255), # Blue
- (255, 0, 0), # Red
- (128, 0, 128)] # Purple
- num_colors = len(colors)
- image = Image.new("RGB", (COLS, ROWS), "white")
- xy = {}
- def reset_canvas(event=None):
- global image_data, ants, directions
- image_data = colors * (ROWS * COLS // num_colors)
- random.shuffle(image_data)
- ants = {i: (ROWS // 2, COLS // 2) for i in range(num_colors)}
- directions = {}
- for color in colors:
- directions[color] = random.sample(colors, len(colors))
- root.bind("<space>", reset_canvas)
- reset_canvas(0)
- while True:
- for i in range(num_colors):
- ant_x, ant_y = ants[i]
- idx = idx = ant_y * COLS + ant_x
- color = image_data[idx]
- if color == "white":
- ant_direction = colors.index(colors[i]) % 4
- else:
- ant_direction = directions[colors[i]].index(color) % 4
- if ant_direction == 0:
- ant_x += 1
- elif ant_direction == 1:
- ant_x -= 1
- elif ant_direction == 2:
- ant_y += 1
- elif ant_direction == 3:
- ant_y -= 1
- ant_x %= ROWS
- ant_y %= COLS
- ants[i] = (ant_x, ant_y)
- image_data[idx] = colors[i]
- image.putdata(image_data)
- photo = ImageTk.PhotoImage(image.resize((WW, HH), resample=Image.NEAREST))
- canvas.create_image(0, 0, image=photo, anchor=tk.NW)
- root.update()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement