Last active
December 16, 2015 18:29
-
-
Save Sanqui/5477940 to your computer and use it in GitHub Desktop.
part of a larger program
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/python | |
| # encoding: utf-8 | |
| import random | |
| # DIMENSIONS MUST BE ODD! | |
| WIDTH = 17 | |
| HEIGHT = 17 | |
| SQUARE = 14 | |
| neighborhood = (-1, 0), (1, 0), (0, -1), (0, 1) | |
| def printmaze(): # Crude testing function. | |
| for line in maze: | |
| print "".join((" ", "#")[m] for m in line) | |
| # Set up stuff. | |
| maze = [[0]*WIDTH for j in range(HEIGHT)] | |
| def in_boundaries(x, y): # checks if a position isn't out of bounds of the maze. | |
| if x >= WIDTH or x < 0: | |
| return False | |
| if y >= HEIGHT or y < 0: | |
| return False | |
| return True | |
| # Generates a random connected maze using a trivial algorithm. | |
| # Starts on a random odd square and draws a wall in a random direction, | |
| # until there is no free odd square left. | |
| # Guaranteed (?) to be connected as long as the maze dimensions are odd. | |
| while True: | |
| # Find all free odd squares. | |
| locs = [] | |
| for x in range(1, (WIDTH // 2)+1): | |
| for y in range(1, (HEIGHT // 2)+1): | |
| px, py = (x*2)-1, (y*2)-1 | |
| if maze[py][px] == 0: | |
| locs.append((px, py)) | |
| # If there are no free squares, we're done. | |
| if not locs: break | |
| # Pick a random starting point and direction. | |
| x, y = random.choice(locs) | |
| xvel, yvel = random.choice((neighborhood)) | |
| # Draw the wall as far as possible. | |
| while True: | |
| if not in_boundaries(x, y): | |
| break | |
| if maze[y][x] == 1: | |
| break | |
| maze[y][x] = 1 | |
| x += xvel | |
| y += yvel | |
| # Find all free squares | |
| free = [] | |
| for x in range(WIDTH): | |
| for y in range(HEIGHT): | |
| if maze[y][x] == 0: | |
| free.append((x, y)) | |
| # Random positions: | |
| px, py = random.choice(free) # player | |
| free.remove((px, py)) | |
| gx, gy = random.choice(free) # goal | |
| printmaze() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment