Advertisement
tzot

maze generation (slashdot related)

Dec 2nd, 2012
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. #!/usr/bin/python -O
  2.  
  3. from __future__ import unicode_literals
  4.  
  5. import sys
  6. import random, array
  7. import itertools as it
  8. import operator as op
  9.  
  10. def powerset(s):
  11.     "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
  12.     return it.chain.from_iterable(it.combinations(s, r) for r in xrange(len(s)+1))
  13.  
  14. def value(desc):
  15.     return (68, 64, 4, 160, 128, 32, 0)[
  16.         ('VERTICAL', 'UP', 'DOWN', 'HORIZONTAL', 'LEFT', 'RIGHT', None).index(desc)]
  17.  
  18. OTHERS= [reduce(op.or_, x, 0) for x in powerset((16, 8, 2, 1))]
  19.  
  20. def make_table():
  21.     import unicodedata as ud, re
  22.     matcher= re.compile('^BOX DRAWINGS LIGHT (\S+)(?: AND (\S+))?$')
  23.     table= array.array(b'u', ' ')*256
  24.     for char_index in xrange(0x2500, 0x257f):
  25.         char= unichr(char_index)
  26.         match= matcher.match(ud.name(char))
  27.         if match:
  28.             mg1= match.group(1)
  29.             mg2= match.group(2)
  30.             table_index= value(mg1) | value(mg2)
  31.             for other in OTHERS:
  32.                 table[table_index | other]= char
  33.     return table
  34.  
  35. def make_maze(rows, cols):
  36.     table= make_table()
  37.     last_row= [1] + [2]*cols
  38.     for ix in xrange(rows):
  39.         curr_row= [1] + [random.randrange(4) for _ in xrange(cols-2)] + [1]
  40.         for idx in xrange(1, len(curr_row)):
  41.             sys.stdout.write(table[
  42.                 64*last_row[idx-1]
  43.                 + 16*last_row[idx]
  44.                 + 4*curr_row[idx-1]
  45.                 + curr_row[idx]])
  46.         sys.stdout.write('\n')
  47.         last_row= curr_row
  48.  
  49. if __name__ == "__main__":
  50.     make_maze(int(sys.argv[1]), int(sys.argv[2]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement