Skip to content

Instantly share code, notes, and snippets.

@jdp
Created December 25, 2012 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdp/4374899 to your computer and use it in GitHub Desktop.
Save jdp/4374899 to your computer and use it in GitHub Desktop.
Simple implementation of Zelda dungeons in Python
def floor(size=10):
"""Return a list of rooms represented by dictionaries.
The list is procedurally generated. Each room is represented by a ``dict``
with ``'x'``, ``'y'``, and ``'exits'`` keys.
>>> floor(5)[0]
{'x': 0, 'y': 0, 'exits': {'up': {...}, 'right': {...}}}
"""
from random import choice
# Seed the dungeon with a single room.
rooms = [dict(x=0, y=0, exits={})]
# Map the possible exits to the X/Y offsets and the corresponding exit
# in the adjacent room.
exits = {'up': (0, -1, 'down'),
'down': (0, 1, 'up'),
'left': (-1, 0, 'right'),
'right': (1, 0, 'left')}
while len(rooms) < size:
# Select an exit from a room in the floor that has unused exits.
extant = choice(filter(lambda r: len(r['exits']) < 4, rooms))
exit = choice([d for d in exits.keys() if not extant['exits'].get(d)])
# Connect the new room to the existing room and add it to the floor.
room = dict(x=extant['x'] + exits[exit][0],
y=extant['y'] + exits[exit][1],
exits={exits[exit][2]: extant})
extant['exits'][exit] = room
rooms.append(room)
return rooms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment