here2share

# Tk_avoidance_walk_4.py

Mar 5th, 2022 (edited)
1,381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None | 0 0
  1. # Tk_avoidance_walk_4.py
  2.  
  3. import random
  4. from Tkinter import *
  5. from math import *
  6.  
  7. ri = random.randint
  8. rs = random.shuffle
  9. rc = random.choice
  10.  
  11. ww = 600
  12. hh = 600
  13.  
  14. root = Tk()
  15. root.title("Tk_avoidance_walk")
  16. root.geometry("%dx%d+-6+-2"%(ww,hh))
  17. cv = Canvas(width=ww, height=hh, bg='white')
  18. cv.pack()
  19.  
  20. steps = ["N","E","S","W"]
  21. tries = 0
  22. def direction():
  23.     if not tries:
  24.         t = steps[:]
  25.         rs(t)
  26.         return [t]
  27.     return [rc([steps[:], steps[::-1]])]
  28.    
  29. r = 10
  30. grid = dict([((x,y), 0) for x in range(r,ww-r) for y in range(r,hh-r)])
  31. x,y = ww/2, hh/2
  32. xy = [(x,y)]
  33. zz = []
  34.  
  35. most = 0
  36.  
  37. while 1:
  38.     while 1:
  39.         try:
  40.             x,y = xy[-1]
  41.             step = zz[-1].pop()
  42.             break
  43.         except:
  44.             try:
  45.                 xy.pop()
  46.                 zz.pop()
  47.             except:
  48.                 xy = [(x,y)]
  49.                 zz += direction()
  50.     if   step == "E":
  51.         x += r
  52.     elif step == "W":
  53.         x -= r
  54.     elif step == "N":
  55.         y += r
  56.     else:
  57.         y -= r
  58.     try:
  59.         grid[x,y]
  60.         if (x,y) not in xy:
  61.             zz += direction()
  62.             xy += [(x,y)]
  63.             if len(xy) > most:
  64.                 most = len(xy)
  65.                 print most
  66.             tries = max(0,tries-3)
  67.             cv.delete('all')
  68.             cv.create_line(xy,fill='blue')
  69.             cv.update()
  70.         else:
  71.             tries += 1
  72.             if tries > 12:
  73.                 xy = xy[:-50]
  74.                 zz = zz[:-50]
  75.     except:
  76.         0
  77.    
Add Comment
Please, Sign In to add comment