/
levelgen.py
1546 lines (1250 loc) · 43.9 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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import functions, life, draw, var
import logging, copy, math, random, time
import numpy
class LevelGen:
def __init__(self,size=(50,50),rooms=25,room_size=(5,7),diagtunnels=True,overlaprooms=False,outside=False):
self.size = size
self.map = []
self.rooms = []
self.max_rooms = rooms
self.room_size = room_size
self.diagtunnels = diagtunnels
self.overlaprooms = overlaprooms
self.outside = outside
self.landmarks = []
self.walking_space = []
self.walls = []
#Lights and maps...
self.lights = []
self.fmap = [[0] * self.size[1] for i in xrange(self.size[0])]
self.real_estate = []
self.lmap = []
self.tmap = []
self.fov = []
self.items = []
self.items_shortcut = []
#Python has no concept of 2d arrays, so we "fake" it here.
for x in xrange(self.size[0]):
_y = []
_l = []
_i = []
_t = []
for y in xrange(self.size[1]):
_y.append(0)
_l.append({'source':False,'color':(0,0,0),'brightness':0})
_i.append([])
_t.append(0)
self.walls.append((x,y))
self.map.append(_y)
self.lmap.append(_l)
self.tmap.append(_t)
self.items.append(_i)
def save(self):
_keys = {}
_keys['size'] = self.size
_keys['map'] = self.map
_keys['fmap'] = self.fmap
_keys['tmap'] = self.tmap
_keys['real_estate'] = self.real_estate
_keys['z'] = self.z
_keys['entrances'] = self.entrances
_keys['exits'] = self.exits
_keys['outside'] = self.outside
_rooms = []
for room in self.rooms:
if room.has_key('owner') and room['owner']:
_r = room.copy()
_r['owner'] = _r['owner'].id
_rooms.append(_r)
else:
_rooms.append(room)
_keys['rooms'] = _rooms
_items = copy.deepcopy(self.items)
for y in xrange(self.size[1]):
for x in xrange(self.size[0]):
for item in _items[x][y]:
if item.has_key('planted_by'):
item['planted_by'] = item['planted_by'].id
if item.has_key('from'):
item['from'] = item['from'].id
if item.has_key('owner') and item['owner']:
item['owner'] = item['owner'].id
if item['type'] == 'storage':
for _item in item['items']:
if _item.has_key('planted_by'):
_item['planted_by'] = _item['planted_by'].id
if _item.has_key('from'):
_item['from'] = _item['from'].id
if item['type'] == 'stove' and item['cooking'] and item['cooking'].has_key('planted_by'):
item['cooking']['planted_by'] = item['cooking']['planted_by'].id
_keys['items'] = _items
return _keys
def load(self,keys):
self.size = keys['size']
self.map = keys['map']
self.fmap = keys['fmap']
self.tmap = keys['tmap']
self.real_estate = keys['real_estate']
self.z = keys['z']
self.entrances = keys['entrances']
self.exits = keys['exits']
self.outside = keys['outside']
self.rooms = keys['rooms']
self.items = keys['items']
def finalize(self):
"""Cleans up after load()"""
for room in self.rooms:
room['name'] = str(room['name'])
if room.has_key('owner') and room['owner']:
room['owner'] = functions.get_alife_by_id(room['owner'])
for y in xrange(self.size[1]):
for x in xrange(self.size[0]):
for item in self.items[x][y]:
if item.has_key('planted_by'):
item['planted_by'] = functions.get_alife_by_id(item['planted_by'])
if item.has_key('from'):
item['from'] = functions.get_alife_by_id(item['from'])
if item.has_key('owner') and item['owner']:
item['owner'] = functions.get_alife_by_id(item['owner'])
if item['type'] == 'storage':
for _item in item['items']:
if _item.has_key('planted_by'):
_item['planted_by'] = functions.get_alife_by_id(_item['planted_by'])
if _item.has_key('from'):
_item['from'] = functions.get_alife_by_id(_item['from'])
if item['type'] == 'stove' and item['cooking'] and item['cooking'].has_key('planted_by'):
item['cooking']['planted_by'] = functions.get_alife_by_id(item['cooking']['planted_by'])
def build_color_map(self):
self.color_map = []
r = numpy.zeros((self.size[1],self.size[0]))
g = numpy.zeros((self.size[1],self.size[0]))
b = numpy.zeros((self.size[1],self.size[0]))
for x in xrange(0,self.size[0]):
for y in xrange(0,self.size[1]):
_fgcolor = var.color_codes[var.tile_map[str(self.map[x][y])]['color'][0]]
_bgcolor = var.color_codes[var.tile_map[str(self.map[x][y])]['color'][1]]
#r[x,y] = _fgcolor[0]
#g[x,y] = _fgcolor[1]
#b[x,y] = _fgcolor[2]
r[y,x] = _bgcolor[0]
g[y,x] = _bgcolor[1]
b[y,x] = _bgcolor[2]
self.color_map.append(r)
self.color_map.append(g)
self.color_map.append(b)
def add_light(self,pos,color,life,brightness):
self.lights.append(pos)
self.lmap[pos[0]][pos[1]]['source'] = True
self.lmap[pos[0]][pos[1]]['color'] = color
self.lmap[pos[0]][pos[1]]['life'] = life
self.lmap[pos[0]][pos[1]]['brightness'] = brightness
self.lmap[pos[0]][pos[1]]['children'] = []
def add_item(self,item,pos,no_place=False):
_item = var.items[str(item)].copy()
#if item in [18]: _item['items'] = []
if _item.has_key('items'): _item['items'] = []
_item['pos'] = pos
if not no_place:
self.items[pos[0]][pos[1]].append(_item)
self.items_shortcut.append(_item)
return _item
def place_item(self,pos,item):
self.items[pos[0]][pos[1]].append(item)
self.items_shortcut.append(item)
def remove_item(self,pos,item):
self.items[pos[0]][pos[1]].remove(item)
self.items_shortcut.remove(item)
def get_item(self,pos):
return self.items[pos[0]][pos[1]]
def get_all_items_of_tile(self,tile):
_ret = []
for y in xrange(self.size[1]):
for x in xrange(self.size[0]):
for item in self.items[x][y]:
if item['type'] == 'storage':
for _item in item['items']:
if _item['tile'] == tile:
_ret.append(_item)
if item['tile'] == tile:
_ret.append(item)
return _ret
def get_items(self,**kargv):
_ret = []
for y in xrange(self.size[1]):
for x in xrange(self.size[0]):
for item in self.items[x][y]:
_match = kargv.keys()
for key in kargv:
if item.has_key(key) and item[key]==kargv[key]:
_match.remove(key)
if not _match:
_ret.append(item)
break
return _ret
def get_items_ext(self,**kargv):
_ret = []
for y in xrange(self.size[1]):
for x in xrange(self.size[0]):
for item in self.items[x][y]:
_match = kargv.keys()
for key in kargv:
if item.has_key(key) and item[key] in kargv[key]:
_match.remove(key)
if not _match:
_ret.append(item)
break
return _ret
def get_items_in_building(self,building,**kargv):
_ret = []
for room in self.rooms:
if room['name'].lower() == building.lower():
for pos in room['walking_space']:
for item in self.items[pos[0]][pos[1]]:
if item['type'] == 'storage':
for _item in item['items']:
_match = kargv.keys()
for key in kargv:
if _item.has_key(key) and _item[key]==kargv[key]:
_match.remove(key)
if not _match:
_ret.append(_item)
break
_match = kargv.keys()
for key in kargv:
if item.has_key(key) and item[key]==kargv[key]:
_match.remove(key)
if not _match:
_ret.append(item)
break
return _ret
def get_items_in_building_ext(self,building,**kargv):
_ret = []
for room in self.rooms:
if room['name'].lower() == building.lower():
for pos in room['walking_space']:
for item in self.items[pos[0]][pos[1]]:
if item['type'] == 'storage':
for _item in item['items']:
_match = kargv.keys()
for key in kargv:
if _item.has_key(key) and _item[key] in kargv[key]:
_match.remove(key)
if not _match:
_ret.append(_item)
break
_match = kargv.keys()
for key in kargv:
if item.has_key(key) and item[key]==kargv[key]:
_match.remove(key)
if not _match:
_ret.append(item)
break
return _ret
def get_all_items_of_type(self,type,check_storage=True):
if isinstance(type,list): _list = True
else: _list = False
_ret = []
for item in self.items_shortcut:
if item['type'] == 'storage' and check_storage:
for _item in item['items']:
if _list:
if _item['type'] in type:
_ret.append(_item)
else:
if _item['type'] == type:
_ret.append(_item)
if _list:
if item['type'] in type:
_ret.append(item)
else:
if item['type'] == type:
_ret.append(item)
return _ret
def get_all_items_tagged(self,tag,ignore_storage=False):
"""Returns items with flag 'tag'."""
_ret = []
for item in self.items_shortcut:
if item['type'] == 'storage' and not ignore_storage:
for _item in item['items']:
if _item.has_key(tag) and _item[tag]:
_ret.append(_item)
if item.has_key(tag) and item[tag]:
_ret.append(item)
return _ret
def get_all_items_in_building(self,building):
"""Returns all items in 'building'"""
_ret = []
for room in self.rooms:
if room['name'].lower() == building.lower():
for pos in room['walking_space']:
for item in self.items[pos[0]][pos[1]]:
if item['type'] == 'storage':
for _item in item['items']:
_ret.append(_item)
_ret.append(item)
return _ret
def get_all_items_in_building_tagged(self,building,tag):
"""Returns all items in 'building' with 'tag'"""
_ret = []
for room in self.rooms:
if room['name'].lower() == building.lower():
for pos in room['walking_space']:
for item in self.items[pos[0]][pos[1]]:
if item['type'] == 'storage':
for _item in item['items']:
if _item.has_key(tag) and _item[tag]:
_ret.append(_item)
else:
if item.has_key(tag) and item[tag]:
_ret.append(item)
return _ret
def get_all_items_in_building_of_type(self,building,type):
"""Returns all items in 'building' of 'type'"""
_ret = []
if isinstance(type,list): _list = True
else: _list = False
for room in self.rooms:
if room['name'].lower() == building.lower():
for pos in room['walking_space']:
for item in self.items[pos[0]][pos[1]]:
if item['type'] == 'storage':
for _item in item['items']:
if _list:
if _item['type'] in type:
_ret.append(_item)
else:
if _item['type'] == type:
_ret.append(_item)
if _list:
if item['type'] in type:
_ret.append(item)
else:
if item['type'] == type:
_ret.append(item)
return _ret
def remove_item_from_building(self,item,building):
"""Removes 'item' from 'building'"""
for room in self.rooms:
if room['name'].lower() == building.lower():
for pos in room['walking_space']:
for _item in self.items[pos[0]][pos[1]]:
if _item['type'] == 'storage':
for __item in _item['items']:
if __item == item:
_item['items'].remove(__item)
return True
if _item == item:
self.items[pos[0]][pos[1]].remove(_item)
return True
return False
def get_all_solid_items(self):
_ret = []
_a = time.time()
for item in self.items_shortcut:
if item['solid']:
_ret.append(item)
return _ret
def get_open_buildings_of_type(self,type):
_ret = []
for room in self.rooms:
if room['owner']: continue
if room['type'] == type: _ret.append(room)
return _ret
def get_open_buildings_with_items(self,items):
_ret = []
for room in self.rooms:
if room['owner']: continue
_needs = items[:]
for pos in room['walking_space']:
for item in self.items[pos[0]][pos[1]]:
if item['type'] in _needs:
_needs.remove(item['type'])
if not _needs: _ret.append(room)
return _ret
def get_all_buildings_of_type(self,type):
_ret = []
for room in self.rooms:
if room['type'].lower() == type.lower():
_ret.append(room)
return _ret
def get_open_space_around(self,pos,dist=5):
"""Returns all open spaces around 'pos' in xrange 'dist'"""
_ret = []
for x1 in xrange(-dist,dist+1):
x = pos[0]+x1
if x<0 or x>=self.size[0]: continue
for y1 in xrange(-dist,dist+1):
y = pos[1]+y1
if y<0 or y>=self.size[1]: continue
if self.map[x][y] in var.solid or self.map[x][y] in var.blocking:
continue
_ret.append((x,y))
return _ret
def get_real_estate(self,pos,size):
_ret = []
for (x1,y1) in self.get_open_space_around(pos,dist=40):
_break = False
for x2 in xrange(size[0]):
if x1+x2>=self.size[0]: _break=True;break
for y2 in xrange(size[1]):
if y1+y2>=self.size[1]-1: _break=True;break
_pos = (x1+x2,y1+y2)
if (x1+x2,y1+y2) in self.real_estate or self.map[_pos[0]][_pos[1]] in var.blocking or\
self.map[_pos[0]][_pos[1]] in var.solid:
_break = True
break
if _break: break
if _break: break
else: _ret.append((x1,y1))
return _ret
def claim_real_estate(self,pos,size):
for x1 in xrange(size[0]):
for y1 in xrange(size[1]):
self.real_estate.append((pos[0]+x1,pos[1]+y1))
def has_item_type_at(self,type,pos):
for item in self.items[pos[0]][pos[1]]:
if item['type'] == type:
return True
return False
def has_solid_item_at(self,pos):
for item in self.items[pos[0]][pos[1]]:
if item['solid']:
return True
return False
def remove_item_at(self,item,pos):
for _item in self.items_shortcut:
if _item['type'] == 'storage':
for __item in _item['items']:
if __item == item:
_item['items'].remove(__item)
if _item == item:
self.remove_item(pos,item)
def get_room(self,name):
for room in self.rooms:
if room['name'].lower() == name.lower():
return room
return False
def get_room_items(self,name):
_ret = []
for room in self.rooms:
if room['name'].lower() == name.lower():
for pos in room['walking_space']:
for item in self.items[pos[0]][pos[1]]:
if item['type'] == 'storage':
for _item in item['items']:
_ret.append(_item)
else:
_ret.append(item)
return _ret
def dofov(self,pos,x,y,dist,efov=False):
#This next bit comes from http://roguebasin.roguelikedevelopment.org/index.php/Eligloscode
#I translated it to Python. You are welcome to use this code instead of writing your own :)
i = 0
ox = 0
oy = 0
ox = pos[0]+0.5
oy = pos[1]+0.5
while i<dist:
i+=1
if int(ox) >= self.size[0] or int(oy) >= self.size[1]: continue
if int(ox) < 0 or int(oy) < 0: continue
self.fmap[int(ox)][int(oy)]=1
self.vmap[int(ox)][int(oy)]=1
if self.map[int(ox)][int(oy)] in var.solid or\
self.has_item_type_at('solid',(int(ox),int(oy))): return
ox+=x;
oy+=y;
def light(self,pos):
self.vmap = [[self.outside] * self.size[1] for i in xrange(self.size[0])]
if self.outside: return
x = 0
y = 0
i = 0
self.fov = []
while i<360:
x=math.cos(i*0.01745);
y=math.sin(i*0.01745);
self.dofov(pos,x,y,10);
i+=1
def tick(self):
for item in self.get_all_items_of_type(['seed','stove','forge'],check_storage=False):
if item['type'] == 'seed':
if item.has_key('planted_by') and item['growth']==item['growth_max']:
self.remove_item(item['pos'],item)
_i = self.add_item(item['makes'],item['pos'])
_i['planted_by'] = item['planted_by']
if item['growth']<item['growth_max']:
if item['growth_time']>=item['growth_time_max']:
item['growth']+=1
item['image_index']+=1
item['growth_time']=0
else:
item['growth_time']+=1
#print 'ticking',item['growth_time'],item['image_index']
elif item['type'] == 'stove':
if item['cooking'] and item['cooking']['type']=='food':
if item['cooking']['type']=='food' and\
item['cooking']['cook_time']: item['cooking']['cook_time']-=1
else:
item['cooking'] = self.add_item(item['cooking']['makes'],item['pos'],no_place=True)
elif item['type'] == 'forge':
if item['forging']:
if item['forge_time']>0: item['forge_time']-=1
elif not item['forge_time']:
item['forging'] = self.add_item(item['forging'],item['pos'],no_place=True)
item['forge_time'] = -1
def tick_lights(self):
for _l in self.lights:
light = self.lmap[_l[0]][_l[1]]
if self.lmap[_l[0]][_l[1]]['life']<=0:
self.lmap[_l[0]][_l[1]]['source'] = False
self.lmap[_l[0]][_l[1]]['color'] = (0,0,0)
self.lmap[_l[0]][_l[1]]['brightness'] = 0
self.lights.remove(_l)
continue
self.lmap[_l[0]][_l[1]]['life']-=1
if light['source']:
light['children'] = []
for _pos in draw.draw_circle(_l,light['brightness']):
if not (_pos) in light['children']:
light['children'].append(_pos)
def decompose(self,times,edgesonly=True,count=4,tile=-1,to=None,all=False):
if not to:
to = var.STONE
for i in xrange(times):
_map = copy.deepcopy(self.map)
for y in xrange(self.size[1]-1):
for x in xrange(self.size[0]-1):
if (x,y) in self.landmarks: continue
if self.map[x][y] and edgesonly: continue
_count = 0
for pos in [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]:
_x = x+pos[0]
_y = y+pos[1]
if 0>_x<self.size[0]-1: continue
if 0>_y<self.size[1]-1: continue
#print _x,_y
if tile==-1:
if self.map[_x][_y]:
_count+=1
elif tile>=0:
if self.map[_x][_y]==tile:
_count+=1
elif all:
_count+=1
if _count>=count:
_map[x][y]=random.choice(to)
self.map = _map
def decompose_ext(self,times,all=False,find=-1,to=-1,count=3,breakon=[]):
_ret = []
for i in xrange(times):
_map = copy.deepcopy(self.map)
for x in xrange(self.size[0]):
for y in xrange(self.size[1]):
if (x,y) in self.landmarks: continue
if self.map[x][y]==find and not all: continue
_count = 0
for pos in [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]:
_x = x+pos[0]
_y = y+pos[1]
if 0>_x or _x>self.size[0]-1: continue
if 0>_y or _y>self.size[1]-1: continue
if self.map[_x][_y] in breakon:
_count = 0
break
if self.map[_x][_y] == find:
_count+=1
if _count>=count:
_map[x][y]=to
if not (x,y) in _ret:
_ret.append((x,y))
self.map = _map
return _ret
def walk(self,walkers=7,intensity=(25,45),distance=(3,4),types=[],where=[]):
#Okay, this is a bit tricky...
#I did this kind of levelgen for a previous
#game and it looked okay...
#We'll see how it works here.
_walkers = []
_dirs = [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
_ret = []
for i in xrange(walkers):
_pos = random.choice(where)
_tile = random.choice(types)
_walkers.append([_pos[0],_pos[1],_dirs[:],_tile])
for i in xrange(random.randint(intensity[0],intensity[1])):
for walker in _walkers:
_pos=random.choice(walker[2])
walker[2].remove(_pos)
for i2 in xrange(random.randint(distance[0],distance[1])):
if not len(walker[2]):
walker[2] = _dirs[:]
_x = walker[0]+_pos[0]
_y = walker[1]+_pos[1]
#if (_x,_y) in self.landmarks: continue
if 1>_x or _x>self.size[0]-2: continue
if 1>_y or _y>self.size[1]-2: continue
walker[0] = _x
walker[1] = _y
for pos in [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]:
#if (_x+pos[0],_y+pos[1]) in self.landmarks: continue
if 1>_x+pos[0] or _x+pos[0]>=self.size[0]-2: continue
if 1>_y+pos[1] or _y+pos[1]>=self.size[1]-2: continue
self.map[_x+pos[0]][_y+pos[1]] = walker[3]
_ret.append((_x+pos[0],_y+pos[1]))
#if walker[3] in var.blocking:
# if (_x+pos[0],_y+pos[1]) in self.walking_space:
# self.walking_space.remove((_x+pos[0],_y+pos[1]))
self.map[_x][_y] = walker[3]
if not (_x,_y) in _ret:
_ret.append((_x,_y))
return _ret
def generate_cave(self, entrances=[(4,4)],exits=[],overlaprooms=False):
#We'll be generating the level in the following
#way:
# Place a small room around the entrance
# Randomly place rooms
# Mark chosen spot as a "landmark"
# Connect landmarks via tunnels
#Our map is currently all 0s
#In the end, we will have a mix of numbers
#0 - wall
#1 - floor
#2 - tunnel
#3 - door
self.entrances = entrances
self.exits = exits
#First, let's place our entrances+exits.
_places = entrances[:]
_places.extend(exits)
for pos in _places:
#We'll make a 3x3 area around it
for x in xrange(-1,2):
#One thing I suggest is making lines
#as compact as possible.
#For example, we'll be writing "entrance[0]+x"
#and "entrance[1]+y" a lot in the next three lines
#this can give us the impression that the line
#is complicated when it's just simple addition...
#Also doing more complex math OVER AND OVER
#will slow things down a lot, so it's better
#to just do it once and assign it to a variable
#Addition is by no means complicated, but it
#makes things more readable.
#As a rule of thumb, I always put an underscore
#before the variables I plan to throw away...
_x = pos[0]+x
for y in xrange(-1,2):
#We need to check to see if we're drawing
#inside the map first...
#By the way, a '\' in Python
#just lets us drop down a line in case
#a line gets too lengthy...
#Very handy!
#Another temp variable...
_y = pos[1]+y
if 0<_x<self.size[0]\
and 0<_y<self.size[1]:
self.map[_x][_y] = 1
if not (_x,_y) in self.walking_space:
self.walking_space.append((_x,_y))
if (_x,_y) in self.walls:
self.walls.remove((_x,_y))
#What we just did was "carve" out the room
#Imagine these as rooms in a cave or something,
#like the dungeons in Oblivion...
#We also add the open space we create to a
#"walking_space" list.
#We'll use this later, but just know that
#it marks places you could potentially walk
#(it does more than just that, though!)
#Now, here's where tunneling comes into play
#First, we keep track of all the major "landmarks"
#on our map.
#These are things like doors, exits, and the center
#of rooms.
#We'll use these as guidelines for our tunnels...
#Since we already have an entrance, add it to
#the list...
self.landmarks.append(pos)
#We'll want to place our rooms next
for i in xrange(self.max_rooms):
#To prevent our rooms from being too far apart,
#we want to randomly select a position and compare
#it to our landmark list...
_found = False
_room_size = (random.randint(self.room_size[0],self.room_size[1]),\
random.randint(self.room_size[0],self.room_size[1]))
#Here, we keep looking through the list of walls on the map
#Technically, every wall on the map could potentially be the
#cornerstone for a room, so we should check them all until we
#find one.
#NOTE:
#As you can see, we're using a while loop and checking the
#array "self.walls"
#If a position is randomly chosen from this array and it turns
#out to not be a good place to put the room, then we should
#remove it from the array so it doesn't get checked again.
#Here, I make a copy of the array...
_walls = self.walls[:]
#We'll be using this throughout the while loop, which
#will hopefully speed things up...
while not _found:
_found = True
#This array holds all the positions for every tile
#in the room.
_room = []
#Randomly select a position from our array of walls
_pos = random.choice(_walls)
#Remove the position from the array so it isn't checked
#again.
_walls.pop(_walls.index(_pos))
#Check to make sure the room will fit in this spot
if _pos[0]-(_room_size[0]/2)<=0 or _pos[0]+(_room_size[0]/2)>=self.size[0]: _found=False;continue
if _pos[1]-(_room_size[1]/2)<=0 or _pos[1]+(_room_size[1]/2)>=self.size[1]: _found=False;continue
#Start checking to see if the room "fits"
for x in xrange(-_room_size[0]/2,_room_size[0]/2):
_x = _pos[0]+x
for y in xrange(-_room_size[1]/2,_room_size[1]/2):
_y = _pos[1]+y
#ALRIGHT, IS YOUR BODY READY?
#This is the last check we do to make sure the room
#is okay. If we want to overlap rooms, then the next
#line will always be true and the room can begin
#being placed.
#IF a floor tile is detected, then the loop breaks
#and we restart the whole process.
if not overlaprooms and not self.map[_x][_y] in [0,2]:
_found = False
break
else:
#We're okay. Add the floor tiles to the array
#_room
_room.append((_x,_y))
if not _found: break
#We made it.
#Make sure the room is of proper size and begin placing.
if _found and len(_room)>=9:
__room = {'name':'cave_room','walls':[],'open_walls':[],'walking_space':_room,\
'door':None,'type':None}
#Find some open walls
#For every floor tile in the room...
for pos in _room:
#change the spot on the map to a floor tile
#and add this position to the "walking_space"
#array.
self.map[pos[0]][pos[1]] = random.choice(var.STONE)
self.walking_space.append(pos)
#Remove the position from the REAL self.walls
#array-- NOT the copy we made earlier
if pos in self.walls:
self.walls.remove(pos)
#Add it to our rooms array
self.rooms.append(__room)
#Instead of finding the center, just find a random
#spot in the array. This makes the tunnels look a
#bit more natural.
self.landmarks.append(random.choice(_room))
else:
_found = False
#Hang in there...
#This is the last big part.
#Now we're going to loop through all the landmarks we just
#placed and connect them in the best way possible...
#The following array tracks which landmarks have already been
#connected.
_done = []
for l1 in self.landmarks:
#This is concept I use a lot in my code
#It finds the nearest landmark to the one we're connecting.
_lowest = {'where':None,'dist':9000}
for l2 in self.landmarks:
#We can't connect to ourselves!
if l1 == l2 or l2 in _done: continue
#Find the distance between the two landmarks.
_dist = abs(l2[0]-l1[0])+abs(l2[1]-l1[1])
#If it's closer than the current one, then set _lowest
#to represent that.
if _dist<_lowest['dist']:
_lowest['dist'] = _dist
_lowest['where'] = l2
#If we couldn't connect it, then break (this is usually true
#for the last room)
if not _lowest['where']: break
#If we allow diagonal tunnels, then randomly
#choose between straight and diagonal here.
if random.randint(0,1) and self.diagtunnels:
_diag = True
_line = draw.draw_diag_line(l1,_lowest['where'])
else:
_diag = False
_line = draw.draw_line(l1,_lowest['where'])
#Now, for every position in the line, "tunnel" the map
for pos in _line:
if not self.map[pos[0]][pos[1]]:
#Diagonal tunnels require more space because the player
#can't move like this...
# ####
# ##..
# #@##
# #.##
if _diag:
for _pos in [(-1,-1),(0,-1),(1,-1),(-1,0),(0,0),(1,0),(-1,1),(0,1),(1,1)]:
__pos = (pos[0]+_pos[0],pos[1]+_pos[1])
if __pos[0]<=0 or __pos[0]>=self.size[0]: continue
if __pos[1]<=0 or __pos[1]>=self.size[1]: continue
self.map[__pos[0]][__pos[1]] = random.choice(var.STONE)
if not __pos in self.walking_space:
self.walking_space.append(__pos)
if __pos in self.walls:
self.walls.remove(__pos)
else:
#Else, change the map to a tunnel tile!
if pos[0]<0 or pos[0]>=self.size[0]: continue
if pos[1]<0 or pos[1]>=self.size[1]: continue
self.map[pos[0]][pos[1]] = random.choice(var.STONE)
#Add it to the walking_space array if it isn't there already...
if not pos in self.walking_space:
self.walking_space.append(pos)
#Remove the spot from the walls array also...