Advertisement
here2share

# tk_Langtons_Ant.py

May 4th, 2025
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. # tk_Langtons_Ant.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.  
  19. while 1:
  20.     grid[ant_x][ant_y] ^= 1
  21.     color = "black" if grid[ant_x][ant_y] else "white"
  22.     canvas.create_rectangle(ant_y * GRID_SIZE, ant_x * GRID_SIZE,
  23.                             (ant_y + 1) * GRID_SIZE, (ant_x + 1) * GRID_SIZE,
  24.                             fill=color, outline="")
  25.  
  26.     if grid[ant_x][ant_y]:  # White -> Right turn
  27.         ant_direction = (ant_direction + 1) % 4
  28.     else:  # Black -> Left turn
  29.         ant_direction = (ant_direction - 1) % 4
  30.  
  31.     if ant_direction == 0:
  32.         ant_x -= 1
  33.     elif ant_direction == 1:
  34.         ant_y += 1
  35.     elif ant_direction == 2:
  36.         ant_x += 1
  37.     elif ant_direction == 3:
  38.         ant_y -= 1
  39.  
  40.     ant_x %= ROWS
  41.     ant_y %= COLS
  42.  
  43.     root.update()
  44.  
  45. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement