rc3/maps/ir/gmaze/genmaze.py

63 lines
1.6 KiB
Python

import sys, os, json
from random import shuffle, randrange
from operator import iadd
from functools import reduce
#================================================================
def gen_maze(w = 8, h = 8):
visited = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
walls = [[1,(i+1)%2]*w+[1] for i in range(2*h+1)]
def walk(x, y):
visited[y][x] = 1
d = [(x-1,y), (x,y+1), (x+1,y), (x,y-1)]
shuffle(d)
for (xx, yy) in d:
if visited[yy][xx]: continue
if xx == x: walls[2*max(y, yy)][2*x+1] = 0
if yy == y: walls[1+2*y][2*max(x, xx)] = 0
walk(xx, yy)
walk(randrange(w), randrange(h))
return walls
#================================================================
outfile = 'gmaze.json'
if len(sys.argv) > 1:
outfile = sys.argv[1]
outfile = os.path.basename(outfile) # !!! Prohibit path traversal !!!
if not outfile.endswith('.json'):
outfile += '.json'
#================================================================
with open('gmaze__template.json') as f:
map = json.load(f)
w,h = map['width'], map['height']
walls = None
collides = None
for layer in map['layers']:
if layer['name'] == 'walls':
walls = layer['data']
elif layer['name'] == 'collides':
collides = layer['data']
maze = gen_maze(w//2, h//2)
maze = reduce(iadd, maze) # flatten list
for i in range(len(maze)): # clear maze walls
if maze[i] == 0:
walls[i] = 0
collides[i] = 0
with open(outfile,'w') as f:
map = json.dump(map, f, sort_keys=1)
#================================================================