-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
2258 lines (1866 loc) · 67 KB
/
main.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 os
import io
import random
import pygame
import pgzero
import builtins
from pgzero.constants import keys
from numpy import ndarray, chararray, array, any
from copy import deepcopy
from random import randint, choice, shuffle
from traceback import extract_stack
from constants import *
from leveltools import *
from translations import *
from cellactor import *
from objects import *
from game import game
from drop import draw_status_drops
from flags import flags
from puzzle import create_puzzle
from solution import solution, set_solution_funcs
from sizetools import *
from joystick import scan_joysticks_and_state, emulate_joysticks_press_key, get_joysticks_arrow_keys
from statusmessage import reset_status_messages, set_status_message, draw_status_message
lang = 'en'
def warn(error, with_trace=False):
print(error)
if with_trace:
for fs in extract_stack():
if fs.name in ("warn", "die"):
continue
print("%s:%d in %s\n %s" % (fs.filename, fs.lineno, fs.name, fs.line))
def die(error, with_trace=False):
warn(error, with_trace)
quit()
def autodetect_lang():
global lang
lang = 'en'
try:
if 'LANG' in os.environ:
lang0 = (os.environ['LANG'])[0:2]
if lang0 in translations:
lang = lang0
except:
pass
def _(str_key):
str = translations[lang][str_key] if str_key in translations[lang] else translations['en'][str_key] if str_key in translations['en'] else str_key
if lang == 'he' and str_key in translations[lang]:
str = str[::-1]
return str
autodetect_lang()
def load_map(filename_or_stringio, special_cell_types={}):
global map
is_stringio = type(filename_or_stringio) == io.StringIO
filename = "<from-string>" if is_stringio else filename_or_stringio
def print_error(error):
print("File %s: %s. Ignoring map file" % (filename, error))
if is_stringio:
print(filename_or_stringio.getvalue())
enemies.clear()
barrels.clear()
set_char_cell(None, 0)
if is_stringio:
file = filename_or_stringio
if DEBUG_LEVEL >= 2:
print(filename_or_stringio.getvalue())
else:
try:
file = open(filename, "r")
except:
print_error("Failed to open")
return
words = file.readline().split(" ")
if len(words) <= 1:
print_error("Invalid signature line, no expected space")
return
if words[0] != '#' or words[1] != 'Dungeon':
print_error("Invalid signature line, no expected '# Dungeon'")
return
size_str = words[-1].rstrip("\n")
sizes = size_str.split("x")
if len(sizes) != 2 or not sizes[0].isdigit() or not sizes[1].isdigit():
print_error("Invalid signature line, invalid size '%s'" % size_str)
return
size_x = int(sizes[0])
size_y = int(sizes[1])
if size_x != MAP_SIZE_X or size_y != MAP_SIZE_Y:
print_error("Invalid size %dx%d instead of %dx%d" % (size_x, size_y, MAP_SIZE_X, MAP_SIZE_Y))
return
orig_map = map.copy()
set_char_cell(None, 0)
line_n = 1
special_cell_infos = []
for y in range(0, size_y):
line = file.readline()
if line == '':
map = orig_map.copy()
print_error("Failed to read map line #%d" % line_n)
return
line = line.rstrip("\n")
for x in range(0, size_x):
if len(line) <= x:
map = orig_map.copy()
print_error("Failed to read char #%d in map line #%d" % (x + 1, line_n))
return
ch = line[x]
cell = (x, y)
if ch == CELL_START:
set_char_cell(cell, 0)
if ch in LIFT_TYPES_BY_CHAR:
create_lift(cell, LIFT_TYPES_BY_CHAR[ch])
ch = CELL_VOID
if ch in ACTOR_AND_PLATE_BY_CHAR:
actor_name, is_plate = ACTOR_AND_PLATE_BY_CHAR[ch]
ch = CELL_PLATE if is_plate else CELL_FLOOR
if actor_name == "key1":
drop_key1.instantiate(cell)
if actor_name == "key2":
drop_key2.instantiate(cell)
if actor_name == "enemy":
create_enemy(cell)
if actor_name == "barrel":
create_barrel(cell)
if actor_name == "char":
set_char_cell(cell, 0)
if actor_name == "npc":
special_cell_infos.append((cell, None))
if value_type := special_cell_types.get(ch):
special_cell_infos.append((cell, value_type))
map[x, y] = ch
line_n += 1
special_cell_values = {}
for cell, value_type in special_cell_infos:
if value_type is None:
special_cell_values[cell] = None
continue
line = file.readline()
if line == '':
map = orig_map.copy()
print_error("Failed to read value for special map cell %s" % str(cell))
return
str = line.rstrip("\n")
def parse_int(str):
return None if str == '-' else int(str)
try:
if value_type == 'str':
value = str
elif value_type == 'int':
value = parse_int(str)
elif value_type == 'ints':
value = tuple(builtins.map(parse_int, str.split()))
else:
raise ValueError("Unsupported value type %s" % value_type)
except Exception as e:
print_error("Error: \"%s\" in map line #%d" % (e, line_n))
return
special_cell_values[cell] = value
line_n += 1
extra_values = []
while True:
line = file.readline()
if line == '':
break
extra_values.append(line.rstrip("\n"))
file.close()
return (special_cell_values, extra_values)
def is_cell_in_area(cell, x_range, y_range):
return cell[0] in x_range and cell[1] in y_range
# get 4 neughbour cells for cell
def get_cell_neighbors(cell, x_range=None, y_range=None):
neighbors = []
for diff in ((-1, 0), (+1, 0), (0, -1), (0, +1)):
neigh = apply_diff(cell, diff)
if x_range is None or y_range is None or is_cell_in_area(neigh, x_range, y_range):
neighbors.append(neigh)
debug(3, "* get_cell_neighbors %s - %s" % (str(cell), neighbors))
return neighbors
# get 4 neughbour cells for actor
def get_actor_neighbors(actor, x_range=None, y_range=None):
return get_cell_neighbors(actor.c, x_range, y_range)
# get 8 or 9 neughbour cells for cell
def get_all_neighbors(cell, include_self=False):
neighbors = []
for dy in (-1, 0, +1):
for dx in (-1, 0, +1):
if dy == 0 and dx == 0 and not include_self:
continue
neighbors.append(apply_diff(cell, (dx, dy)))
return neighbors
is_game_won = False
is_music_enabled = True
is_music_started = False
is_sound_enabled = True
is_move_animate_enabled = True
is_level_intro_enabled = True
music_orig_volume = None
music_start_time = None
music_fadein_time = None
mode = "start"
is_main_screen = True
puzzle = None
bg_image = None
game_time = 0
level_time = 0
idle_time = 0
last_regeneration_time = 0
last_time_arrow_keys_processed = 0
pressed_arrow_keys = []
last_processed_arrow_keys = []
last_processed_arrow_diff = (0, 0)
map = None # will be generated
cell_images = {} # will be generated
revealed_map = None
theme_prefix = None
switch_cell_infos = {} # tuple(old_cell_type, new_cell_type, end_time, duration) per cell
portal_demolition_infos = {} # tuple(new_cell_type, start_time) per cell
def get_drop_on_cell(cell):
for drop in drops:
if drop.has_instance(cell):
return drop
return None
killed_enemies = []
level_title_time = 0
level_goal_time = 0
level = None
room = Area()
enter_room_idx = None
def get_bg_image():
return bg_image
def debug(level, str, depth=None):
if DEBUG_LEVEL < level:
return
if depth is not None:
print(" " * depth, end="")
print(str)
def debug_map(level=0, descr=None, full_format=False, full=True, clean=True, combined=True, dual=False, endl=False, char_cell=None, cell_chars={}):
if DEBUG_LEVEL < level:
return
if descr:
print(descr)
if full_format:
full = True
combined = True
dual = False
print("# Dungeon %s anonymous map %dx%d" % (puzzle.__class__.__name__ if puzzle else "non-puzzle", MAP_SIZE_X, MAP_SIZE_Y))
for cy in MAP_Y_RANGE if full else PLAY_Y_RANGE:
if not combined:
for cx in MAP_X_RANGE if full else PLAY_X_RANGE:
cell = (cx, cy)
print(CELL_FLOOR if clean and map[cell] in CELL_FLOOR_TYPES else map[cell], end="")
if dual:
print(" ", end="")
if dual or combined:
for cx in MAP_X_RANGE if full else PLAY_X_RANGE:
cell = (cx, cy)
cell_ch = CELL_FLOOR if clean and map[cell] in CELL_FLOOR_TYPES else map[cell]
actor_chars = ACTOR_ON_PLATE_CHARS if cell_ch == CELL_PLATE else ACTOR_CHARS
if cell in cell_chars:
cell_ch = cell_chars[cell]
if drop := get_drop_on_cell(cell):
cell_ch = actor_chars[drop.name]
if is_cell_in_actors(cell, enemies):
cell_ch = actor_chars['enemy']
if is_cell_in_actors(cell, barrels):
cell_ch = actor_chars['barrel']
if lift := get_actor_on_cell(cell, lifts):
cell_ch = LIFT_CHARS[lift.type]
if cell == char_cell or char.c is not None and char.c == cell:
cell_ch = actor_chars['char']
print(cell_ch, end="")
print()
if full_format:
for extra_value in puzzle.get_map_extra_values() if puzzle else ():
line = ' '.join(builtins.map(str, extra_value)) if hasattr(extra_value, '__iter__') else str(extra_value)
print(line)
if endl:
print()
def is_cell_in_map(cell):
return is_cell_in_area(cell, MAP_X_RANGE, MAP_Y_RANGE)
def is_outer_wall(cell):
if map[cell] not in CELL_WALL_TYPES:
return False
for neigh in get_all_neighbors(cell):
if is_cell_in_map(neigh) and map[neigh] not in CELL_WALL_TYPES:
return False
return True
def replace_outer_walls(*cell_types):
for cy in MAP_Y_RANGE:
for cx in MAP_X_RANGE:
if map[cx, cy] == CELL_OUTER_WALL:
map[cx, cy] = choice(cell_types)
def convert_outer_walls(cell_type=None):
for cy in MAP_Y_RANGE:
for cx in MAP_X_RANGE:
if is_outer_wall((cx, cy)):
map[cx, cy] = CELL_OUTER_WALL
if cell_type is not None:
replace_outer_walls(*cell_type)
def convert_outer_floors(cell_type=None):
floor_cells_to_convert = set()
for cy in (0, MAP_SIZE_Y - 1):
for cx in (0, MAP_SIZE_X - 1):
if map[cx, cy] in CELL_FLOOR_TYPES:
floor_cells_to_convert.update(get_accessible_cells((cx, cy)))
for cell in floor_cells_to_convert:
map[cell] = CELL_OUTER_WALL
if cell_type is not None:
replace_outer_walls(cell_type)
def get_theme_image_name(image_name):
for full_image_name in (theme_prefix + image_name, DEFAULT_IMAGE_PREFIX + image_name):
if os.path.isfile(IMAGES_DIR_PREFIX + full_image_name + '.png'):
debug(2, "Found image %s" % full_image_name)
return full_image_name
die("Unable to find image %s in neither %s nor %s" % (image_name, theme_prefix, DEFAULT_IMAGE_PREFIX))
def load_image(image_name, size, do_crop=False):
image = pygame.image.load(image_name).convert()
if do_crop:
# image=300x400 size=100x200 -> cropped=200x400
# image=300x400 size=200x100 -> cropped=300x150
w = image.get_width()
h = image.get_height()
if w * size[1] > h * size[0]:
crop_w = size[0] * h // size[1]
crop_h = h
crop_x = (w - crop_w) // 2
crop_y = 0
else:
crop_w = w
crop_h = size[1] * w // size[0]
crop_x = 0
crop_y = (h - crop_h) // 2
cropped_image = pygame.Surface((crop_w, crop_h), pygame.SRCALPHA, 32)
cropped_image.blit(image, (-crop_x, -crop_y))
image = cropped_image
return pygame.transform.scale(image, size)
def load_theme_cell_image(image_name):
return pygame.image.load(IMAGES_DIR_PREFIX + get_theme_image_name(image_name) + '.png').convert_alpha()
def colorize_cell_image(image, color, alpha=1):
cell_surface = pygame.Surface((CELL_W, CELL_H), pygame.SRCALPHA, 32)
cell_surface.fill((*color, alpha * 255))
cell_surface.blit(image, (0, 0))
return cell_surface
def create_cell_subimage(image, cell, starting_cell=(0, 0), rotate_angle=0):
cell_surface = pygame.Surface((CELL_W, CELL_H), pygame.SRCALPHA, 32)
cell = apply_diff(cell, starting_cell, subtract=True)
cell_surface.blit(image, (-cell[0] * CELL_W, -cell[1] * CELL_H))
if rotate_angle != 0:
cell_surface = pygame.transform.rotate(cell_surface, rotate_angle)
return cell_surface
def create_text_cell_image(text, color='#E0E0E0', gcolor="#408080", owidth=1.2, ocolor="#004040", alpha=1, fontsize=48):
cell_surface = pygame.Surface((CELL_W, CELL_H), pygame.SRCALPHA, 32)
pgzero.ptext.draw(text, surf=cell_surface, center=cell_to_pos((0, 0)), color=color, gcolor=gcolor, owidth=owidth, ocolor=ocolor, alpha=alpha, fontsize=fontsize)
return cell_surface
def is_portal_destination(cell):
return cell in {v: k for k, v in portal_destinations.items()}
def is_cell_occupied_except_char(cell, include_phased=False):
if is_cell_in_actors(cell, enemies + barrels, include_phased):
return True
return get_drop_on_cell(cell) is not None
def is_cell_occupied(cell, include_phased=False):
return is_cell_occupied_except_char(cell, include_phased) or char.c == cell
# used for positioning enemies during level generation
def is_cell_occupied_for_enemy(cell):
return map[cell] in CELL_ENEMY_PLACE_OBSTACLES or is_cell_occupied(cell, True) or is_portal_destination(cell)
def create_theme_image(image_name):
return CellActor(get_theme_image_name(image_name))
def create_theme_actor(image_name, cell):
return create_actor(get_theme_image_name(image_name), cell)
def reveal_map_near_char():
if not flags.is_cloud_mode:
return
for cell in get_all_neighbors(char.c, include_self=True):
revealed_map[cell] = True
def get_revealed_actors(actors):
if not flags.is_cloud_mode or level.get("actors_always_revealed", False):
return actors
revealed_actors = []
for actor in actors:
if revealed_map[actor.c]:
revealed_actors.append(actor)
return revealed_actors
def set_char_flip(is_right_dir=True):
char.flip = None if is_right_dir else (True, False)
def assert_room():
if mode != "game" and mode != "init" and mode != "next":
die("Called room function when not inside game or init (mode=%s). Fix this bug" % mode)
def set_room(idx):
room.size = flags.ROOM_SIZE(idx)
room.size_x = flags.ROOM_SIZE_X[idx]
room.size_y = flags.ROOM_SIZE_Y[idx]
room.x1 = flags.ROOM_X1[idx]
room.x2 = flags.ROOM_X2[idx]
room.y1 = flags.ROOM_Y1[idx]
room.y2 = flags.ROOM_Y2[idx]
room.x_range = flags.ROOM_X_RANGE[idx]
room.y_range = flags.ROOM_Y_RANGE[idx]
room.idx = idx
puzzle.set_room(room)
# only to be used by puzzle's restore_level
def advance_room():
if room.idx + 1 >= flags.NUM_ROOMS:
return False
set_room(room.idx + 1)
return True
def enter_room(idx):
global mode, char_cells
set_room(idx)
reset_status_messages()
place_char_in_room()
char_cells[idx] = char.c # needed for Alt-R
reveal_map_near_char()
char.reset_inplace()
char.reset_inplace_animation()
if map[char.c] == CELL_START:
char.activate_inplace_animation(level_time, CHAR_APPEARANCE_SCALE_DURATION, scale=(0, 1), angle=(180, 720))
cursor.reset()
mode = "game"
game.start_level(map)
puzzle.on_enter_room()
char.phased = puzzle.is_char_phased()
set_char_flip((char.cx - room.x1) * 2 < room.size_x)
def get_max_area_distance(area):
return cell_distance((area.x1, area.y1), (area.x2, area.y2))
def get_max_room_distance():
return get_max_area_distance(room)
def is_actor_in_room(actor):
assert_room()
return actor.cx >= room.x1 and actor.cx <= room.x2 and actor.cy >= room.y1 and actor.cy <= room.y2
def get_actors_in_room(actors):
return [actor for actor in actors if is_actor_in_room(actor)]
def is_cell_in_room(cell):
return is_cell_in_area(cell, room.x_range, room.y_range)
accessible_obstacles = None
def start_accessible_obstacles():
global accessible_obstacles
accessible_obstacles = set()
def clear_accessible_obstacles():
global accessible_obstacles
accessible_obstacles0 = accessible_obstacles
accessible_obstacles = None
return accessible_obstacles0
def is_cell_accessible(cell, obstacles=None, place=False, allow_obstacles=False, allow_enemy=False):
is_cell_blocked = map[cell] in (() if allow_obstacles else CELL_CHAR_PLACE_OBSTACLES if place else CELL_CHAR_MOVE_OBSTACLES)
if obstacles is not None:
if accessible_obstacles is not None and cell in obstacles:
accessible_obstacles.add(cell)
return False if is_cell_blocked or cell in obstacles else True
if is_cell_blocked:
return False
return not is_cell_in_actors(cell, barrels if allow_enemy else barrels + enemies)
def get_accessible_neighbors(cell, obstacles=None, allow_obstacles=False, allow_enemy=False, allow_closed_gate=False, allow_stay=False):
neighbors = []
if ALLOW_DIAGONAL_MOVES and False:
directions = ((-1, -1), (0, -1), (+1, -1), (-1, 0), (+1, 0), (-1, +1), (0, +1), (+1, +1))
else:
directions = ((-1, 0), (+1, 0), (0, -1), (0, +1))
for diff in directions + ((0, 0),) if allow_stay else directions:
neigh = apply_diff(cell, diff)
if is_cell_in_room(neigh) and (
allow_closed_gate and map[neigh] == CELL_GATE0 or
is_cell_accessible(neigh, obstacles, allow_obstacles=allow_obstacles, allow_enemy=allow_enemy)
):
neighbors.append(neigh)
debug(3, "* get_accessible_neighbors %s - %s" % (str(cell), neighbors))
return neighbors
def get_accessible_cells(start_cell, obstacles=None):
accessible_cells = []
unprocessed_cells = [start_cell]
while unprocessed_cells:
cell = unprocessed_cells.pop(0)
accessible_cells.append(cell)
neigbours = get_accessible_neighbors(cell, obstacles)
for n in neigbours:
if n not in accessible_cells and n not in unprocessed_cells:
unprocessed_cells.append(n)
return accessible_cells
def get_accessible_cell_distances(start_cell, obstacles=None, allow_obstacles=False, allow_enemy=False):
accessible_cells = []
accessible_cell_distances = {start_cell: 0}
unprocessed_cells = [start_cell]
while unprocessed_cells:
cell = unprocessed_cells.pop(0)
accessible_distance = accessible_cell_distances[cell]
accessible_cells.append(cell)
neigbours = get_accessible_neighbors(cell, obstacles, allow_obstacles, allow_enemy)
for n in neigbours:
if n not in accessible_cells and n not in unprocessed_cells:
unprocessed_cells.append(n)
accessible_cell_distances[n] = accessible_distance + 1
return accessible_cell_distances
def get_all_accessible_cells():
return get_accessible_cells(char.c)
def get_num_accessible_target_directions(start_cell, target_cells):
num_accessible_directions = 0
for neigh in get_accessible_neighbors(start_cell, allow_closed_gate=True):
unprocessed_cells = [ neigh ]
accessible_cells = [ start_cell, neigh ]
while unprocessed_cells:
cell = unprocessed_cells.pop(0)
if cell in target_cells:
num_accessible_directions += 1
break
for new_neigh in get_accessible_neighbors(cell, allow_closed_gate=True):
if new_neigh in accessible_cells:
continue
accessible_cells.append(new_neigh)
unprocessed_cells.append(new_neigh)
return num_accessible_directions
def find_path(start_cell, target_cell, obstacles=None, allow_obstacles=False, allow_enemy=False, randomize=True):
if start_cell == target_cell:
return []
accessible_cell_distances = get_accessible_cell_distances(start_cell, obstacles, allow_obstacles, allow_enemy)
accessible_distance = accessible_cell_distances.get(target_cell)
if accessible_distance is None:
return None
path_cells = [target_cell]
while accessible_distance > 1:
accessible_distance -= 1
neigh_cells = get_accessible_neighbors(path_cells[0], obstacles, allow_obstacles, allow_enemy)
if randomize:
shuffle(neigh_cells)
for neigh_cell in neigh_cells:
neigh_distance = accessible_cell_distances.get(neigh_cell)
if neigh_distance == accessible_distance:
path_cells.insert(0, neigh_cell)
break
return path_cells
def find_all_paths(start_cell, target_cell, obstacles=None, allow_obstacles=False):
if start_cell == target_cell:
return [()]
accessible_cell_distances = get_accessible_cell_distances(start_cell, obstacles, allow_obstacles)
accessible_distance = accessible_cell_distances.get(target_cell)
if accessible_distance is None:
return None
all_path_cells = [(target_cell,)]
while accessible_distance > 1:
accessible_distance -= 1
new_all_path_cells = []
for path_cells in all_path_cells:
neigh_cells = [cell for cell in get_accessible_neighbors(path_cells[0], obstacles, allow_obstacles)
if accessible_cell_distances.get(cell) == accessible_distance]
for neigh_cell in neigh_cells:
new_all_path_cells.append((neigh_cell, *path_cells))
all_path_cells = new_all_path_cells
return all_path_cells
def find_best_path(start_cell, target_cell, obstacles=None, allow_obstacles=False, randomize=True,
cost_func=None, set_path_cost=None, allow_stay=False, state_func=None
):
if start_cell == target_cell:
return []
def _pack_state(cell, old_cell, old_state):
if state_func:
state = state_func(cell, old_cell, old_state)
return None if state is None else (cell, state)
else:
return cell
def _unpack_state(cell_state):
return cell_state if state_func else (cell_state, None)
if not (start_cell_state := _pack_state(start_cell, None, None)):
return None
target_cell_state = None
visited_cells = {start_cell_state: [None, 0]} # cell_state: [parent, cost]
processed_cells = []
unprocessed_cells = [start_cell_state]
while unprocessed_cells:
cell_state = unprocessed_cells.pop(0)
cell, state = _unpack_state(cell_state)
processed_cells.append(cell_state)
if cell == target_cell:
target_cell_state = cell_state
break
neigbours = get_accessible_neighbors(cell, obstacles, allow_obstacles, allow_stay=allow_stay)
if randomize:
shuffle(neigbours)
for neigh in neigbours:
if not (neigh_state := _pack_state(neigh, cell, state)):
continue
if neigh_state in processed_cells:
continue
if cost_func:
cost = cost_func(neigh, cell, visited_cells, start_cell, target_cell, obstacles)
else:
cost = 0
if cost is None:
continue
cost += visited_cells[cell_state][1]
if neigh_state not in visited_cells:
visited_cells[neigh_state] = [cell_state, cost]
unprocessed_cells.append(neigh_state)
unprocessed_cells.sort(key=lambda cell: visited_cells[neigh_state][1] + cell_distance(neigh, target_cell))
else:
if visited_cells[neigh_state][1] < cost:
visited_cells[neigh_state] = [cell_state, cost]
if not target_cell_state:
return None
best_path_cells = []
cell_state = target_cell_state
while cell_state != start_cell_state:
cell, _ = _unpack_state(cell_state)
best_path_cells.insert(0, cell)
if not cell_state in visited_cells:
print("BUG:", cell_state, visited_cells)
cell_state = visited_cells[cell_state][0]
if set_path_cost is not None:
set_path_cost[0] = visited_cells[target_cell_state][1]
return best_path_cells
def is_path_found(start_cell, target_cell, obstacles=None):
return target_cell in get_accessible_cells(start_cell, obstacles)
def set_char_cell(cell, room_idx=None):
global char_cells
char_cells[room.idx if room_idx is None else room_idx] = cell
def get_farthest_accessible_cell(start_cell):
accessible_cell_distances = get_accessible_cell_distances(start_cell)
return max(accessible_cell_distances, key=lambda cell: accessible_cell_distances[cell])
def get_closest_accessible_cell(start_cell, target_cell):
accessible_cells = get_accessible_cells(start_cell)
return min(accessible_cells, key=lambda cell: cell_distance(cell, target_cell))
def get_topleft_accessible_cell(start_cell):
return get_closest_accessible_cell(start_cell, (0, 0))
def place_char_in_closest_accessible_cell(target_cell):
char.c = get_closest_accessible_cell(char.c, target_cell)
def place_char_in_topleft_accessible_cell():
char.c = get_topleft_accessible_cell(char.c)
def place_char_in_first_free_spot():
for cell in room.cells:
if is_cell_accessible(cell, place=True):
char.c = cell
return
if lifts:
char.c = get_actors_in_room(lifts)[0].c
return
print("Was not able to find free spot for char, fix the level or a bug")
if DEBUG_LEVEL:
char.c = (0, 0)
else:
quit()
def place_char_in_room():
if char_cells[room.idx]:
char.c = char_cells[room.idx]
else:
place_char_in_first_free_spot()
def get_random_floor_cell_type():
return CELL_FLOOR_TYPES_FREQUENT[randint(0, len(CELL_FLOOR_TYPES_FREQUENT) - 1)]
def convert_to_floor_if_needed(cell):
if not cell:
warn("Called convert_to_floor_if_needed without cell, ignoring", True)
return
if map[cell] in (*CELL_WALL_TYPES, CELL_VOID, CELL_INTERNAL1):
map[cell] = get_random_floor_cell_type()
def get_random_even_point(a1, a2):
return a1 + randint(0, int((a2 - a1) / 2)) * 2
def generate_random_maze_area(x1, y1, x2, y2):
if x2 - x1 <= 1 or y2 - y1 <= 1:
return
# select random point that will divide the area into 4 sub-areas
random_x = get_random_even_point(x1 + 1, x2 - 1)
random_y = get_random_even_point(y1 + 1, y2 - 1)
# create the horizontal and vertical wall via this point
for x in range(x1, x2 + 1):
map[x, random_y] = CELL_WALL
for y in range(y1, y2 + 1):
map[random_x, y] = CELL_WALL
# select 3 random holes on the 4 just created wall walls
skipped_wall = randint(0, 3)
if skipped_wall != 0: map[get_random_even_point(x1, random_x - 1), random_y] = get_random_floor_cell_type()
if skipped_wall != 1: map[random_x, get_random_even_point(y1, random_y - 1)] = get_random_floor_cell_type()
if skipped_wall != 2: map[get_random_even_point(random_x + 1, x2), random_y] = get_random_floor_cell_type()
if skipped_wall != 3: map[random_x, get_random_even_point(random_y + 1, y2)] = get_random_floor_cell_type()
# recurse into 4 sub-areas
generate_random_maze_area(x1, y1, random_x - 1, random_y - 1)
generate_random_maze_area(random_x + 1, y1, x2, random_y - 1)
generate_random_maze_area(x1, random_y + 1, random_x - 1, y2)
generate_random_maze_area(random_x + 1, random_y + 1, x2, y2)
def generate_grid_maze():
for cy in room.y_range:
for cx in room.x_range:
if (cx - room.x1 - 1) % 2 == 0 and (cy - room.y1 - 1) % 2 == 0:
map[cx, cy] = CELL_WALL
def generate_spiral_maze():
if randint(0, 1) == 0:
pointer = (room.x1 - 1, room.y1 + 1)
steps = ((1, 0), (0, 1), (-1, 0), (0, -1))
len = [room.x2 - room.x1, room.y2 - room.y1]
else:
pointer = (room.x1 + 1, room.y1 - 1)
steps = ((0, 1), (1, 0), (0, -1), (-1, 0))
len = [room.y2 - room.y1, room.x2 - room.x1]
dir = 0
while len[dir % 2] > 0:
step = steps[dir]
for i in range(len[dir % 2]):
pointer = apply_diff(pointer, step)
map[pointer] = CELL_WALL
if dir % 2 == 0:
len[0] -= 2
len[1] -= 2
dir = (dir + 1) % 4
def generate_random_maze_room():
generate_random_maze_area(room.x1, room.y1, room.x2, room.y2)
def generate_random_free_path(start_cell, target_cell, area=None, deviation=0, level=0):
global map
if randint(0, deviation) == 0:
start_cell = get_closest_accessible_cell(start_cell, target_cell)
if start_cell == target_cell:
return True
if area == None:
area = room
debug_path_str = "free path from %s to %s" % (str(start_cell), str(target_cell))
debug(2, "* [%d] generating %s" % (level, debug_path_str))
max_distance = get_max_area_distance(area)
accessible_cells = get_accessible_cells(start_cell)
weighted_neighbors = []
for cell in get_cell_neighbors(start_cell, area.x_range, area.y_range):
if cell in accessible_cells:
continue
if is_cell_in_actors(cell, barrels):
continue
weight = randint(0, max_distance)
weight -= cell_distance(cell, target_cell)
if map[cell] in CELL_FLOOR_TYPES:
weight -= randint(0, max_distance)
weighted_neighbors.append((weight, cell))
neighbors = [n[1] for n in sorted(weighted_neighbors, reverse=True)]
if not neighbors:
debug(2, "* [%d] failed to generate %s" % (level, debug_path_str))
return False
for neigh in neighbors:
old_cell_type = map[neigh]
if old_cell_type not in (*CELL_WALL_TYPES, CELL_VOID):
print("BUG!")
return False
convert_to_floor_if_needed(neigh)
debug(3, "* [%d] trying to move to %s" % (level, str(neigh)))
debug_map(3)
is_generated = generate_random_free_path(neigh, target_cell, area, deviation, level + 1)
if is_generated:
debug(2, "* [%d] successfully generated %s" % (level, debug_path_str))
if level == 0:
debug_map(2)
return True
map[neigh] = old_cell_type
return False
def create_barrel(cell):
global barrels
barrel = create_theme_actor("barrel", cell)
barrels.append(barrel)
def get_random_floor_cell():
while True:
cell = randint(room.x1, room.x2), randint(room.y1, room.y2)
if map[cell] in CELL_FLOOR_TYPES:
return cell
def replace_random_floor_cell(cell_type, num=1, callback=None, extra=None, extra_num=None):
for n in range(num):
cell = get_random_floor_cell()
map[cell] = cell_type
extra_cells = []
if extra_num:
for i in range(extra_num):
extra_cell = get_random_floor_cell()
map[extra_cell] = cell_type
extra_cells.append(extra_cell)
if callback:
if extra is not None:
callback(cell, extra, *extra_cells)
else:
callback(cell, *extra_cells)
def create_portal(cell, dst_cell):
if cell == dst_cell:
die("BUG: Portal destination can't be the same cell %s, exiting" % str(cell))
map[cell] = CELL_PORTAL
portal_destinations[cell] = dst_cell
def create_portal_pair(cell1, cell2):
create_portal(cell1, cell2)
create_portal(cell2, cell1)
def create_lift(cell, type, surface=None):
global lifts
image_name = "lift" + type
lift = create_actor(surface, cell) if surface else create_theme_actor(image_name, cell)
lift.type = type
lifts.append(lift)
def get_lift_target(cell, diff):
lift = get_actor_on_cell(cell, lifts)
if not lift or diff not in LIFT_TYPE_DIRECTIONS[lift.type]:
return None
while True:
next_cell = apply_diff(cell, diff)
if not is_cell_in_room(next_cell) or map[next_cell] != CELL_VOID or is_cell_in_actors(next_cell, lifts):
return cell if cell != lift.c else None
cell = next_cell
def get_lift_target_at_neigh(lift, neigh):
return get_lift_target(lift.c, cell_diff(lift.c, neigh))
def create_enemy(cell, health=None, attack=None, drop=None):
global enemies
enemy = Fighter("skeleton")
enemy.c = cell
enemy.power = health if char.power else None
enemy.health = None if char.power else health if health is not None else randint(MIN_ENEMY_HEALTH, MAX_ENEMY_HEALTH)
enemy.attack = None if char.power else attack if attack is not None else randint(MIN_ENEMY_ATTACK, MAX_ENEMY_ATTACK)
enemy.drop = None if char.power else drop if drop is not None else (None, drop_heart, drop_sword)[randint(0, 2)]
if enemy.drop:
enemy.drop.contain(enemy)
enemies.append(enemy)
def switch_cell_type(cell, new_cell_type, duration):
game.remember_map_cell(cell)
switch_cell_infos[cell] = (map[cell], new_cell_type, level_time + duration, duration)
map[cell] = new_cell_type
def demolish_portal(cell, new_cell_type=CELL_FLOOR):
portal_demolition_infos[cell] = (new_cell_type, level_time + PORTAL_DEMOLITION_DELAY)
def toggle_gate(gate_cell):
cell_type = map[gate_cell]
if cell_type not in (CELL_GATE0, CELL_GATE1):
die("Called toggle_gate not on CELL_GATE")
if cell_type == CELL_GATE1:
sound_name = 'close.wav'
new_cell_type = CELL_GATE0
else:
sound_name = 'open.wav'
new_cell_type = CELL_GATE1
switch_cell_type(gate_cell, new_cell_type, GATE_SWITCH_DURATION)
play_sound(sound_name)
def toggle_actor_phased(actor):
is_phased = not actor.phased
if is_phased:
sound_name = 'switch-on.wav'
opacity = [1, ACTOR_PHASED_OPACITY]
else:
sound_name = 'switch-off.wav'
opacity = [ACTOR_PHASED_OPACITY, 1]