Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_Langtons_Ant_9_Color.py
- import tkinter as tk
- from PIL import Image, ImageTk
- 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()
- grid = [[0] * COLS for _ in range(ROWS)]
- 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
- (0, 0, 0)] # Black
- num_colors = len(colors)
- ants = {i: (ROWS // 2, COLS // 2) for i in range(num_colors)}
- image = Image.new("RGB", (COLS, ROWS), "white")
- image_data = [(255, 255, 255)] * (ROWS * COLS)
- ant_direction = 0
- xy = {}
- def darken_color(color):
- factor = 0.9
- return tuple(int(c * factor) for c in color)
- while True:
- for i in range(num_colors):
- ant_x, ant_y = ants[i]
- grid[ant_x][ant_y] ^= 1
- idx = ant_x * COLS + ant_y
- current_color = image_data[idx]
- if colors[i] != xy.get((ant_x, ant_y)):
- image_data[idx] = colors[i]
- else:
- image_data[idx] = darken_color(current_color)
- xy[(ant_x, ant_y)] = colors[i]
- ant_direction = (ant_direction + 1) % 4 if grid[ant_x][ant_y] else (ant_direction - 1) % 4
- if ant_direction == 0:
- ant_x -= 1
- elif ant_direction == 1:
- ant_y += 1
- elif ant_direction == 2:
- ant_x += 1
- elif ant_direction == 3:
- ant_y -= 1
- ant_x %= ROWS
- ant_y %= COLS
- ants[i] = (ant_x, ant_y)
- 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