Skip to content

Instantly share code, notes, and snippets.

@Tyaedalis
Created November 14, 2012 05:49
Show Gist options
  • Save Tyaedalis/4070542 to your computer and use it in GitHub Desktop.
Save Tyaedalis/4070542 to your computer and use it in GitHub Desktop.
Simple cave generator.
"""
TODO:
====
+ Fit grid to generated structure (with a border)
+ Generate a few small "rooms" and combine them to a grid
+ Corridors
+ Doors?
+ Func to determine where rooms should go
"""
import random
class Point():
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __str__(self):
return str((self.x, self.y))
class Digger():
def __init__(self, grid, point=None, life=None, directions=None):
self.grid = grid
self.position = point or Point(self.grid.width / 2, self.grid.height / 2)
self.directions = (
Point(1, 0),
Point(0, 1),
Point(-1, 0),
Point(0, -1),
) or directions
self.life = life or 50
def rand_move(self):
## Moves digger randomly by 1 cell in a cardinal direction
self.position += random.choice(self.directions)
self.position = self.grid.in_bounds(self.position)
def dig(self, grid):
self.grid.set_at(self.position, '.')
self.life -= 1
class Grid():
def __init__(self, width, height):
self.width = width
self.height = height
self.cells = [['#'] * width for _ in range(height)] # fill up a grid of #
def __str__(self):
return '\n'.join(''.join(row) for row in self.cells)
def set_at(self, point, value):
self.cells[point.y][point.x] = value
def in_bounds(self, point):
x, y = point.x, point.y
if x <= 0:
x = 1
if x >= self.width - 1:
x = self.width - 2
if y <= 0:
y = 1
if y >= self.height - 1:
y = self.height - 2
return Point(x, y)
ITER = 100 # number of iterations to cut
def main():
while 1:
# Width, height of grid
WIDTH = random.randint(20, 50)
HEIGHT = random.randint(20, 50)
## Below is for setting dimensions randomly
##if abs(WIDTH - HEIGHT) > 20: # Keeps aspect reasonable (only for random dimensions)
## WIDTH = random.randint(100, 150)
## HEIGHT = random.randint(20, 50)
grid = Grid(WIDTH, HEIGHT)
diggers = []
diggers.append(Digger(grid))
for _ in range(ITER):
print 'diggers: ', len(diggers)
for digger in diggers:
digger.rand_move()
grid.set_at(digger.position, '@') #used to watch the little guy crawl around ^_^
print grid, '\n'
raw_input("")
for i in range(len(diggers)):
diggers[i].dig(grid)
if random.randint(1, 100) < 12:
diggers.append(Digger(grid, diggers[i].position, 5))
print diggers[i].life
if diggers[i].life == 0:
del diggers[i]
print grid
raw_input("Another? ")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment