/
hexoshi.py
executable file
·7118 lines (5993 loc) · 261 KB
/
hexoshi.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
# Hexoshi
#
# 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__ = "0.3a0"
import argparse
import datetime
import gettext
import itertools
import json
import math
import os
import random
import sys
import time
import traceback
import warnings
import weakref
import sge
import xsge_gui
import xsge_lighting
import xsge_particle
import xsge_path
import xsge_physics
import xsge_tiled
import hlib
if getattr(sys, "frozen", False):
__file__ = sys.executable
hlib.datadir = os.path.join(os.path.dirname(__file__), "data")
gettext.install("hexoshi", os.path.abspath(os.path.join(hlib.datadir, "locale")))
parser = argparse.ArgumentParser()
parser.add_argument(
"--version", action="version", version=f"Hexoshi {__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(hlib.datadir))
parser.add_argument(
"--scale",
help=_('The scale factor to use by default in windowed mode (Default: '
'"{}")').format(hlib.scale))
parser.add_argument(
"--fsscale",
help=_("Specify a scale factor to use in fullscreen mode instead of using "
"dynamic scaling. This will cause the screen resolution to change, "
"which may improve performance. For best results, specify this as "
"the target resolution width divided by {w}, or as the target "
"resolution height divided by {h} (whichever is smaller). For "
"example, to target a resolution of 640x480, use {ex}. A scale "
"factor of 1 will always be fastest, but may result in "
"windowboxing.").format(
w=hlib.SCREEN_SIZE[0], h=hlib.SCREEN_SIZE[1],
ex=min(640 / hlib.SCREEN_SIZE[0], 480 / hlib.SCREEN_SIZE[1])))
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(
"-m", "--gen-map", help=_("Generate the map even if it already exists."),
action="store_true")
parser.add_argument(
"-s", "--save-map", help=_('Save an image of the full map as "map.png".'),
action="store_true")
parser.add_argument(
"--dist-ai", help=_("Write the AI data to the game data directory instead "
"of the user data directory (for distribution)."),
action="store_true")
parser.add_argument(
"-q", "--quit",
help=_("Quit immediately on startup (useful with -m or -s)."),
action="store_true")
parser.add_argument("--god")
args = parser.parse_args()
PRINT_ERRORS = args.print_errors
DELTA = not args.nodelta
if args.datadir:
hlib.datadir = args.datadir
if args.scale:
hlib.scale = eval(args.scale)
if args.fsscale:
hlib.fsscale = eval(args.fsscale)
NO_BACKGROUNDS = args.no_backgrounds
hlib.no_hud = args.no_hud
GEN_MAP = args.gen_map
SAVE_MAP = args.save_map
DIST_AI = args.dist_ai
QUIT = args.quit
hlib.god = (args.god and args.god.lower() == "inbailey")
if args.lang:
lang = gettext.translation("hexoshi",
os.path.abspath(os.path.join(hlib.datadir, "locale")),
[args.lang])
lang.install()
with open(os.path.join(hlib.datadir, "ai_data.json"), 'r') as f:
ai_data = json.load(f)
class Game(sge.dsp.Game):
fps_real = hlib.FPS
fps_time = 0
fps_frames = 0
fps_text = ""
cheatcode = ""
def event_step(self, time_passed, delta_mult):
self.fps_time += time_passed
self.fps_frames += 1
if self.fps_time >= 250:
self.fps_real = (1000 * self.fps_frames) / self.fps_time
self.fps_text = '{:.2f}'.format(self.fps_real)
self.fps_time = 0
self.fps_frames = 0
if hlib.fps_enabled:
self.project_text(hlib.font_small, self.fps_text, self.width - 8,
self.height - 8, z=1000000,
color=sge.gfx.Color("yellow"), halign="right",
valign="bottom", outline=sge.gfx.Color("black"),
outline_thickness=1)
def event_key_press(self, key, char):
if key == "f7":
self.cheatcode = ""
elif sge.keyboard.get_pressed("f7"):
if not self.cheatcode:
print(_("Code entry:"), end=' ')
self.cheatcode += char
print(char, end='')
sys.stdout.flush()
def event_key_release(self, key):
if key == "f7":
if self.cheatcode:
print()
if self.cheatcode.lower() == "knowitall":
hlib.map_revealed = set(hlib.map_objects.keys())
elif self.cheatcode.lower() == "seenitall":
hlib.map_explored = hlib.map_revealed
elif self.cheatcode.startswith("tele"):
warp(self.cheatcode[4:] + ".json")
else:
print(_("Invalid cheat code: {}").format(self.cheatcode))
def event_close(self):
self.end()
def event_paused_close(self):
self.event_close()
class Level(sge.dsp.Room):
"""Handles levels."""
def __init__(self, objects=(), *, background=None,
object_area_width=hlib.TILE_SIZE * 2,
object_area_height = hlib.TILE_SIZE * 2,
name=None, bgname=None, music=None, timeline=None,
ambient_light=None, disable_lights=False, music_noloop=False,
**kwargs):
self.fname = None
self.name = name
self.music = music
self.music_noloop = music_noloop
self.timeline_objects = {}
self.shake_queue = 0
self.death_time = None
self.status_text = None
self.player_z = 0
if bgname is not None:
background = hlib.backgrounds.get(bgname, background)
self.load_timeline(timeline)
if ambient_light:
self.ambient_light = ambient_light
if (self.ambient_light.red >= 255 and
self.ambient_light.green >= 255 and
self.ambient_light.blue >= 255):
self.ambient_light = None
else:
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(hlib.datadir, "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 show_hud(self):
# Show darkness
if self.ambient_light:
xsge_lighting.project_darkness(ambient_light=self.ambient_light,
buffer=hlib.TILE_SIZE * 2)
else:
xsge_lighting.clear_lights()
if not hlib.no_hud:
if self.status_text:
sge.game.project_text(hlib.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=1)
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, player_x=None, player_y=None):
if (self.timeline_skip_target is not None and
self.timeline_step < self.timeline_skip_target):
self.timeline_skipto(self.timeline_skip_target)
else:
play_sound(hlib.pause_sound)
PauseMenu.create(player_x=player_x, player_y=player_y)
def die(self):
sge.game.start_room.start(transition="fade")
def win_game(self):
credits_room = CreditsScreen.load(os.path.join("special",
"credits.json"))
credits_room.start()
def event_room_start(self):
if hlib.player is not None:
self.add(hlib.player)
xsge_lighting.clear_lights()
play_music(self.music, noloop=self.music_noloop)
def event_room_resume(self):
play_music(self.music, noloop=self.music_noloop)
def event_step(self, time_passed, delta_mult):
hlib.time_taken += time_passed / 1000
for view in self.views:
for obj in self.get_objects_at(
view.x - hlib.LIGHT_RANGE, view.y - hlib.LIGHT_RANGE,
view.width + hlib.LIGHT_RANGE * 2,
view.height + hlib.LIGHT_RANGE * 2):
if isinstance(obj, InteractiveObject):
if not self.disable_lights:
obj.project_light()
# 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":
DialogBox(gui_handler, _(arg)).show()
elif command == "play_music":
self.music = arg
play_music(arg)
elif command == "timeline":
if self.timeline_name not in hlib.watched_timelines:
hlib.watched_timelines = hlib.watched_timelines[:]
hlib.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 hlib.watched_timelines:
self.timeline[i] = []
break
elif command == "if_not_watched":
if self.timeline_name in hlib.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 hlib.watched_timelines):
hlib.watched_timelines = hlib.watched_timelines[:]
hlib.watched_timelines.append(self.timeline_name)
self.timeline_name = ""
self.timeline_step += delta_mult
def event_paused_step(self, time_passed, delta_mult):
# Handle lighting
for view in self.views:
for obj in self.get_objects_at(
view.x - hlib.LIGHT_RANGE, view.y - hlib.LIGHT_RANGE,
view.width + hlib.LIGHT_RANGE*2,
view.height + hlib.LIGHT_RANGE*2):
if isinstance(obj, InteractiveObject):
if not self.disable_lights:
obj.project_light()
self.show_hud()
def event_alarm(self, alarm_id):
if alarm_id == "shake_down":
self.shake_queue -= 1
for view in self.views:
view.yport += hlib.SHAKE_AMOUNT
self.alarms["shake_up"] = hlib.SHAKE_FRAME_TIME
elif alarm_id == "shake_up":
for view in self.views:
view.yport -= hlib.SHAKE_AMOUNT
if self.shake_queue:
self.alarms["shake_down"] = hlib.SHAKE_FRAME_TIME
elif alarm_id == "death":
self.die()
@classmethod
def load(cls, fname, show_prompt=False):
if show_prompt:
text = _("Loading data...")
if sge.game.current_room is not None:
x = sge.game.width / 2
y = sge.game.height / 2
w = hlib.font.get_width(text, outline_thickness=1) + 32
h = hlib.font.get_height(text, outline_thickness=1) + 32
sge.game.project_rectangle(x - w/2, y - h/2, w, h,
fill=sge.gfx.Color("black"))
sge.game.project_text(hlib.font, text, x, y,
color=sge.gfx.Color("white"),
halign="center", valign="middle",
outline=sge.gfx.Color("black"),
outline_thickness=1)
hlib.game.refresh_screen(0, 0)
else:
print(_("Loading \"{}\"…").format(fname))
try:
r = xsge_tiled.load(os.path.join(hlib.datadir, "rooms", fname), cls=cls,
types=TYPES)
except Exception as e:
m = _("An error occurred when trying to load the level:\n\n"
"{}").format(traceback.format_exc())
show_error(m)
r = None
else:
r.fname = fname
return r
class SpecialScreen(Level):
def event_room_start(self):
super().event_room_start()
if hlib.player is not None:
hlib.player.destroy()
class TitleScreen(SpecialScreen):
def event_room_start(self):
super().event_room_start()
MainMenu.create()
def event_room_resume(self):
super().event_room_resume()
MainMenu.create()
def event_step(self, time_passed, delta_mult):
super().event_step(time_passed, delta_mult)
sge.game.project_sprite(hlib.logo_sprite, 0, self.width / 2, 16)
def event_key_press(self, key, char):
pass
class CreditsScreen(SpecialScreen):
def event_room_start(self):
super().event_room_start()
with open(os.path.join(hlib.datadir, "credits.json"), 'r') as f:
sections = json.load(f)
logo_section = sge.dsp.Object.create(self.width / 2, self.height,
sprite=hlib.logo_sprite,
tangible=False)
self.sections = [logo_section]
for section in sections:
if "title" in section:
head_sprite = sge.gfx.Sprite.from_text(
hlib.font_big, section["title"], width=self.width,
color=sge.gfx.Color("white"), halign="center",
outline=sge.gfx.Color("black"), outline_thickness=1)
x = self.width / 2
y = self.sections[-1].bbox_bottom + hlib.font_big.size*3
head_section = sge.dsp.Object.create(x, y, sprite=head_sprite,
tangible=False)
self.sections.append(head_section)
if "lines" in section:
for line in section["lines"]:
list_sprite = sge.gfx.Sprite.from_text(
hlib.font, line, width=self.width - 2*hlib.TILE_SIZE,
color=sge.gfx.Color("white"), halign="center",
outline=sge.gfx.Color("black"), outline_thickness=1)
x = self.width / 2
y = self.sections[-1].bbox_bottom + hlib.font.size
list_section = sge.dsp.Object.create(
x, y, sprite=list_sprite, tangible=False)
self.sections.append(list_section)
for obj in self.sections:
obj.yvelocity = -0.2
def event_step(self, time_passed, delta_mult):
if self.sections[0].yvelocity > 0 and self.sections[0].y > self.height:
for obj in self.sections:
obj.yvelocity = 0
if self.sections[-1].bbox_bottom < 0 and "end" not in self.alarms:
sge.snd.Music.stop(fade_time=3000)
self.alarms["end"] = 3.5 * hlib.FPS
def event_alarm(self, alarm_id):
if alarm_id == "end":
sge.game.start_room.start()
def event_key_press(self, key, char):
if key in hlib.down_key:
if "end" not in self.alarms:
for obj in self.sections:
obj.yvelocity -= 0.1
elif key in hlib.up_key:
if "end" not in self.alarms:
for obj in self.sections:
obj.yvelocity += 0.1
elif (key in hlib.jump_key or key in hlib.shoot_key
or key in hlib.secondary_key or key in hlib.pause_key):
sge.game.start_room.start()
def event_joystick(self, js_name, js_id, input_type, input_id, value):
js = (js_id, input_type, input_id)
if value >= hlib.joystick_threshold:
if js in hlib.down_js:
if "end" not in self.alarms:
for obj in self.sections:
obj.yvelocity -= 0.1
elif js in hlib.up_js:
if "end" not in self.alarms:
for obj in self.sections:
obj.yvelocity += 0.1
elif (js in hlib.jump_js or js in hlib.shoot_js
or js in hlib.secondary_js or js in hlib.pause_js):
sge.game.start_room.start()
class SolidLeft(xsge_physics.SolidLeft):
def __init__(self, *args, **kwargs):
kwargs.setdefault("visible", False)
kwargs.setdefault("checks_collisions", False)
super().__init__(*args, **kwargs)
class SolidRight(xsge_physics.SolidRight):
def __init__(self, *args, **kwargs):
kwargs.setdefault("visible", False)
kwargs.setdefault("checks_collisions", False)
super().__init__(*args, **kwargs)
class SolidTop(xsge_physics.SolidTop):
def __init__(self, *args, **kwargs):
kwargs.setdefault("visible", False)
kwargs.setdefault("checks_collisions", False)
super().__init__(*args, **kwargs)
class SolidBottom(xsge_physics.SolidBottom):
def __init__(self, *args, **kwargs):
kwargs.setdefault("visible", False)
kwargs.setdefault("checks_collisions", False)
super().__init__(*args, **kwargs)
class Solid(xsge_physics.Solid):
def __init__(self, *args, **kwargs):
kwargs.setdefault("visible", False)
kwargs.setdefault("checks_collisions", False)
super().__init__(*args, **kwargs)
class SlopeTopLeft(xsge_physics.SlopeTopLeft):
xsticky_top = True
def __init__(self, *args, **kwargs):
kwargs.setdefault("visible", False)
kwargs.setdefault("checks_collisions", False)
super().__init__(*args, **kwargs)
def event_create(self):
self.slope_xacceleration = -self.bbox_height / self.bbox_width
class SlopeTopRight(xsge_physics.SlopeTopRight):
xsticky_top = True
def __init__(self, *args, **kwargs):
kwargs.setdefault("visible", False)
kwargs.setdefault("checks_collisions", False)
super().__init__(*args, **kwargs)
def event_create(self):
self.slope_xacceleration = self.bbox_height / self.bbox_width
class SlopeBottomLeft(xsge_physics.SlopeBottomLeft):
def __init__(self, *args, **kwargs):
kwargs.setdefault("visible", False)
kwargs.setdefault("checks_collisions", False)
super().__init__(*args, **kwargs)
class SlopeBottomRight(xsge_physics.SlopeBottomRight):
def __init__(self, *args, **kwargs):
kwargs.setdefault("visible", False)
kwargs.setdefault("checks_collisions", False)
super().__init__(*args, **kwargs)
class MovingPlatform(xsge_physics.SolidTop, xsge_physics.MobileWall):
sticky_top = True
def __init__(self, x, y, z=0, **kwargs):
kwargs.setdefault("sprite", platform_sprite)
super().__init__(x, y, z, **kwargs)
self.path = None
self.following = False
def event_step(self, time_passed, delta_mult):
super().event_step(time_passed, delta_mult)
if self.path and not self.following:
for other in self.collision(Player, y=self.y - 1):
if self in other.get_bottom_touching_wall():
self.path.follow_start(self, self.path.path_speed,
accel=self.path.path_accel,
decel=self.path.path_decel,
loop=self.path.path_loop)
break
class HurtLeft(SolidLeft):
pass
class HurtRight(SolidRight):
pass
class HurtTop(SolidTop):
pass
class HurtBottom(SolidBottom):
pass
class SpikeLeft(HurtLeft, xsge_physics.Solid):
pass
class SpikeRight(HurtRight, xsge_physics.Solid):
pass
class SpikeTop(HurtTop, xsge_physics.Solid):
pass
class SpikeBottom(HurtBottom, xsge_physics.Solid):
pass
class Death(sge.dsp.Object):
def __init__(self, *args, **kwargs):
kwargs.setdefault("visible", False)
kwargs.setdefault("checks_collisions", False)
super().__init__(*args, **kwargs)
class Player(xsge_physics.Collider):
name = "Ian C."
max_hp = hlib.PLAYER_MAX_HP
max_speed = hlib.PLAYER_MAX_SPEED
roll_max_speed = hlib.PLAYER_ROLL_MAX_SPEED
acceleration = hlib.PLAYER_ACCELERATION
roll_acceleration = hlib.PLAYER_ROLL_ACCELERATION
air_acceleration = hlib.PLAYER_AIR_ACCELERATION
friction = hlib.PLAYER_FRICTION
roll_friction = hlib.PLAYER_ROLL_FRICTION
air_friction = hlib.PLAYER_AIR_FRICTION
jump_height = hlib.PLAYER_JUMP_HEIGHT
gravity = hlib.GRAVITY
fall_speed = hlib.PLAYER_FALL_SPEED
slide_speed = hlib.PLAYER_SLIDE_SPEED
roll_slide_speed = hlib.PLAYER_ROLL_SLIDE_SPEED
roll_slope_acceleration = hlib.PLAYER_ROLL_SLOPE_ACCELERATION
hitstun_time = hlib.PLAYER_HITSTUN
can_move = True
@property
def slope_acceleration(self):
if self.rolling:
return self.roll_slope_acceleration
else:
return 0
@slope_acceleration.setter
def slope_acceleration(self, value):
pass
@property
def hp(self):
return self.__hp
@hp.setter
def hp(self, value):
self.__hp = value
while self.__hp > self.max_hp and self.etanks_used > 0:
self.etanks_used -= 1
self.__hp -= self.max_hp
while self.__hp <= 0 and self.etanks_used < hlib.etanks:
self.etanks_used += 1
self.__hp += self.max_hp
self.__hp = min(self.__hp, self.max_hp)
self.update_hud()
@property
def camera_target_x(self):
guides = sge.collision.rectangle(self.x, self.y, 1, 1, CameraXGuide)
if guides:
return guides[0].x
else:
return (self.x - self.view.width/2
+ self.xvelocity*hlib.CAMERA_OFFSET_FACTOR)
@property
def camera_target_y(self):
guides = sge.collision.rectangle(self.x, self.y, 1, 1, CameraYGuide)
if guides:
self.camera_guided_y = True
return guides[0].y
else:
self.camera_guided_y = False
return self.y-self.view.height + hlib.CAMERA_TARGET_MARGIN_BOTTOM
@property
def aim_lock(self):
return "aim_lock" in self.alarms
@aim_lock.setter
def aim_lock(self, value):
if value:
self.alarms["aim_lock"] = hlib.PLAYER_AIM_LOCK_TIME
elif "aim_lock" in self.alarms:
del self.alarms["aim_lock"]
def __init__(self, x, y, z=0, sprite=None, visible=True, active=True,
checks_collisions=True, tangible=True, bbox_x=8, bbox_y=0,
bbox_width=16, bbox_height=16, regulate_origin=True,
collision_ellipse=False, collision_precise=False, xvelocity=0,
yvelocity=0, xacceleration=0, yacceleration=0,
xdeceleration=0, ydeceleration=0, image_index=0,
image_origin_x=None, image_origin_y=None, image_fps=None,
image_xscale=1, image_yscale=1, image_rotation=0,
image_alpha=255, image_blend=None, ID="player", player=0,
human=True, lose_on_death=True, view_frozen=False):
self.ID = ID
self.player = player
self.human = human
self.lose_on_death = lose_on_death
self.view_frozen = view_frozen
self.input_lock = False
self.warp_dest = None
self.hud_sprite = sge.gfx.Sprite(width=hlib.SCREEN_SIZE[0],
height=hlib.SCREEN_SIZE[1])
self.reset_input()
self.etanks_used = 0
self.hitstun = False
self.invincible = False
self.facing = 1
self.has_jumped = False
self.rolling = False
self.aim_direction = None
self.aim_direction_time = 0
self.view = None
self.__hp = self.max_hp
self.last_xr = None
self.last_yr = None
self.camera_guided_y = False
super().__init__(
x, y, z=z, sprite=sprite, visible=visible, active=active,
checks_collisions=checks_collisions, tangible=tangible,
bbox_x=bbox_x, bbox_y=bbox_y, bbox_width=bbox_width,
bbox_height=bbox_height, regulate_origin=regulate_origin,
collision_ellipse=collision_ellipse,
collision_precise=collision_precise, xvelocity=xvelocity,
yvelocity=yvelocity, xacceleration=xacceleration,
yacceleration=yacceleration, xdeceleration=xdeceleration,
ydeceleration=ydeceleration, image_index=image_index,
image_origin_x=image_origin_x, image_origin_y=image_origin_y,
image_fps=image_fps, image_xscale=image_xscale,
image_yscale=image_yscale, image_rotation=image_rotation,
image_alpha=image_alpha, image_blend=image_blend)
def reset_input(self):
self.left_pressed = False
self.right_pressed = False
self.up_pressed = False
self.down_pressed = False
self.jump_pressed = False
self.shoot_pressed = False
self.secondary_pressed = False
self.aim_diag_pressed = False
self.aim_up_pressed = False
self.aim_down_pressed = False
def refresh_input(self):
if self.input_lock or not self.human:
return
key_controls = [hlib.left_key, hlib.right_key, hlib.up_key,
hlib.down_key, hlib.aim_diag_key, hlib.jump_key,
hlib.shoot_key, hlib.secondary_key, hlib.aim_up_key,
hlib.aim_down_key]
js_controls = [hlib.left_js, hlib.right_js, hlib.up_js, hlib.down_js,
hlib.aim_diag_js, hlib.jump_js, hlib.shoot_js,
hlib.secondary_js, hlib.aim_up_js, hlib.aim_down_js]
states = [0 for i in key_controls]
for i, control in enumerate(key_controls):
for choice in control:
value = sge.keyboard.get_pressed(choice)
states[i] = max(states[i], value)
for i, control in enumerate(js_controls):
for choice in control:
j, t, c = choice
value = min(sge.joystick.get_value(j, t, c), 1)
if value >= hlib.joystick_threshold:
states[i] = max(states[i], value)
(self.left_pressed, self.right_pressed, self.up_pressed,
self.down_pressed, self.aim_diag_pressed, self.jump_pressed,
self.shoot_pressed, self.secondary_pressed, self.aim_up_pressed,
self.aim_down_pressed) = states
def press_up(self):
if not self.aim_diag_pressed:
warp_pad_objs = self.collision(WarpPad)
if warp_pad_objs:
warp_pad = warp_pad_objs[0]
warp_pad.teleport(self)
def press_down(self):
pass
def jump(self):
if self.on_floor or self.was_on_floor:
self.has_jumped = True
self.yvelocity = get_jump_speed(self.jump_height, self.gravity)
self.on_floor = []
self.was_on_floor = []
self.event_jump()
def jump_release(self):
if self.has_jumped and self.yvelocity < 0:
self.has_jumped = False
self.yvelocity /= 2
def shoot(self):
pass
def shoot_release(self):
pass
def secondary(self):
pass
def secondary_release(self):
pass
def hurt(self, damage=1, touching=False):
if not self.hitstun and not self.invincible:
play_sound(hlib.hurt_sound, self.x, self.y)
if not hlib.god:
self.hp -= damage
if self.hp <= 0:
self.kill()