#!/usr/bin/env python3

import random

map_width = 30
map_height = 20

min_width = 4
stop_width = min_width * 2 + 1

random.seed(42) # Traditional value for fixed layouts.

# Levels are stored by line: y is always the first index.
level = [['.' for x in range(map_width)] for y in range(map_height)]
# Add walls all around the level to begin with.
for y in range(map_height):
	level[y][0] = '#'
	level[y][map_width - 1] = '#'
	for x in range(map_width):
		level[0][x] = '#'
		level[map_height - 1][x] = '#'

def subdivide(x1, y1, x2, y2):
	w = x2 - x1 + 1
	h = y2 - y1 + 1
	
	if w >= h and w >= stop_width:
		subdivide_width(x1, y1, x2, y2)
	elif h >= stop_width:
		subdivide_height(x1, y1, x2, y2)

def subdivide_width(x1, y1, x2, y2):
	x = random.randint(x1 + min_width, x2 - min_width)

	for y in range(y1, y2 + 1):
		level[y][x] = '#'

	subdivide(x1, y1, x - 1, y2)
	subdivide(x + 1, y1, x2, y2)

	doory = random.randint(y1 + 1, y2 - 1)
	level[doory][x] = '.'
	# Account for walls placed deeper into recursion.
	level[doory][x - 1] = '.'
	level[doory][x + 1] = '.'

def subdivide_height(x1, y1, x2, y2):
	y = random.randint(y1 + min_width, y2 - min_width)

	for x in range(x1, x2 + 1):
		level[y][x] = '#'

	subdivide(x1, y1, x2, y - 1)
	subdivide(x1, y + 1, x2, y2)

	doorx = random.randint(x1 + 1, x2 - 1)
	level[y][doorx] = '.'
	# Account for walls placed deeper into recursion.
	level[y - 1][doorx] = '.'
	level[y + 1][doorx] = '.'

# Subdivide the space *inside* the exterior wall, leaving it out.
subdivide(1, 1, map_width - 2, map_height - 2)

for i in level:
	print("".join(i))
