/
levelgen.py
573 lines (564 loc) · 21.4 KB
/
levelgen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
import random
import sys
import time
from heapq import heappush, heappop
class Rectangle:
def __init__(self, x0, y0, w, h):
self.x0, self.y0 = x0, y0
self.w, self.h = w, h
def area(self):
return self.w * self.h
def leastSide(self):
return min( self.w, self.h )
def intersect(self, that):
x1, y1 = self.x0 + self.w - 1, self.y0 + self.h - 1
tx1, ty1 = that.x0 + that.w - 1, that.y0 + that.h - 1
x0 = max( self.x0, that.x0 )
y0 = max( self.y0, that.y0 )
x1 = min( x1, tx1 )
y1 = min( y1, ty1 )
w = x1 - x0 + 1
h = y1 - y0 + 1
if w < 0 or h < 0:
w = 0
h = 0
self.x0, self.y0, self.w, self.h = x0, y0, w, h
return self
def contains(self, x, y):
return x >= self.x0 and x < self.x0 + self.w and y >= self.y0 and y < self.y0 + self.h
def copy(self):
return Rectangle(self.x0, self.y0, self.w, self.h)
def shrink(self, n):
self.x0 += n
self.y0 += n
self.w -= 2 * n
self.h -= 2 * n
assert self.w > 0 and self.h > 0
return self
def values(self):
return self.x0, self.y0, self.w, self.h
def midpoint(self):
return self.x0 + int(self.w/2), self.y0 + int(self.h/2)
def coordinates(self):
return [ (x,y) for x in range(self.x0,self.x0+self.w) for y in range(self.y0,self.y0+self.h) ]
class LevelGenerator:
def __init__(self, width, height, bigRects = (32,44,32,44), smallRects = (12,32,12,22), delay = None):
self.width = width
self.height = height
self.rooms = []
self.bigRects = bigRects
self.smallRects = smallRects
self.hallwayLimit = 10 * (width + height)/2.0
self.delay = delay
self.generate()
def generateProtomap(self):
self.data = []
for y in range(self.height):
self.data.append( [] )
for x in range(self.width):
wrote = False
for rect in self.rooms:
if rect.contains( x, y ):
assert not wrote
self.data[-1].append( rect.data[y-rect.y0][x-rect.x0] )
wrote = True
if not wrote:
if x == 0 or y == 0 or x + 1 == self.width or y + 1 == self.height:
self.data[-1].append( '=' )
else:
self.data[-1].append( '-' )
def generateRooms(self):
rooms = self.rooms
for rect in self.generateRectangles( tries = 1, prevs = rooms, *self.bigRects ):
rooms.append( Room( bigRoom = True, *rect.shrink(1).values() ) )
for rect in self.generateRectangles( tries = 1000, prevs = rooms, *self.smallRects):
rooms.append( Room( *rect.shrink(1).values() ) )
for room in rooms:
room.createData()
rounded = False
if room.leastSide() > 16:
room.makeCavernous()
rounded = True
elif random.randint(0,1):
room.makeRectangularCornerclipped( minimal = 3)
else:
room.makeRectangular()
if random.randint(0,1):
dist = 2
subrect = room.generateFloorRect( 5 + dist*2, 5 + dist*2 )
if subrect:
if rounded:
room.fillSubrectangleRounded( subrect.shrink(dist - 1) )
else:
room.fillSubrectangleRectangular( subrect.shrink(dist) )
self.rooms = rooms
return self.rooms
def generate(self):
self.generateRooms()
self.generateProtomap()
self.markCorners()
if not self.tryConnectAllNonvaults(tries=200):
raise AgainException()
self.makeSerendipitousDoors()
self.makeEmptyDoorways(0.1)
self.simplify()
self.designateRooms()
def generateRectangles(self, minWidth, maxWidth, minHeight, maxHeight, tries, prevs = []):
rv = []
triesLeft = tries
while triesLeft > 0:
w = random.randint( minWidth, maxWidth )
h = random.randint( minHeight, maxHeight )
x = random.randint( 1, self.width - w - 1)
y = random.randint( 1, self.height - h - 1)
r = Rectangle( x, y, w, h )
failed = False
for rec in rv + prevs:
if r.copy().intersect( rec ).area() > 0:
failed = True
break
if failed:
triesLeft -= 1
else:
triesLeft = tries
rv.append( r )
return rv
def tryConnect( self, alpha, beta ):
if self.tryDigHallwayBetween( alpha, beta ):
alpha.nowConnectedTo( beta )
return True
return False
def tryConnectAllNonvaults(self, tries = 100):
nonvaults = [room for room in self.rooms if not room.vault ]
origin = random.choice( nonvaults )
connected = set( [origin] )
triesLeft = tries
while len(connected) < len(nonvaults) and triesLeft > 0:
self.tryConnectAny()
newsies = []
for room in connected:
for connection in room.connections:
if connection not in connected:
newsies.append( connection )
for newsie in newsies:
connected.add( newsie )
if newsies:
triesLeft = tries
else:
tries -= 1
return len(connected) == len(nonvaults)
def getUnconnected( self, alpha ): # directly
l = [ room for room in self.rooms if not room in alpha.connections and room != alpha and not room.vault ]
if not l:
return None
return random.choice( l )
def tryConnectToAny(self, alpha ):
beta = self.getUnconnected( alpha )
if not beta:
return False
return self.tryConnect( alpha, beta )
def tryConnectAny(self):
alpha = random.choice( [room for room in self.rooms if not room.vault] )
return self.tryConnectToAny( alpha )
def markCorners(self):
for x in range(self.width):
for y in range(self.height):
if self.data[y][x] == '#':
fn = 0
for dx, dy in ((0,1),(0,-1),(1,0),(-1,0)):
fn += 1 if self.data[y+dy][x+dx] == '.' else 0
if fn == 0:
self.data[y][x] = 'C'
def getRoomContaining(self, x, y):
for room in self.rooms:
if room.contains( x, y ):
return room
def makeSerendipitousDoorsForHallwayAt(self, x, y, probability = 1.0):
hallway = set()
unexplored = [ (x,y) ]
neighbours = [ (0,1), (-1,0), (1,0), (0,-1) ]
endpoints = []
walls = {}
while unexplored:
x, y = unexplored.pop()
if self.data[y][x] == '$':
continue
self.data[y][x] = '$'
hallway.add( (x,y) )
for dx, dy in neighbours:
nx, ny = x+dx,y+dy
if nx < 0 or ny < 0 or nx >= self.width or ny >= self.height:
continue
if self.data[ny][nx] == '+':
room = self.getRoomContaining( nx, ny )
endpoints.append( room )
if self.data[ny][nx] == ':':
unexplored.append( (nx,ny) )
if self.data[ny][nx] in ['#', '[']:
dneigh, fneigh = 0, 0
for ddx, ddy in neighbours:
nnx, nny = nx+dx,ny+dy
if nnx < 0 or nny < 0 or nnx >= self.width or nny >= self.height:
continue
if self.data[nny][nnx] == '+':
dneigh += 1
if self.data[nny][nnx] == '.':
fneigh += 1
if dneigh > 0 or fneigh < 1:
continue
room = self.getRoomContaining( nx, ny )
try:
walls[ room ].append( (nx,ny) )
except KeyError:
walls[ room ] = [ (nx,ny) ]
for key in walls:
if key not in endpoints:
if random.random() < probability:
x, y = random.choice( walls[key] )
self.data[y][x] = '+'
for end in endpoints:
end.nowConnectedTo( key )
endpoints.append( key )
def makeSerendipitousDoors(self, probability = 1.0):
did = True
while did:
did = False
for y in range(self.height):
for x in range(self.width):
if self.data[y][x] == ':':
self.makeSerendipitousDoorsForHallwayAt( x, y, probability )
did = True
break
if did: break
def makeEmptyDoorways(self, probability = 0.5):
for x in range(self.width):
for y in range(self.height):
if self.data[y][x] == '+' and random.random() < probability:
self.data[y][x] = '.'
def simplify(self):
conversions = {
'+': '+', # door
'$': 'o', # procsesed hallway
':': 'o', # unprocsesed hallway
'-': ' ', # impenetrable rock
'=': ' ', # impenetrable rock (guard)
'.': '.', # floor
'#': '#', # wall
'[': '#', # wall (guard)
'C': '#', # wall (corner)
'*': '#', # wall (internal border)
'!': ' ', # impenetrable rock (internal non-border)
}
for x in range(self.width):
for y in range(self.height):
self.data[y][x] = conversions[ self.data[y][x] ]
def tryDigHallwayBetween( self, alpha, beta):
from pathfind import Pathfinder, infinity
import math
tx, ty = beta.floorpoint()
ox, oy = alpha.floorpoint()
assert self.data[oy][ox] == '.'
assert self.data[ty][tx] == '.'
costs = {
'!': infinity,
'*': infinity,
'.': 1,
'#': 100,
'-': 10,
':': infinity,
'+': infinity,
'X': infinity,
'=': infinity,
'C': infinity,
'[': infinity,
}
def cost( (x, y) ):
if self.data[y][x] != '-':
if not alpha.contains( x, y) and not beta.contains( x, y):
return infinity
return costs[ self.data[y][x] ]
pf = Pathfinder(cost = cost,
goal = lambda (x,y) : beta.contains(x, y) and self.data[y][x] == '.',
heuristic = lambda (x,y) : math.sqrt( (x-tx)*(x-tx) + (y-tx)*(y-tx) ),
neighbours = lambda (x,y) : [ (x+dx,y+dy) for (dx,dy) in ((0,1),(0,-1),(1,0),(-1,0)) if x+dx >= 0 and y+dy >= 0 and x+dx < self.width and y+dy < self.height ],
limit = self.hallwayLimit,
delay = self.delay
)
pf.addOrigin( (ox,oy) )
path = pf.seek()
if not path:
return False
protect = []
for x, y in path:
self.data[y][x] = {
'#': '+',
'-': ':',
'.': '.',
'=': ':',
'[': ':',
}[ self.data[y][x] ]
if self.data[y][x] != '.':
protect.append( (x,y) )
for x, y in protect:
for dx, dy in ((1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)):
try:
t = self.data[y+dy][x+dx]
except IndexError:
continue
if t == '#':
self.data[y+dy][x+dx] = '['
if t == '-':
self.data[y+dy][x+dx] = '='
return True
def generateRoomOrdering(self):
import copy
rooms = [ room for room in self.rooms if not room.vault ]
rooms.sort(key = lambda room : room.area() )
entryRoom = rooms[0]
rooms.remove( entryRoom )
for room in rooms:
room.distance = 2**30
def exploreFrom( node ):
v = set()
q = []
node.distance = 0
heappush( q, (node.distance,node) )
while q:
dist, node = heappop( q )
for next in node.connections:
if dist + 1 < next.distance:
next.distance = dist + 1
heappush( q, (next.distance, next) )
exploreFrom( entryRoom )
ordered = []
while rooms:
rooms.sort( key = lambda v : v.distance )
distantRoom = rooms.pop()
exploreFrom( distantRoom )
ordered.append( distantRoom )
return entryRoom, ordered[0], ordered[1:]
def designateRooms(self):
maxRewardsRooms = 3
entry, exit, rewards = self.generateRoomOrdering()
noRewards = random.randint( 1, min( len( rewards ), 3 ))
danger = rewards[noRewards:]
rewards = rewards[:noRewards]
entry.role = 'entry'
exit.role = 'exit'
self.rewardRooms = rewards + [room for room in self.rooms if room.vault ]
for room in rewards:
room.role = 'reward'
for room in danger:
room.role = 'danger'
self.dangerRooms = danger
self.entryRoom = entry
self.exitRoom = exit
class Room (Rectangle):
def __init__(self, x0, y0, w, h, bigRoom = False, vault = False):
Rectangle.__init__(self, x0, y0, w, h)
self.bigRoom = bigRoom
self.vault = vault
self.connections = set()
def nowConnectedTo(self, that):
self.connections.add( that )
that.connections.add( self )
def floorpoint(self):
while True:
x = random.randint( 0, self.w - 1)
y = random.randint( 0, self.h - 1)
if self.data[y][x] == '.':
return x + self.x0,y + self.y0
def internalFloorpoint(self, tries = 100):
nbs = [ (0,1), (1,0), (-1,0), (0,-1) ] + [ (1,1), (1,-1), (-1,1), (-1,-1) ]
while tries > 0:
tries -= 1
x = random.randint( 0, self.w - 1)
y = random.randint( 0, self.h - 1)
if self.data[y][x] == '.':
noninternal = False
for dx, dy in nbs:
if self.data[y+dy][x+dx] != '.':
noninternal = True
if not noninternal:
return x + self.x0,y + self.y0
return self.floorpoint()
def createData(self):
self.data = [ [ '.' for j in range(self.w) ] for i in range(self.h) ]
def makeRectangular(self):
for x in range( self.w ):
for y in range( self.h ):
if x == 0 or y == 0 or x+1 == self.w or y+1 == self.h:
dot = '#'
else:
dot = '.'
self.data[y][x] = dot
def makeRectangularCornerclipped(self, minimal = 1):
srw = random.randint( minimal, int(self.w/2) )
srh = random.randint( minimal, int(self.h/2) )
srx = self.w - srw if random.randint(0,1) else 0
sry = self.h - srh if random.randint(0,1) else 0
subrect = Rectangle( srx, sry, srw, srh )
nbs = [ (0,1), (1,0), (-1,0), (0,-1) ] + [ (1,1), (1,-1), (-1,1), (-1,-1) ]
def inside(a,b):
return a >= 0 and b >= 0 and a < self.w and b < self.h and not subrect.contains( a, b )
for x in range( self.w ):
for y in range( self.h ):
dot = '.'
if not inside(x,y):
dot = '-'
else:
for dx, dy in nbs:
if not inside(x+dx,y+dy):
dot = '#'
self.data[y][x] = dot
def makeCavernous(self):
tiles = {}
for x in range( self.w ):
for y in range( self.h ):
hubness = min( x, self.w - x - 1, y, self.h - y - 1)
edginess = max( self.w, self.h ) - hubness if hubness > 0 else 2**30 #hax
tiles[x,y] = edginess
cset = []
oset = [ (int(self.w/2), int(self.h/2)) ]
tiles[ oset[0] ] = 0
nbs = [ (0,1), (1,0), (-1,0), (0,-1) ]
dnbs = [ (1,1), (1,-1), (-1,1), (-1,-1) ]
while len( oset + cset ) < self.area() * 0.6:
x, y = next = random.choice( oset )
bs = []
for dx, dy in nbs:
try:
nb = tiles[x+dx,y+dy]
if nb <= 0: continue
bs.append( (x+dx,y+dy) )
except KeyError:
continue
if not bs:
oset.remove( next )
cset.append( next )
continue
else:
x, y = random.choice( bs )
tiles[x,y] -= 1
if tiles[x,y] <= 0:
oset.append( (x,y) )
digged = set( cset + oset )
for x in range( self.w ):
for y in range( self.h ):
dot = '-'
if (x,y) in digged:
dot = '.'
else:
for dx, dy in nbs+dnbs:
if (x+dx,y+dy) in digged:
dot = '#'
self.data[y][x] = dot
def generateFloorRect(self, minWidth, minHeight, tries = 100):
while tries > 0:
w = random.randint( minWidth, self.w )
h = random.randint( minHeight, self.h )
x = random.randint( 0, self.w - w )
y = random.randint( 0, self.h - h )
fail = False
for i in range(w):
for j in range(h):
if self.data[y+j][x+i] != '.':
fail = True
if not fail:
return Rectangle( x, y, w, h )
tries -= 1
return None
def fillSubrectangleRectangular(self, rect):
for x in range(rect.x0, rect.x0 + rect.w):
for y in range(rect.y0, rect.y0 + rect.h):
assert self.data[y][x] == '.'
if x == rect.x0 or y == rect.y0 or x + 1 == rect.x0 + rect.w or y + 1 == rect.y0 + rect.h:
dot = '*'
else:
dot = '!'
self.data[y][x] = dot
def fillSubrectangleRounded(self, rect):
filled = []
for x in range(rect.x0, rect.x0 + rect.w):
for y in range(rect.y0, rect.y0 + rect.h):
filled.append( (x,y) )
nbs = [ (0,1), (1,0), (-1,0), (0,-1) ] + [ (1,1), (1,-1), (-1,1), (-1,-1) ]
def inside(a,b):
return rect.contains(a,b) and (a,b) in filled
for i in range( len( filled ) / 4 ):
hasNbNin = False
x, y = random.choice( filled )
for dx, dy in nbs:
if not inside( x+dx, y+dy ):
hasNbNin = True
if hasNbNin:
filled.remove( (x,y) )
for x in range(rect.x0, rect.x0 + rect.w):
for y in range(rect.y0, rect.y0 + rect.h):
dot = '.'
if inside(x,y):
dot = '!'
for dx, dy in nbs:
if not inside(x+dx,y+dy):
dot = '*'
self.data[y][x] = dot
class AgainException: pass
def generateLevel(*args, **kwargs ):
while True:
try:
return LevelGenerator(*args, **kwargs)
except AgainException:
print >> sys.stderr, "warning: regenerating level -- should be unlikely"
import Queue
import threading
class ShutdownException:
pass
class GeneratorThread( threading.Thread ):
def __init__(self, q):
threading.Thread.__init__(self)
self.q = q
self.go = True
def run(self):
lg = generateLevel( *self.args, **self.kwargs )
self.q.put( lg )
def raiseOnShutdown():
if not self.go:
raise ShutdownException
while self.go:
try:
lg = generateLevel( delay = raiseOnShutdown, *self.args, **self.kwargs )
except ShutdownException:
break
self.q.put( lg )
class GeneratorQueue (Queue.Queue):
def __init__(self, buffer, *args, **kwargs):
Queue.Queue.__init__(self, buffer)
self.thread = GeneratorThread( self )
self.thread.args = args
self.thread.kwargs = kwargs
self.thread.start()
def shutdown(self):
self.thread.go = False
if not self.empty():
self.get() # epic hack
self.thread.join()
if __name__ == '__main__':
import time
times = []
t0 = time.time()
while True:
t0 = time.time()
lg = generateLevel( 80,
50,
(16,30,16,30),
(12,20,12,16),
# (32,44,32,44),
# (12,32,12,22),
)
dt = time.time() - t0
for line in lg.data:
print "".join( line )
times.append( dt )
print "Generated in", dt, "seconds"
print "Average", sum(times) / float( len( times ) ), "seconds"
print "Maximum", max(times), "seconds"