Advertisement
here2share

# Tk_maze_genX.py

Nov 2nd, 2019
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. # Tk_maze_genX.py
  2.  
  3. from random import shuffle, randrange
  4.  
  5. tk = 1
  6. try:
  7.     from Tkinter import *
  8. except:
  9.     try:
  10.         from tkinter import *
  11.     except:
  12.         tk = 0
  13.  
  14. import math
  15. import random
  16. import time
  17.  
  18. def make_maze(w=25, h=18):
  19.     vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
  20.     ver = [['| '] * w + ['|.'] for _ in range(h)] + [[]]
  21.     hor = [['+-'] * w + ['+.'] for _ in range(h + 1)]
  22.  
  23.     def walk(x, y):
  24.         vis[y][x] = 1
  25.  
  26.         d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
  27.         shuffle(d)
  28.         for (xx, yy) in d:
  29.             if vis[yy][xx]: continue
  30.             if xx == x: hor[max(y, yy)][x] = '+ '
  31.             if yy == y: ver[y][max(x, xx)] = '  '
  32.             walk(xx, yy)
  33.  
  34.     walk(randrange(w), randrange(h))
  35.  
  36.     s = ""
  37.     for (a, b) in zip(hor, ver):
  38.         s += ''.join(a + ['\n'] + b + ['\n'])
  39.     0
  40.     if tk:
  41.         canvas.delete('all')   
  42.         xy = s[:s.rfind('.')]
  43.         color = '#%02x%02x%02x' % (180, 0, 180)
  44.         x = 25
  45.         y = 30
  46.         sq = 30
  47.         while xy:
  48.             t,xy = xy[:2],xy[2:]
  49.             if t == '+-':
  50.                 canvas.create_line((x,y,x+sq,y), fill=color)
  51.             elif '.' in t:
  52.                 if '+' in t:
  53.                     canvas.create_line((x,y,x,y+sq), fill=color)
  54.                 x = 25
  55.                 if '+' in t:
  56.                     canvas.create_line((x,y,x,y+sq), fill=color)
  57.                     y += sq
  58.                 x -= sq
  59.             elif ' |' in t:
  60.                 canvas.create_line((x,y-sq,x,y), fill=color)
  61.             x += sq
  62.             canvas.update()
  63.        
  64.     print s
  65. 0
  66.  
  67. if tk:
  68.     root = Tk()
  69.     c_width = 800
  70.     c_height = 600
  71.     canvas = Canvas(root, width=c_width, height=c_height, bg='white')
  72.     canvas.pack()
  73.     root.bind("<space>", lambda x: make_maze(randrange(9,25),randrange(9,18))) 
  74.  
  75. make_maze()
  76. 0
  77. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement