-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathretux.py
executable file
·8753 lines (7356 loc) · 311 KB
/
retux.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
#!/usr/bin/env python3
# reTux
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__version__ = "1.6.3a0"
import argparse
import datetime
import gettext
import itertools
import json
import math
import os
import random
import shutil
import sys
import tempfile
import time
import traceback
import warnings
import weakref
import zipfile
import sge
import xsge_gui
import xsge_lighting
import xsge_path
import xsge_physics
import xsge_tiled
try:
from tkinter import Tk
import tkinter.filedialog as tkinter_filedialog
except ImportError:
HAVE_TK = False
else:
HAVE_TK = True
if getattr(sys, "frozen", False):
__file__ = sys.executable
DATA = tempfile.mkdtemp("retux-data")
CONFIG = os.path.join(
os.getenv("XDG_CONFIG_HOME", os.path.join(os.path.expanduser("~"),
".config")), "retux")
LOCAL = os.path.join(
os.getenv("XDG_DATA_HOME", os.path.join(os.path.expanduser("~"), ".local",
"share")), "retux")
dirs = [os.path.join(os.path.dirname(__file__), "data"),
os.path.join(LOCAL, "data")]
gettext.install("retux", os.path.abspath(os.path.join(dirs[0], "locale")),
names=["ngettext", "pgettext"])
parser = argparse.ArgumentParser()
parser.add_argument(
"--version", action="version", version=f"ReTux {__version__}",
help=_("Output version information and exit."))
parser.add_argument(
"-p", "--print-errors",
help=_("Print errors directly to stdout rather than saving them in a file."),
action="store_true")
parser.add_argument(
"-l", "--lang",
help=_("Manually choose a different language to use."))
parser.add_argument(
"--nodelta",
help=_("Disable delta timing. Causes the game to slow down when it can't "
"run at full speed instead of becoming choppier."),
action="store_true")
parser.add_argument(
"-d", "--datadir",
help=_('Where to load the game data from (Default: "{}")').format(dirs[0]))
parser.add_argument(
"--level",
help=_("Play the indicated level and then exit."))
parser.add_argument(
"--record",
help=_("Start the indicated level and record player actions in a "
"timeline. Useful for making cutscenes."))
parser.add_argument(
"--no-backgrounds",
help=_("Only show solid colors for backgrounds (uses less RAM)."),
action="store_true")
parser.add_argument(
"--no-hud", help=_("Don't show the player's heads-up display."),
action="store_true")
parser.add_argument("--god", help=_("Pray to your god. Choose wisely…"))
args = parser.parse_args()
PRINT_ERRORS = args.print_errors
DELTA = not args.nodelta
if args.datadir:
dirs[0] = args.datadir
LEVEL = args.level
RECORD = args.record
NO_BACKGROUNDS = args.no_backgrounds
NO_HUD = args.no_hud
GOD = False
HELL = False
if args.god:
if args.god.lower() == "nano":
GOD = True
elif args.god.lower() in {"emacs", "vi", "vim", "ed"}:
HELL = True
for d in dirs:
if os.path.isdir(d):
for dirpath, dirnames, filenames in os.walk(d, True, None, True):
dirtail = os.path.relpath(dirpath, d)
nd = os.path.join(DATA, dirtail)
for dirname in dirnames:
dp = os.path.join(nd, dirname)
if not os.path.exists(dp):
os.makedirs(dp)
for fname in filenames:
shutil.copy2(os.path.join(dirpath, fname), nd)
del dirs
gettext.install("retux", os.path.abspath(os.path.join(DATA, "locale")),
names=["ngettext", "pgettext"])
if args.lang:
lang = gettext.translation("retux",
os.path.abspath(os.path.join(DATA, "locale")),
[args.lang])
lang.install()
if GOD:
print(_("The text editor god of nano smiles upon you. God mode enabled!"))
elif HELL:
print(_("The true text editor god has sent you to hell for your heresy!"))
SCREEN_SIZE = [800, 480]
TILE_SIZE = 32
FPS = 56
DELTA_MIN = FPS / 2
DELTA_MAX = FPS * 4
TRANSITION_TIME = 750
DEFAULT_LEVELSET = "retux.json"
DEFAULT_LEVEL_TIME_BONUS = 90000
TUX_ORIGIN_X = 28
TUX_ORIGIN_Y = 16
TUX_KICK_TIME = 10
GRAVITY = 0.4
PLAYER_MAX_HP = 2 if HELL else 5
PLAYER_WALK_SPEED = 2
PLAYER_SKID_THRESHOLD = 3
PLAYER_RUN_SPEED = 4
PLAYER_MAX_SPEED = 5
PLAYER_ACCELERATION = 0.2
PLAYER_AIR_ACCELERATION = 0.1
PLAYER_FRICTION = 0.17
PLAYER_AIR_FRICTION = 0.03
PLAYER_JUMP_HEIGHT = 4 * TILE_SIZE + 2
PLAYER_RUN_JUMP_HEIGHT = 5 * TILE_SIZE + 2
PLAYER_STOMP_HEIGHT = TILE_SIZE / 2
PLAYER_FALL_SPEED = 8
PLAYER_SLIDE_ACCEL = 0.3
PLAYER_SLIDE_SPEED = 1
PLAYER_WALK_FRAMES_PER_PIXEL = 2 / 17
PLAYER_RUN_FRAMES_PER_PIXEL = 1 / 10
PLAYER_HITSTUN = 30 if HELL else 120
PLAYER_DIE_HEIGHT = 6 * TILE_SIZE
PLAYER_DIE_FALL_SPEED = 8
PLAYER_OFF_FLOOR_THRESHOLD = 2
SNOWMAN_WALK_SPEED = 3 if HELL else 2
SNOWMAN_STRONG_WALK_SPEED = 4 if HELL else 3
SNOWMAN_FINAL_WALK_SPEED = 6 if HELL else 4
SNOWMAN_STUNNED_WALK_SPEED = 8 if HELL else 6
SNOWMAN_ACCELERATION = 0.5 if HELL else 0.1
SNOWMAN_STRONG_ACCELERATION = 0.5 if HELL else 0.2
SNOWMAN_FINAL_ACCELERATION = 1 if HELL else 0.5
SNOWMAN_HOP_HEIGHT = 2 * TILE_SIZE
SNOWMAN_JUMP_HEIGHT = 7 * TILE_SIZE
SNOWMAN_JUMP_TRIGGER = 2 * TILE_SIZE
SNOWMAN_STOMP_DELAY = 30
SNOWMAN_WALK_FRAMES_PER_PIXEL = 1 / 4
SNOWMAN_HP = 20 if HELL else 5
SNOWMAN_STRONG_STAGE = 2
SNOWMAN_FINAL_STAGE = 3
SNOWMAN_HITSTUN = 120
SNOWMAN_SHAKE_NUM = 3
RACCOT_WALK_SPEED = 4 if HELL else 3
RACCOT_ACCELERATION = 0.2
RACCOT_HOP_HEIGHT = TILE_SIZE
RACCOT_JUMP_HEIGHT = 5 * TILE_SIZE
RACCOT_JUMP_TRIGGER = 2 * TILE_SIZE
RACCOT_STOMP_SPEED = 4
RACCOT_STOMP_DELAY = 15
RACCOT_WALK_FRAMES_PER_PIXEL = 1 / 22
RACCOT_HP = 20 if HELL else 5
RACCOT_HOP_TIME = 5
RACCOT_HOP_INTERVAL_MIN = 45
RACCOT_HOP_INTERVAL_MAX = 60 if HELL else 120
RACCOT_CHARGE_INTERVAL_MIN = 300
RACCOT_CHARGE_INTERVAL_MAX = 600
RACCOT_CRUSH_LAX = -8 # A negative lax makes it have the opposite effect.
RACCOT_CRUSH_GRAVITY = 0.6
RACCOT_CRUSH_FALL_SPEED = 15
RACCOT_CRUSH_SPEED = 12
RACCOT_CRUSH_CHARGE = TILE_SIZE
RACCOT_SHAKE_NUM = 4
HP_POINTS = 1000
TIMER_FRAMES = 40
HEAL_COINS = 20
CEILING_LAX = 10
STOMP_LAX = 8
BLOCK_HIT_HEIGHT = 8
ITEM_HIT_HEIGHT = 16
COIN_COLLECT_TIME = 30
COIN_COLLECT_SPEED = 2
ITEM_SPAWN_SPEED = 1
SECOND_POINTS = 100
COIN_POINTS = 100
ENEMY_KILL_POINTS = 50
AMMO_POINTS = 10
TUXDOLL_POINTS = 50000 if HELL else 5000
CAMERA_STOPPED_THRESHOLD = PLAYER_WALK_SPEED
CAMERA_STOPPED_HSPEED_MAX = 4
CAMERA_HSPEED_FACTOR = 1 / 2
CAMERA_VSPEED_FACTOR = 1 / 20
CAMERA_OFFSET_FACTOR = 10
CAMERA_MARGIN_TOP = 4 * TILE_SIZE
CAMERA_MARGIN_BOTTOM = 5 * TILE_SIZE
CAMERA_TARGET_MARGIN_BOTTOM = CAMERA_MARGIN_BOTTOM + TILE_SIZE
WARP_LAX = 12
WARP_SPEED = 3
WARP_EDGE_SPEED = 1.5
SHAKE_FRAME_TIME = FPS / DELTA_MIN
SHAKE_AMOUNT = 3
ENEMY_WALK_SPEED = 1
ENEMY_FALL_SPEED = 7
ENEMY_SLIDE_SPEED = 0.3
ENEMY_HIT_BELOW_HEIGHT = TILE_SIZE * 3 / 4
SNOWBALL_BOUNCE_HEIGHT = TILE_SIZE * 3 + 2
KICK_FORWARD_SPEED = 6
KICK_FORWARD_HEIGHT = TILE_SIZE * 3 / 4
KICK_UP_HEIGHT = 5.5 * TILE_SIZE
ICEBLOCK_GRAVITY = 0.6
ICEBLOCK_FALL_SPEED = 9
ICEBLOCK_FRICTION = 0.1
ICEBLOCK_DASH_SPEED = 7
JUMPY_BOUNCE_HEIGHT = TILE_SIZE * 4
BOMB_GRAVITY = 0.6
BOMB_TICK_TIME = 4
EXPLOSION_TIME = FPS * 3 / 4
ICICLE_LAX = TILE_SIZE * 3 / 4
ICICLE_SHAKE_TIME = FPS
ICICLE_GRAVITY = 0.75
ICICLE_FALL_SPEED = 12
CRUSHER_LAX = TILE_SIZE * 3 / 4
CRUSHER_GRAVITY = 1
CRUSHER_FALL_SPEED = 15
CRUSHER_RISE_SPEED = 2
CRUSHER_CRUSH_TIME = FPS * 2 / 3
CRUSHER_SHAKE_NUM = 2
THAW_FPS = 15
THAW_TIME_DEFAULT = FPS * 5
THAW_WARN_TIME = FPS
BRICK_SHARD_NUM = 6
BRICK_SHARD_SPEED = 3
BRICK_SHARD_HEIGHT = TILE_SIZE * 2
BRICK_SHARD_GRAVITY = 0.75
BRICK_SHARD_FALL_SPEED = 12
ROCK_GRAVITY = 0.6
ROCK_FALL_SPEED = 10
ROCK_FRICTION = 0.4
SPRING_JUMP_HEIGHT = 8 * TILE_SIZE + 11
FLOWER_FALL_SPEED = 5
FLOWER_THROW_HEIGHT = TILE_SIZE / 2
FLOWER_THROW_UP_HEIGHT = TILE_SIZE * 3 / 2
FIREBALL_AMMO = 20
FIREBALL_SPEED = 8
FIREBALL_GRAVITY = 0.5
FIREBALL_FALL_SPEED = 5
FIREBALL_BOUNCE_HEIGHT = TILE_SIZE / 2
FIREBALL_UP_HEIGHT = TILE_SIZE * 3 / 2
ICEBULLET_AMMO = 20
ICEBULLET_SPEED = 16
COINBRICK_COINS = 5 if HELL else 20
COINBRICK_DECAY_TIME = 25
ICE_CRACK_TIME = 20
ICE_REFREEZE_RATE = 1 / 4
LIGHT_RANGE = 600
ACTIVATE_RANGE = 528
ENEMY_ACTIVE_RANGE = 32
ICEBLOCK_ACTIVE_RANGE = 400
BULLET_ACTIVE_RANGE = 96
ROCK_ACTIVE_RANGE = 464
TILE_ACTIVE_RANGE = 528
DEATHZONE = 2 * TILE_SIZE
DEATH_FADE_TIME = 3000
DEATH_RESTART_WAIT = FPS
WIN_COUNT_START_TIME = 120
WIN_COUNT_CONTINUE_TIME = 45
WIN_COUNT_POINTS_MULT = 111
WIN_COUNT_TIME_MULT = 311
WIN_COUNT_POINTS_MAX = FPS
WIN_COUNT_TIME_MAX = 5 * FPS
WIN_FINISH_DELAY = 120
MAP_SPEED = 4
TEXT_SPEED = 1000
SAVE_NSLOTS = 10
MENU_MAX_ITEMS = 14
SOUND_MAX_RADIUS = 400
SOUND_ZERO_RADIUS = 1200
SOUND_CENTERED_RADIUS = 150
SOUND_TILTED_RADIUS = 1000
SOUND_TILT_LIMIT = 0.75
text_outline_thickness = 0
backgrounds = {}
loaded_music = {}
tux_grab_sprites = {}
fullscreen = False
scale_method = None
scale_proportional = True
sound_volume = 1
music_volume = 1
stereo_enabled = True
fps_enabled = False
joystick_threshold = 0.5
left_key = [["left", "a"]]
right_key = [["right", "d"]]
up_key = [["up", "w"]]
down_key = [["down", "s"]]
jump_key = [["space"]]
action_key = [["ctrl_left", "ctrl_right"]]
sneak_key = [["shift_left", "shift_right"]]
menu_key = [["tab", "backspace"]]
pause_key = [["enter", "p"]]
left_js = [[(0, "axis-", 0), (0, "hat_left", 0)]]
right_js = [[(0, "axis+", 0), (0, "hat_right", 0)]]
up_js = [[(0, "axis-", 1), (0, "hat_up", 0)]]
down_js = [[(0, "axis+", 1), (0, "hat_down", 0)]]
jump_js = [[(0, "button", 1), (0, "button", 3)]]
action_js = [[(0, "button", 0)]]
sneak_js = [[(0, "button", 2)]]
menu_js = [[(0, "button", 8)]]
pause_js = [[(0, "button", 9)]]
save_slots = [None for i in range(SAVE_NSLOTS)]
abort = False
current_save_slot = None
current_levelset = None
start_cutscene = None
worldmap = None
loaded_worldmaps = {}
levels = []
loaded_levels = {}
level_names = {}
level_timers = {}
cleared_levels = []
tuxdolls_available = []
tuxdolls_found = []
watched_timelines = []
level_time_bonus = 0
current_worldmap = None
worldmap_entry_space = None
current_worldmap_space = None
current_level = 0
current_checkpoints = {}
score = 0
current_areas = {}
main_area = None
level_cleared = False
mapdest = None
mapdest_space = None
class Game(sge.dsp.Game):
fps_time = 0
fps_frames = 0
fps_text = ""
def show_hell(self):
# Disabling this at least for now. It's just too inconsistent.
return
if HELL:
self.project_rectangle(0, 0, self.width, self.height, 20000,
fill=sge.gfx.Color((255, 128, 128)),
blend_mode=sge.BLEND_RGB_MULTIPLY)
def event_step(self, time_passed, delta_mult):
self.show_hell()
if fps_enabled:
self.fps_time += time_passed
self.fps_frames += 1
if self.fps_time >= 250:
self.fps_text = str(round(
(1000 * self.fps_frames) / self.fps_time, 2))
self.fps_time = 0
self.fps_frames = 0
self.project_text(font_small, self.fps_text, self.width - 8,
self.height - 8, z=1000,
color=sge.gfx.Color("yellow"), halign="right",
valign="bottom", outline=sge.gfx.Color("black"),
outline_thickness=text_outline_thickness)
def event_paused_step(self, time_passed, delta_mult):
self.show_hell()
def event_close(self):
rush_save()
self.end()
def event_paused_close(self):
self.event_close()
class Level(sge.dsp.Room):
"""Handles levels."""
@property
def name_width(self):
return sge.game.width * 2 / 5
def __init__(self, objects=(), *, background=None,
object_area_width=TILE_SIZE * 2,
object_area_height=TILE_SIZE * 2,
name=None, bgname=None, music=None,
time_bonus=DEFAULT_LEVEL_TIME_BONUS, spawn=None,
timeline=None, ambient_light=None, disable_lights=False,
persistent=True, **kwargs):
self.fname = None
self.name = name
self.music = music
self.time_bonus = time_bonus
self.spawn = spawn
self.persistent = persistent
self.points = 0
self.timeline_objects = {}
self.warps = []
self.shake_queue = 0
self.pause_delay = TRANSITION_TIME
self.game_won = False
self.status_text = None
if bgname is not None:
background = backgrounds.get(bgname, background)
self.load_timeline(timeline)
self.ambient_light = ambient_light
if (self.ambient_light and self.ambient_light.red >= 255
and self.ambient_light.green >= 255
and self.ambient_light.blue >= 255):
self.ambient_light = None
self.disable_lights = disable_lights or self.ambient_light is None
super().__init__(objects, background=background,
object_area_width=object_area_width,
object_area_height=object_area_height, **kwargs)
self.add(gui_handler)
def load_timeline(self, timeline):
self.timeline = {}
self.timeline_name = ""
self.timeline_step = 0
self.timeline_skip_target = None
if timeline:
self.timeline_name = timeline
fname = os.path.join(DATA, "timelines", timeline)
with open(fname, 'r') as f:
jt = json.load(f)
for i in jt:
self.timeline[eval(i)] = jt[i]
def add_timeline_object(self, obj):
if obj.ID is not None:
self.timeline_objects[obj.ID] = weakref.ref(obj)
def timeline_skipto(self, step):
t_keys = sorted(self.timeline.keys())
self.timeline_step = step
while t_keys and t_keys[0] < step:
i = t_keys.pop(0)
self.timeline[i] = []
def add_points(self, x):
if main_area not in cleared_levels:
self.points += x
def show_hud(self):
# Show darkness
if self.ambient_light:
xsge_lighting.project_darkness(ambient_light=self.ambient_light,
buffer=TILE_SIZE * 2)
else:
xsge_lighting.clear_lights()
if not NO_HUD:
if self.points:
score_text = f"{self.points}+{score}"
else:
score_text = str(score)
time_bonus = level_timers.get(main_area, 0)
text = "{}\n{}\n\n{}\n{}".format(
_("Score"), score_text,
_("Time Bonus") if time_bonus >= 0 else _("Time Penalty"),
abs(time_bonus))
sge.game.project_text(font, text, sge.game.width, 0,
color=sge.gfx.Color("white"), halign="right",
outline=sge.gfx.Color("black"),
outline_thickness=text_outline_thickness)
y = 0
if self.name:
sge.game.project_text(
font, pgettext("level_name", self.name),
sge.game.width / 2, y, width=self.name_width,
color=sge.gfx.Color("white"), halign="center",
outline=sge.gfx.Color("black"),
outline_thickness=text_outline_thickness)
y += font.get_height(
pgettext("level_name", self.name),
sge.game.width * 2 / 5,
outline_thickness=text_outline_thickness)
if main_area in tuxdolls_available or main_area in tuxdolls_found:
if main_area in tuxdolls_found:
s = tuxdoll_sprite
else:
s = tuxdoll_transparent_sprite
sge.game.project_sprite(s, 0, sge.game.width / 2,
s.height/2 + 8 + y)
if self.status_text:
sge.game.project_text(font, self.status_text,
sge.game.width / 2, sge.game.height - 16,
color=sge.gfx.Color("white"),
halign="center", valign="middle",
outline=sge.gfx.Color("black"),
outline_thickness=text_outline_thickness)
self.status_text = None
def shake(self, num=1):
shaking = (self.shake_queue or "shake_up" in self.alarms or
"shake_down" in self.alarms)
self.shake_queue = max(self.shake_queue, num)
if not shaking:
self.event_alarm("shake_down")
for obj in self.objects:
if isinstance(obj, SteadyIcicle):
obj.check_shake(True)
def pause(self):
global level_timers
global score
if self.death_time is not None or "death" in self.alarms:
if level_timers.setdefault(main_area, 0) >= 0:
sge.snd.Music.stop()
self.alarms["death"] = 0
elif (self.timeline_skip_target is not None and
self.timeline_step < self.timeline_skip_target):
self.timeline_skipto(self.timeline_skip_target)
elif self.pause_delay <= 0 and not self.won:
sge.snd.Music.pause()
play_sound(pause_sound)
PauseMenu.create()
def die(self):
global current_areas
current_areas = {}
self.death_time = DEATH_FADE_TIME
self.death_time_bonus = level_timers.setdefault(main_area, 0)
if "timer" in self.alarms:
del self.alarms["timer"]
fade_time = DEATH_FADE_TIME
for m in loaded_music.values():
if m.playing:
name, ext = os.path.splitext(m.fname)
if name.endswith("-start"):
fade_time = min(fade_time, round(m.length - m.position))
break
sge.snd.Music.clear_queue()
sge.snd.Music.stop(fade_time)
def return_to_map(self, completed=False):
global current_worldmap
global current_worldmap_space
global mapdest
global mapdest_space
if completed:
if mapdest:
current_worldmap = mapdest
if mapdest_space:
current_worldmap_space = mapdest_space
worldmap_entry_space = mapdest_space
mapdest = None
mapdest_space = None
save_game()
if current_worldmap:
m = Worldmap.load(current_worldmap)
m.start(transition="iris_out", transition_time=TRANSITION_TIME)
else:
sge.game.start_room.start()
def win_level(self, victory_walk=True):
global current_checkpoints
if self.death_time is None and "death" not in self.alarms:
for obj in self.objects[:]:
if isinstance(obj, WinPuffObject) and obj.active:
obj.win_puff()
for obj in self.objects:
if isinstance(obj, Player):
obj.human = False
obj.left_pressed = False
obj.right_pressed = False
obj.up_pressed = False
obj.down_pressed = False
obj.jump_pressed = False
obj.action_pressed = False
obj.sneak_pressed = True
obj.jump_release()
if victory_walk:
if obj.xvelocity >= 0:
obj.right_pressed = True
else:
obj.left_pressed = True
if "timer" in self.alarms:
del self.alarms["timer"]
self.won = True
self.alarms["win_count_points"] = WIN_COUNT_START_TIME
current_checkpoints[main_area] = None
sge.snd.Music.clear_queue()
sge.snd.Music.stop()
if music_volume:
level_win_music.volume = music_volume
level_win_music.play()
def win_game(self):
global current_level
current_level = 0
save_game()
credits_room = CreditsScreen.load(os.path.join("special",
"credits.json"))
credits_room.start()
def event_room_start(self):
self.add(coin_animation)
self.add(bonus_animation)
self.add(lava_animation)
self.add(goal_animation)
self.event_room_resume()
def event_room_resume(self):
global main_area
global level_time_bonus
xsge_lighting.clear_lights()
self.won = False
self.win_count_points = False
self.win_count_time = False
self.count_mult = 1
self.count_time = 0
self.death_time = None
self.alarms["timer"] = TIMER_FRAMES
self.pause_delay = TRANSITION_TIME
play_music(self.music)
if main_area is None:
main_area = self.fname
if main_area == self.fname:
level_time_bonus = self.time_bonus
if GOD:
level_timers[main_area] = min(0, level_timers.get(main_area, 0))
elif main_area not in level_timers:
if main_area in levels:
level_timers[main_area] = level_time_bonus
else:
level_timers[main_area] = 0
players = []
spawn_point = None
for obj in self.objects:
if isinstance(obj, (Spawn, Door, WarpSpawn)):
if self.spawn is not None and obj.spawn_id == self.spawn:
spawn_point = obj
if isinstance(obj, Warp) and obj not in self.warps:
self.warps.append(obj)
elif isinstance(obj, Player):
players.append(obj)
del_warps = []
for warp in self.warps:
if warp not in self.objects:
del_warps.append(warp)
for warp in del_warps:
self.warps.remove(warp)
if spawn_point is not None:
for player in players:
player.x = spawn_point.x
player.y = spawn_point.y
if player.view is not None:
player.view.x = player.x - player.view.width / 2
player.view.y = (player.y - player.view.height +
CAMERA_TARGET_MARGIN_BOTTOM)
if isinstance(spawn_point, WarpSpawn):
player.visible = False
player.tangible = False
player.warping = True
spawn_point.follow_start(player, WARP_SPEED)
else:
player.visible = True
player.tangible = True
player.warping = False
def event_step(self, time_passed, delta_mult):
global watched_timelines
global level_timers
global current_level
global score
global current_areas
global main_area
global level_cleared
if self.pause_delay > 0:
self.pause_delay -= time_passed
# Handle inactive objects and lighting
if self.ambient_light:
range_ = max(ACTIVATE_RANGE, LIGHT_RANGE)
else:
range_ = ACTIVATE_RANGE
for view in self.views:
for obj in self.get_objects_at(
view.x - range_, view.y - range_, view.width + range_ * 2,
view.height + range_ * 2):
if isinstance(obj, (Player, InteractiveObject)):
if not self.disable_lights:
obj.project_light()
if not obj.active:
if isinstance(obj, InteractiveObject):
obj.update_active()
elif isinstance(obj, (Lava, LavaSurface)):
obj.image_index = lava_animation.image_index
elif isinstance(obj, (Goal, GoalTop)):
obj.image_index = goal_animation.image_index
# Show HUD
self.show_hud()
# Timeline events
t_keys = sorted(self.timeline.keys())
while t_keys:
i = t_keys.pop(0)
if i <= self.timeline_step:
while i in self.timeline and self.timeline[i]:
command = self.timeline[i].pop(0)
command = command.split(None, 1)
if command:
if len(command) >= 2:
command, arg = command[:2]
else:
command = command[0]
arg = ""
if command.startswith("#"):
# Comment; do nothing
pass
elif command == "setattr":
args = arg.split(None, 2)
if len(args) >= 3:
obj, name, value = args[:3]
try:
value = eval(value)
except Exception as e:
m = _("An error occurred in a timeline "
"'setattr' command:\n\n{}").format(
traceback.format_exc())
show_error(m)
else:
if obj in self.timeline_objects:
obj = self.timeline_objects[obj]()
if obj is not None:
setattr(obj, name, value)
elif obj == "__level__":
setattr(self, name, value)
elif command == "call":
args = arg.split()
if len(args) >= 2:
obj, method = args[:2]
fa = [eval(s) for s in args[2:]]
if obj in self.timeline_objects:
obj = self.timeline_objects[obj]()
if obj is not None:
getattr(obj, method, lambda: None)(*fa)
elif obj == "__level__":
getattr(self, method, lambda: None)(*fa)
elif command == "dialog":
args = arg.split(None, 1)
if len(args) >= 2:
portrait, text = args[:2]
sprite = portrait_sprites.get(portrait)
DialogBox(gui_handler, _(text), sprite).show()
elif command == "play_music":
self.music = arg
play_music(arg)
elif command == "timeline":
if self.timeline_name not in watched_timelines:
watched_timelines.append(self.timeline_name)
self.load_timeline(arg)
break
elif command == "skip_to":
try:
arg = float(arg)
except ValueError:
pass
else:
self.timeline_skipto(arg)
break
elif command == "exec":
try:
exec(arg)
except Exception as e:
m = _("An error occurred in a timeline 'exec' "
"command:\n\n{}").format(
traceback.format_exc())
show_error(m)
elif command == "if":
try:
r = eval(arg)
except Exception as e:
m = _("An error occurred in a timeline 'if' "
"statement:\n\n{}").format(
traceback.format_exc())
show_error(m)
r = False
finally:
if not r:
self.timeline[i] = []
break
elif command == "if_watched":
if self.timeline_name not in watched_timelines:
self.timeline[i] = []
break
elif command == "if_not_watched":
if self.timeline_name in watched_timelines:
self.timeline[i] = []
break
elif command == "while":
try:
r = eval(arg)
except Exception as e:
m = _("An error occurred in a timeline "
"'while' statement:\n\n{}").format(
traceback.format_exc())
show_error(m)
r = False
finally:
if r:
cur_timeline = self.timeline[i][:]
while_command = "while {}".format(arg)
self.timeline[i].insert(0, while_command)
t_keys.insert(0, i)
self.timeline[i - 1] = cur_timeline
self.timeline[i] = loop_timeline
i -= 1
self.timeline_step -= 1
else:
self.timeline[i] = []
break
else:
del self.timeline[i]
else:
break
else:
if (self.timeline_name and
self.timeline_name not in watched_timelines):
watched_timelines.append(self.timeline_name)
self.timeline_name = ""
self.timeline_step += delta_mult
if self.death_time is not None:
a = int(255 * (DEATH_FADE_TIME - self.death_time) / DEATH_FADE_TIME)
sge.game.project_rectangle(
0, 0, sge.game.width, sge.game.height, z=100,
fill=sge.gfx.Color((0, 0, 0, min(a, 255))))
time_bonus = level_timers.setdefault(main_area, 0)
if time_bonus < 0 and cleared_levels:
if HELL:
self.count_time += time_passed
if self.count_time >= 1000 / FPS:
amt = int(math.copysign(
min(math.ceil(abs(self.death_time_bonus) * 3
* self.count_time / DEATH_FADE_TIME),
abs(time_bonus)),
time_bonus))
self.count_time = 0
if amt:
score += amt
level_timers[main_area] -= amt
play_sound(coin_sound)
else:
level_timers[main_area] = 0
if self.death_time < 0:
self.death_time = None
self.alarms["death"] = DEATH_RESTART_WAIT
else:
self.death_time -= time_passed
elif "death" in self.alarms:
sge.game.project_rectangle(0, 0, sge.game.width, sge.game.height,
z=100, fill=sge.gfx.Color("black"))
if self.won:
if self.win_count_points:
if self.points:
self.count_time += delta_mult
if self.count_time >= 1: