Browse Source

Make progress on dungeon generation

master
Josh Gordon 4 years ago
parent
commit
7661ed1705
  1. 126
      app/dungeon.py

126
app/dungeon.py

@ -0,0 +1,126 @@
from random import randint, choice
import numpy as np
#algorithm: http://blankhead.fi/blog/index.php/2019/06/01/cell-flow-dungeon-layout-generation/
CELL_SIZE = 10
RETRY_CELL_PLACEMENT = True
def randomColor():
b = randint(0,255)
g = randint(0,255)
r = randint(0,255)
return np.array([r,g,b])
class Cell(object):
def __init__(self,ID):
self.spaces = []
self.color = randomColor()
self.ID = ID
self.flow = []
def grow(self,grid):
if len(self.spaces) == 0:
x,y = grid.randomPoint()
grid[x,y] = self.ID #claim space
self.spaces.append((x,y))
return #no flow adjustment required, as this is the cell origin
if RETRY_CELL_PLACEMENT:
valid = False
tries = 0
while not valid:
tries += 1
if tries > grid.w*grid.h:
return #guarantees halting. find a better way
x0,y0 = choice(self.spaces)
conn = grid.connectedPoints(x0,y0)
if len(conn) == 0:
continue
x,y = choice(conn)
valid = grid[x,y] == 0
grid[x,y] = self.ID
self.spaces.append((x,y))
self.flow.append((x,y,x0,y0))
else:
pass #write this when interested
class Grid(object):
def __init__(self,w,h):
self.w = w
self.h = h
self.spaces = np.zeros((w,h))
self.cells = []
def isOpen(self,x,y):
if x < 0 or x >= self.w or y < 0 or y >= self.h:
return False
return self.spaces[x,y] == 0
def __getitem__(self,key):
return self.spaces[key]
def __setitem__(self,key,value):
self.spaces[key] = value
def randomPoint(self):
x = self.w//2
y = self.h//2
while not self.isOpen(x,y):
x = randint(0,self.w-1)
y = randint(0,self.h-1)
return x,y
def connectedPoints(self,x0,y0):
pointlist = []
for (x,y) in [(0,1),(1,0),(-1,0),(0,-1)]:
ptx = x0 + x
pty = y0 + y
if ptx < 0 or ptx >= self.w or pty < 0 or pty >= self.h:
pass
else:
pointlist.append((x0 + x,y0 + y))
return pointlist
def addCell(self):
if len(self.cells) == 0:
c = Cell(1)
for i in range(CELL_SIZE):
c.grow(self)
self.cells.append(c)
else:
cOld = choice(self.cells)
while True:
x0,y0 = choice(cOld.spaces)
conn = self.connectedPoints(x0,y0)
if len(conn) == 0:
continue
free = [(x,y) for (x,y) in conn if self.spaces[x,y] == 0]
if len(free) == 0:
continue
sx,sy = choice(free)
c = Cell(len(self.cells))
c.spaces = [(sx,sy)]
c.flow = [(sx,sy,x0,y0)]
self.spaces[sx,sy] = c.ID
for i in range(CELL_SIZE-1):
c.grow(self)
self.cells.append(c)
break
def __str__(self):
return str(self.spaces)
#driver code
g = Grid(10,10)
g.addCell()
g.addCell()
g.addCell()
g.addCell()
print(g)
Loading…
Cancel
Save