-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2236 lines (1859 loc) · 67.2 KB
/
Copy pathmain.py
File metadata and controls
2236 lines (1859 loc) · 67.2 KB
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 sys
import random
import signal
import pygame
import pgzero
from pgzero.constants import keys
from numpy import ndarray
from copy import deepcopy
from random import randint, choice, shuffle
from constants import *
from teestream import *
from sizetools import *
from cellactor import *
from objects import *
from common import *
from debug import debug
from image import *
from theme import *
from draw import *
from room import *
from level import Collection
from cmdargs import cmdargs
from game import game
from drop import draw_status_drops
from load import *
from flags import flags
from puzzle import create_puzzle, Puzzle
from solution import solution, set_solution_funcs
from joystick import scan_joysticks_and_state, emulate_joysticks_press_key, get_joysticks_arrow_keys
from clipboard import clipboard
from translate import _, set_lang
from mainscreen import main_screen_level
from sokobanparser import parse_sokoban_levels
from statusmessage import reset_status_messages, set_status_message, set_quick_status_message, draw_status_message
from processcmdargs import process_cmdargs, parse_clipboard_levels
signal.signal(signal.SIGINT, lambda signum, frame: print("\nInterrupted by user") or exit())
scale_to_display = False
# set data dir and default encoding for the whole program
pgzero.loaders.set_root(DATA_DIR)
# 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 = not cmdargs.no_music
is_music_started = False
is_sound_enabled = not cmdargs.no_sound
is_move_animate_enabled = True
is_level_intro_enabled = True
music_orig_volume = None
music_start_time = None
music_fadein_time = None
mode = "start"
puzzle = None
bg_image = None
game_time = 0
level_time = 0
idle_time = 0
last_regeneration_time = 0
class ArrowKeys:
def __init__(self):
self.reset()
def reset(self):
self.pressed = []
self.clicked = []
self.pending = []
self.reacted = []
self.reacted_prev = []
self.reacted_diff = None
self.reacted_time = None
arrow_keys = ArrowKeys()
level_title = None
level_name = None
level_goal = None
cell_images = {} # will be generated
revealed_map = 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
def is_any_drop_on_cell(cell):
if get_drop_on_cell(cell) or (enemy := get_actor_on_cell(cell, enemies)) and enemy.drop:
return True
return False
killed_enemies = []
level_title_time = 0
level_goal_time = 0
enter_room_idx = None
def get_bg_image():
return bg_image
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.lvl < level:
return
if descr:
print(descr)
if full_format:
full = True
combined = True
dual = False
portal_cells = []
print("# Dungeon %s anonymous map %dx%d" % (puzzle.__class__.__name__ if puzzle else "non-puzzle", MAP_SIZE_X, MAP_SIZE_Y))
def get_cell_type_with_clean_floor(cell):
return CELL_FLOOR if clean and game.map[cell] in CELL_FLOOR_TYPES else game.map[cell]
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(get_cell_type_with_clean_floor(cell), end="")
if dual and cell_chars:
print(" ", end="")
for cx in MAP_X_RANGE if full else PLAY_X_RANGE:
cell = (cx, cy)
print(cell_chars.get(cell, get_cell_type_with_clean_floor(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 = get_cell_type_with_clean_floor(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 barrel := get_actor_on_cell(cell, barrels):
cell_ch = actor_chars['mirror' if barrel.mirror else 'barrel']
if cart := get_actor_on_cell(cell, carts):
cell_ch = CART_CHARS[1 if cart.mirror else 0][cart.type]
if lift := get_actor_on_cell(cell, lifts):
cell_ch = LIFT_CHARS[1 if lift.mirror else 0][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="")
if full_format and cell_ch == CELL_PORTAL:
portal_cells.append(cell)
print()
if full_format:
for cell in portal_cells:
if dest_cell := portal_destinations.get(cell):
print(portal_cells.index(dest_cell) if dest_cell in portal_cells else ' '.join(map(str, portal_destinations[cell])))
else:
print("")
for extra_value in puzzle.get_map_extra_values() if puzzle else ():
line = ' '.join(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, void_is_like_wall=False):
if game.map[cell] not in CELL_WALL_TYPES:
return False
wall_types = (*CELL_WALL_TYPES, CELL_VOID) if void_is_like_wall else CELL_WALL_TYPES
for neigh in get_all_neighbors(cell):
if is_cell_in_map(neigh) and game.map[neigh] not in wall_types:
return False
return True
def replace_outer_walls(*cell_types):
for cy in MAP_Y_RANGE:
for cx in MAP_X_RANGE:
cell = cx, cy
if game.map[cell] == CELL_OUTER_WALL:
game.map[cell] = choice(cell_types)
def convert_outer_walls(cell_type=None, void_is_like_wall=False):
for cy in MAP_Y_RANGE:
for cx in MAP_X_RANGE:
cell = cx, cy
if is_outer_wall(cell, void_is_like_wall=void_is_like_wall):
game.map[cell] = 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 MAP_Y_RANGE:
for cx in MAP_X_RANGE:
if not (cx == 0 or cy == 0 or cx == MAP_SIZE_X - 1 or cy == MAP_SIZE_Y - 1):
continue
cell = cx, cy
if game.map[cell] in CELL_FLOOR_TYPES and not cell in floor_cells_to_convert:
floor_cells_to_convert.update(get_accessible_cells(cell, place=True))
for cell in floor_cells_to_convert:
game.map[cell] = CELL_OUTER_WALL
if cell_type is not None:
replace_outer_walls(cell_type)
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=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 game.map[cell] in CELL_ENEMY_PLACE_OBSTACLES or is_cell_occupied(cell, True) or is_portal_destination(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 game.level.actors_always_revealed:
return actors
revealed_actors = []
for actor in actors:
if revealed_map[actor.c]:
revealed_actors.append(actor)
return revealed_actors
def set_room_and_notify_puzzle(idx):
set_room(idx)
puzzle.on_set_room()
# only to be used by puzzle's restore_level
def advance_room():
if room.idx + 1 >= flags.NUM_ROOMS:
return False
set_room_and_notify_puzzle(room.idx + 1)
return True
def enter_room(idx):
global mode
set_room_and_notify_puzzle(idx)
reset_status_messages()
char.reset_animation()
char.reset_inplace_animation()
arrow_keys.reset()
place_char_in_room()
reveal_map_near_char()
if game.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()
puzzle.on_enter_room()
char.phased = puzzle.is_char_phased()
char.set_h_flip_facing((char.cx - room.x1) * 2 < room.size_x)
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):
if not room.is_cell_inside(cell):
return False
is_cell_blocked = game.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, place=False, 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 game.map[neigh] == CELL_GATE0 or
is_cell_accessible(neigh, obstacles, place, 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, place=False):
accessible_cells = []
unprocessed_cells = [start_cell]
while unprocessed_cells:
cell = unprocessed_cells.pop(0)
accessible_cells.append(cell)
neigbours = get_accessible_neighbors(cell, obstacles, place)
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_obstacles, allow_enemy=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_obstacles, allow_enemy=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
# like find_path, but return all paths with the shortest distance from start to target
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=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_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 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.lvl > 0:
char.c = (0, 0)
else:
quit()
def place_char_in_room():
if game.char_cells[room.idx]:
char.c = game.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 game.map[cell] in (*CELL_WALL_TYPES, CELL_VOID, CELL_INTERNAL1):
game.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):
game.map[x, random_y] = CELL_WALL
for y in range(y1, y2 + 1):
game.map[random_x, y] = CELL_WALL
# select 3 random holes on the 4 just created wall walls
def set_floor_on(x, y):
game.map[x, y] = get_random_floor_cell_type()
skipped_wall = randint(0, 3)
if skipped_wall != 0: set_floor_on(get_random_even_point(x1, random_x - 1), random_y)
if skipped_wall != 1: set_floor_on(random_x, get_random_even_point(y1, random_y - 1))
if skipped_wall != 2: set_floor_on(get_random_even_point(random_x + 1, x2), random_y)
if skipped_wall != 3: set_floor_on(random_x, get_random_even_point(random_y + 1, y2))
# 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:
game.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)
game.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):
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 game.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 = game.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
game.map[neigh] = old_cell_type
return False
def get_random_floor_cell():
while True:
cell = randint(room.x1, room.x2), randint(room.y1, room.y2)
if game.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()
game.map[cell] = cell_type
extra_cells = []
if extra_num:
for i in range(extra_num):
extra_cell = get_random_floor_cell()
game.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 switch_cell_type(cell, new_cell_type, duration):
game.remember_map_cell(cell)
switch_cell_infos[cell] = (game.map[cell], new_cell_type, level_time + duration, duration)
game.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 = game.map[gate_cell]
gate_cell_types = (CELL_TRAP1, CELL_TRAP0) if cell_type in (CELL_TRAP0, CELL_TRAP1) else (CELL_GATE0, CELL_GATE1)
if cell_type not in gate_cell_types:
die("Called toggle_gate not on CELL_GATE or CELL_TRAP")
if cell_type == gate_cell_types[1]:
sound_name = 'close.wav'
new_cell_type = gate_cell_types[0]
else:
sound_name = 'open.wav'
new_cell_type = gate_cell_types[1]
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]
game.remember_obj_state(actor)
actor.phased = is_phased
actor.activate_inplace_animation(level_time, ACTOR_PHASED_DURATION, opacity=opacity, tween="decelerate", on_finished=lambda: actor.reset_opacity())
play_sound(sound_name)
class Globals:
get_actor_neighbors = get_actor_neighbors
get_all_neighbors = get_all_neighbors
get_bg_image = get_bg_image
debug_map = debug_map
is_cell_in_map = is_cell_in_map
convert_outer_walls = convert_outer_walls
convert_outer_floors = convert_outer_floors
is_cell_occupied = is_cell_occupied
advance_room = advance_room
start_accessible_obstacles = start_accessible_obstacles
clear_accessible_obstacles = clear_accessible_obstacles
is_cell_accessible = is_cell_accessible
get_accessible_neighbors = get_accessible_neighbors
get_accessible_cells = get_accessible_cells
get_accessible_cell_distances = get_accessible_cell_distances
get_all_accessible_cells = get_all_accessible_cells
get_num_accessible_target_directions = get_num_accessible_target_directions
find_path = find_path
find_all_paths = find_all_paths
find_best_path = find_best_path
is_path_found = is_path_found
get_farthest_accessible_cell = get_farthest_accessible_cell
get_closest_accessible_cell = get_closest_accessible_cell
place_char_in_topleft_accessible_cell = place_char_in_topleft_accessible_cell
get_random_floor_cell_type = get_random_floor_cell_type
convert_to_floor_if_needed = convert_to_floor_if_needed
generate_random_free_path = generate_random_free_path
get_random_floor_cell = get_random_floor_cell
replace_random_floor_cell = replace_random_floor_cell
switch_cell_type = switch_cell_type
demolish_portal = demolish_portal
toggle_gate = toggle_gate
toggle_actor_phased = toggle_actor_phased
def generate_room(idx):
set_room_and_notify_puzzle(idx)
if flags.is_random_maze:
generate_random_maze_room()
if flags.is_spiral_maze:
generate_spiral_maze()
if flags.is_grid_maze:
generate_grid_maze()
accessible_cells = None
finish_cell = None
if flags.has_finish or puzzle.is_finish_cell_required():
char.c = (room.x1, room.y1)
game.set_char_cell(char.c)
if flags.has_start:
game.map[char.c] = CELL_START
accessible_cells = get_all_accessible_cells()
accessible_cells.pop(0) # remove char cell
if not accessible_cells:
debug_map()
die("Requested to generate finish cell with no accessible cells")
finish_cell = accessible_cells.pop()
game.map[finish_cell] = CELL_FINISH
puzzle.set_finish_cell(accessible_cells, finish_cell)
puzzle.generate_room()
# generate enemies
if char.power:
return
for i in range(game.level.num_enemies):
place_char_in_room()
num_tries = 10000
while num_tries > 0:
cx = randint(room.x1, room.x2)
cy = randint(room.y1, room.y2)
if not is_cell_occupied_for_enemy((cx, cy)):
break
num_tries -= 1
if num_tries == 0:
print("Was not able to find free spot for enemy in 10000 tries, positioning it anyway on an obstacle")
create_enemy((cx, cy))
def generate_map():
game.map = ndarray((MAP_SIZE_X, MAP_SIZE_Y), dtype='U5')
bw = 0 if flags.MULTI_ROOMS and not puzzle.has_border() else 1
for cy in MAP_Y_RANGE:
for cx in MAP_X_RANGE:
if cx == PLAY_X1 - bw or cx == PLAY_X2 + bw or cy == PLAY_Y1 - bw or cy == PLAY_Y2 + bw:
cell_type = CELL_WALL
else:
if cx in flags.ROOM_BORDERS_X or cy in flags.ROOM_BORDERS_Y:
cell_type = CELL_WALL
else:
cell_type = get_random_floor_cell_type()
game.map[cx, cy] = cell_type
if game.level.map_file or game.level.map_string:
filename_or_stringio = game.level.map_file or io.StringIO(game.level.map_string)
if ret := load_map(filename_or_stringio, puzzle.load_map_special_cell_types):
if flags.MULTI_ROOMS:
print("Ignoring multi-room level config when loading map")
puzzle.set_map()
set_room_and_notify_puzzle(0)
puzzle.on_load_map(*ret)
return
puzzle.set_map()
for idx in range(flags.NUM_ROOMS):
generate_room(idx)
puzzle.on_generate_map()
def set_theme(theme_name):
global cell_images, status_image, cloud_image
set_theme_name(theme_name)
image1 = create_theme_image('wall')
image2 = create_theme_image('floor')
image3 = create_theme_image('crack')
image4 = create_theme_image('bones')
image5 = create_theme_image('rocks')
image6 = create_theme_image('plate') if puzzle.has_plate() else None
image7 = create_theme_image('start') if flags.has_start or puzzle.has_start() else None
image8 = create_theme_image('finish') if flags.has_finish or puzzle.has_finish() else None
image9 = create_theme_image('portal') if puzzle.has_portal() else None
image10 = create_theme_image('gate0') if puzzle.has_gate() else None
image11 = create_theme_image('gate1') if puzzle.has_gate() else None
image12 = create_theme_image('sand') if puzzle.has_sand() else None
image13 = create_theme_image('lock1') if puzzle.has_locks() else None
image14 = create_theme_image('lock2') if puzzle.has_locks() else None
image15 = create_theme_image('odirl') if puzzle.has_odirs() else None
image16 = create_theme_image('odirr') if puzzle.has_odirs() else None
image17 = create_theme_image('odiru') if puzzle.has_odirs() else None
image18 = create_theme_image('odird') if puzzle.has_odirs() else None
image19 = create_theme_image('glass') if puzzle.has_glass() else None
image20 = create_theme_image('trap0') if puzzle.has_trap() else None
image21 = create_theme_image('trap1') if puzzle.has_trap() else None
image22 = create_theme_image('beamgn') if puzzle.has_beam() else None
image23 = create_theme_image('beamcl') if puzzle.has_beam() else None
status_image = create_theme_image('status')
cloud_image = create_theme_image('cloud') if flags.is_cloud_mode and not bg_image else None
outer_wall_image = load_theme_cell_image('wall')
outer_wall_image.fill((50, 50, 50), special_flags=pygame.BLEND_RGB_SUB)
cell_images = {
CELL_WALL: image1,
CELL_FLOOR: image2,
CELL_CRACK: image3,
CELL_BONES: image4,
CELL_ROCKS: image5,
CELL_PLATE: image6,
CELL_START: image7,
CELL_FINISH: image8,
CELL_PORTAL: image9,
CELL_GATE0: image10,
CELL_GATE1: image11,
CELL_SAND: image12,
CELL_LOCK1: image13,
CELL_LOCK2: image14,
CELL_ODIRL: image15,
CELL_ODIRR: image16,
CELL_ODIRU: image17,
CELL_ODIRD: image18,
CELL_GLASS: image19,
CELL_TRAP0: image20,
CELL_TRAP1: image21,
CELL_BEAMGN: image22,
CELL_BEAMCL: image23,
CELL_OUTER_WALL: outer_wall_image,
}
load_actor_theme_image(char, 'char')
load_actor_theme_image(cursor, 'cursor')
for enemy in enemies:
load_actor_theme_image(enemy, 'enemy')
for barrel in barrels:
reload_actor_theme_image(barrel)
for cart in carts:
reload_actor_theme_image(cart)
for lift in lifts:
reload_actor_theme_image(lift)
for mirror in mirrors:
reload_actor_theme_image(mirror)
for drop in drops:
drop.set_image(get_theme_image_name(drop.name))
puzzle.on_set_theme()
def set_music_fadein():
global music_orig_volume, music_start_time, music_fadein_time
music_orig_volume = music.get_volume()
music_start_time = level_time
music_fadein_time = level_time + MUSIC_FADEIN_DURATION
music.set_volume(0)
def reset_music_fadein():
global music_orig_volume, music_start_time, music_fadein_time
if music_orig_volume:
music.set_volume(music_orig_volume)
music_orig_volume = music_start_time = music_fadein_time = None
def start_music():
global is_music_started
if mode != "game" and mode != "end":
print("Called start_music outside of game or end")
return
is_music_started = True
if is_music_enabled:
set_music_fadein()
track = game.level.music if mode == "game" else "victory" if is_game_won else "defeat"
music.play(track)
def stop_music():
global is_music_started
is_music_started = False
if is_music_enabled:
music.stop()
reset_music_fadein()
def enable_music():
global is_music_enabled
if is_music_enabled:
return
is_music_enabled = True
if is_music_started:
start_music()
def disable_music():
global is_music_enabled, is_music_started
if not is_music_enabled:
return