Advertisement
here2share

# Tk_avoidance_walk_6.py

Mar 23rd, 2022
848
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. # Tk_avoidance_walk_6.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.    
  22. r = 10
  23. grid = dict([((x,y), 0) for x in range(r,ww-r) for y in range(r,hh-r)])
  24. xy__ = x,y = ww/2, hh/2
  25. xy = [(x,y)]
  26. total = 1
  27. grid[x,y] = total
  28. path = [steps[:]]
  29.  
  30. while 1:
  31.     x,y = xy[-1]
  32.     ttt = []
  33.     vvv = ((x,y-r),(x+r,y),(x,y+r),(x-r,y))
  34.     for x2,y2 in vvv:
  35.         if (x2,y2) in grid:
  36.             step = steps[vvv.index((x2,y2))]
  37.             try:
  38.                 if not grid[x2,y2] and (step in path[-1]):
  39.                     ttt += [(x2, y2, step)]
  40.             except:
  41.                 0
  42.     if ttt:
  43.         x2,y2,ttt = rc(ttt)
  44.         total = total+1
  45.         grid[x2,y2] = total
  46.         path[-1].remove(ttt)
  47.         xy.append((x2,y2))
  48.         path.append((steps[:]))
  49.     else:
  50.         path.pop()
  51.         xy.pop()
  52.    
  53.     if step:
  54.         try:
  55.             cv.create_line(xy[-2:],fill='red')
  56.         except:
  57.             break
  58.         cv.update()
  59.  
  60. xy = [xy__]
  61. Lx, Ly = max(grid.keys())
  62. L = (Lx/5)*(Ly/5)
  63.  
  64. path = []
  65. block = []
  66. prev = []
  67. i = 1
  68. while 1:
  69.     x,y = xy[-1]
  70.     if len(path) < len(xy):
  71.         ttt = []
  72.         vvv = [(x,y-r),(x+r,y),(x,y+r),(x-r,y)]
  73.         for x2,y2 in vvv:
  74.             if (x2,y2) in grid:
  75.                 if (x2,y2) not in xy:
  76.                     ttt += [(grid[x2,y2],x2,y2)]
  77.         path.append(ttt)
  78.     if path[-1]:
  79.         t = min(path[-1])
  80.         path[-1].remove(t)
  81.         zzz,x2,y2 = t
  82.                
  83.         xy += [(x2,y2)]
  84.        
  85.         cv.delete('all')
  86.         cv.create_line(xy,fill='blue')
  87.         cv.update()
  88.     else:
  89.         if (x,y) in block:
  90.             i += 5
  91.         else:
  92.             block += [(x,y)]
  93.             block = block[-100:]
  94.             i = 1
  95.         if len(xy)-i > 4:
  96.             xy = xy[:-i]
  97.             path = path[:-i]
  98.    
  99.     # print len(xy)
  100.  
  101.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement