-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_game.py
1282 lines (800 loc) · 44.9 KB
/
run_game.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
# -*- coding: utf-8 -*-
import math
from typing import Optional
import arcade
import time
SCREEN_TITLE = "Arcadia"
# How big are our image tiles?
SPRITE_IMAGE_SIZE = 128
# Scale sprites up or down
SPRITE_SCALING_PLAYER = 0.5
SPRITE_SCALING_TILES = 0.5
# Scaled sprite size for tiles
SPRITE_SIZE = int(SPRITE_IMAGE_SIZE * SPRITE_SCALING_PLAYER)
# Size of grid to show on screen, in number of tiles
SCREEN_GRID_WIDTH = 25
SCREEN_GRID_HEIGHT = 15
# Size of screen to show, in pixels
SCREEN_WIDTH = SPRITE_SIZE * SCREEN_GRID_WIDTH
SCREEN_HEIGHT = SPRITE_SIZE * SCREEN_GRID_HEIGHT
HALF_SCREEN_WIDTH = SCREEN_WIDTH // 2
HALF_SCREEN_HEIGHT = SCREEN_HEIGHT // 2
# --- Physics forces. Higher number, faster accelerating.
# Gravity
GRAVITY = 1500
# Damping - Amount of speed lost per second
DEFAULT_DAMPING = 1.0
PLAYER_DAMPING = 0.4
#PLAYER_DAMPING = 0.9
# Friction between objects
PLAYER_FRICTION = 1.0
WALL_FRICTION = 0.7
DYNAMIC_ITEM_FRICTION = 0.6
ICE_FRICTION = 0.0
# Mass (defaults to 1)
PLAYER_MASS = 2.0
# Keep player from going too fast
PLAYER_MAX_HORIZONTAL_SPEED = 450
PLAYER_MAX_VERTICAL_SPEED = 1600
# Force applied while on the ground
PLAYER_MOVE_FORCE_ON_GROUND = 8000
# Force applied when moving left/right in the air
PLAYER_MOVE_FORCE_IN_AIR = 900
# Strength of a jump
PLAYER_JUMP_IMPULSE = 1800
# Close enough to not-moving to have the animation go to idle.
DEAD_ZONE = 0.1
# Constants used to track if the player is facing left or right
RIGHT_FACING = 0
LEFT_FACING = 1
# How many pixels to move before we change the texture in the walking animation
DISTANCE_TO_CHANGE_TEXTURE = 20
# How much force to put on the bullet
BULLET_MOVE_FORCE = 4500
# Mass of the bullet
BULLET_MASS = 0.1
# Make bullet less affected by gravity
BULLET_GRAVITY = 300
# GAMEPAD BUTTON CONFIG
JUMPBTN = 0 # A
LIVES_AT_START = 3
SCORE_XOFFSET = 10
SCORE_YOFFSET = 10
TILE_SCALING = 0.5
from itertools import cycle
MECHANDLERS_TEXTURES = {"leverMid":arcade.load_texture("resources/images/misc/leverMid.png"),"leverRight":arcade.load_texture("resources/images/misc/leverRight.png"),"leverLeft":arcade.load_texture("resources/images/misc/leverLeft.png")}
mechandler_texture_list = [arcade.load_texture("resources/images/misc/leverMid.png"),arcade.load_texture("resources/images/misc/leverRight.png"),arcade.load_texture("resources/images/misc/leverLeft.png")]
CYCLIST_OF_MECHANDLERS_TEXTURES = cycle(mechandler_texture_list)
mechandler_texture_names_list = ["leverMid", "leverRight", "leverLeft"]
cyclist_of_mechandler_texture_names_list = cycle(mechandler_texture_names_list)
print("MEMO : press T on Tiled to place objects likes keys on object mode (no simple tiles)")
class PlayerSprite(arcade.Sprite):
""" Player Sprite """
def __init__(self,
ladder_list: arcade.SpriteList,
hit_box_algorithm):
""" Init """
# Let parent initialize
super().__init__()
# Set our scale
self.scale = SPRITE_SCALING_PLAYER
# Images from Kenney.nl's Character pack
main_path = ":resources:images/animated_characters/female_person/femalePerson"
# Load textures for idle standing
self.idle_texture_pair = arcade.load_texture_pair(f"{main_path}_idle.png",
hit_box_algorithm=hit_box_algorithm)
self.jump_texture_pair = arcade.load_texture_pair(f"{main_path}_jump.png")
self.fall_texture_pair = arcade.load_texture_pair(f"{main_path}_fall.png")
# Load textures for walking
self.walk_textures = []
for i in range(8):
texture = arcade.load_texture_pair(f"{main_path}_walk{i}.png")
self.walk_textures.append(texture)
# Load textures for climbing
self.climbing_textures = []
texture = arcade.load_texture(f"{main_path}_climb0.png")
self.climbing_textures.append(texture)
texture = arcade.load_texture(f"{main_path}_climb1.png")
self.climbing_textures.append(texture)
# Set the initial texture
self.texture = self.idle_texture_pair[0]
# Hit box will be set based on the first image used.
self.hit_box = self.texture.hit_box_points
# Default to face-right
self.character_face_direction = RIGHT_FACING
# Index of our current texture
self.cur_texture = 0
# How far have we traveled horizontally since changing the texture
self.x_odometer = 0
self.y_odometer = 0
self.ladder_list = ladder_list
self.is_on_ladder = False
def pymunk_moved(self, physics_engine, dx, dy, d_angle):
""" Handle being moved by the pymunk engine """
# Figure out if we need to face left or right
if dx < -DEAD_ZONE and self.character_face_direction == RIGHT_FACING:
self.character_face_direction = LEFT_FACING
elif dx > DEAD_ZONE and self.character_face_direction == LEFT_FACING:
self.character_face_direction = RIGHT_FACING
# Are we on the ground?
is_on_ground = physics_engine.is_on_ground(self)
# Are we on a ladder?
if len(arcade.check_for_collision_with_list(self, self.ladder_list)) > 0:
if not self.is_on_ladder:
self.is_on_ladder = True
self.pymunk.gravity = (0, 0)
self.pymunk.damping = 0.0001
self.pymunk.max_vertical_velocity = PLAYER_MAX_HORIZONTAL_SPEED
else:
if self.is_on_ladder:
self.pymunk.damping = 1.0
self.pymunk.max_vertical_velocity = PLAYER_MAX_VERTICAL_SPEED
self.is_on_ladder = False
self.pymunk.gravity = None
# Add to the odometer how far we've moved
self.x_odometer += dx
self.y_odometer += dy
if self.is_on_ladder and not is_on_ground:
# Have we moved far enough to change the texture?
if abs(self.y_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
# Reset the odometer
self.y_odometer = 0
# Advance the walking animation
self.cur_texture += 1
if self.cur_texture > 1:
self.cur_texture = 0
self.texture = self.climbing_textures[self.cur_texture]
return
# Jumping animation
if not is_on_ground:
if dy > DEAD_ZONE:
self.texture = self.jump_texture_pair[self.character_face_direction]
return
elif dy < -DEAD_ZONE:
self.texture = self.fall_texture_pair[self.character_face_direction]
return
# Idle animation
if abs(dx) <= DEAD_ZONE:
self.texture = self.idle_texture_pair[self.character_face_direction]
return
# Have we moved far enough to change the texture?
if abs(self.x_odometer) > DISTANCE_TO_CHANGE_TEXTURE:
# Reset the odometer
self.x_odometer = 0
# Advance the walking animation
self.cur_texture += 1
if self.cur_texture > 7:
self.cur_texture = 0
self.texture = self.walk_textures[self.cur_texture][self.character_face_direction]
class BulletSprite(arcade.SpriteSolidColor):
""" Bullet Sprite """
def pymunk_moved(self, physics_engine, dx, dy, d_angle):
""" Handle when the sprite is moved by the physics engine. """
# If the bullet falls below the screen, remove it
if self.center_y < -100:
self.remove_from_sprite_lists()
class GameWindow(arcade.Window):
""" Main Window """
def __init__(self, width, height, title):
""" Create the variables """
# Init the parent class
super().__init__(width, height, title)
#............................................................
#camera demo example vsync:
self.set_vsync(True)
#mouse tracker:
self.mouse_pos = 0, 0
#.............................................
self.time = 0
#*********
# ////////////////////////////////////////////////////////////////
self.joysticks = None
#....................
# Get list of game controllers that are available
joysticks = arcade.get_joysticks()
# If we have any...
if joysticks:
# Grab the first one in the list
self.joystick = joysticks[0]
# Open it for input
self.joystick.open()
print("joystick open")
# Push this object as a handler for joystick events.
# Required for the on_joy* events to be called.
self.joystick.push_handlers(self)
else:
# Handle if there are no joysticks.
print("There are no joysticks, plug in a joystick and run again.")
self.joystick = None
# ////////////////////////////////////////////////////////////////
self.score = 0
self.lives = 0
self.inventory = set()
self.master_status_png: Optional[arcade.Sprite] = None
#self.master_status_name: str()
self.master_status_name: cycle([])
self.master_status_cyclist = cycle([]) #TypeError: cycle expected 1 argument, got 0
self.master_status_index = 0
self.master_status = None
self.mechandlers_textures = dict()
# Player sprite
self.player_sprite: Optional[PlayerSprite] = None
# Sprite lists we need
self.player_list: Optional[arcade.SpriteList] = None
self.wall_list: Optional[arcade.SpriteList] = None
self.bullet_list: Optional[arcade.SpriteList] = None
self.coins_list: Optional[arcade.SpriteList] = None
#self.autonom_moving_sprites_list: Optional[arcade.SpriteList] = None
self.key_lock_door_list: Optional[arcade.SpriteList] = None
self.ladder_list: Optional[arcade.SpriteList] = None
self.trap_list: Optional[arcade.SpriteList] = None
self.mechanics_list: Optional[arcade.SpriteList] = None
self.mechandler_list: Optional[arcade.SpriteList] = None
self.stairs_list: Optional[arcade.SpriteList] = None
self.enemy_list: Optional[arcade.SpriteList] = None
self.lowfric_list: Optional[arcade.SpriteList] = None
self.startposition_list: Optional[arcade.SpriteList] = None
# Track the current state of what key is pressed
self.left_pressed: bool = False
self.right_pressed: bool = False
self.up_pressed: bool = False
self.down_pressed: bool = False
# Physics engine
self.physics_engine = Optional[arcade.PymunkPhysicsEngine]
# Set background color
arcade.set_background_color(arcade.color.AMAZON)
def crash_debug(self, msg):
print("\n\n\n................... crash_debug .............")
print(msg)
print("\n\n\n_________________________________________________")
assert False
def setup(self):
""" Set up everything with the game """
self.lives = LIVES_AT_START
# Create the sprite lists
self.player_list = arcade.SpriteList()
self.bullet_list = arcade.SpriteList()
# Read in the tiled map
map_name = "resources/tmx_maps/pymunk_test_map.tmx"
my_map = arcade.tilemap.read_tmx(map_name)
# Read in the map layers
self.wall_list = arcade.tilemap.process_layer(my_map,
'Platforms',
SPRITE_SCALING_TILES,
hit_box_algorithm="Detailed")
#self.coins_list = arcade.tilemap.process_layer(my_map,
# 'Dynamic Items',
# SPRITE_SCALING_TILES,
# hit_box_algorithm="Detailed")
self.coins_list = arcade.tilemap.process_layer(my_map,
'coins_layer',
SPRITE_SCALING_TILES,
hit_box_algorithm="Detailed")
self.key_lock_door_list = arcade.tilemap.process_layer(my_map,
'key_lock_door_layer',
SPRITE_SCALING_TILES,
hit_box_algorithm="Detailed")
self.ladder_list = arcade.tilemap.process_layer(my_map,
'ladders',
SPRITE_SCALING_TILES,
use_spatial_hash=True,
hit_box_algorithm="Detailed")
self.trap_list = arcade.tilemap.process_layer(my_map,
'traps',
SPRITE_SCALING_TILES,
use_spatial_hash=True,
hit_box_algorithm="Detailed")
self.mechanics_list = arcade.tilemap.process_layer(my_map,
'mechanics',
SPRITE_SCALING_TILES,
use_spatial_hash=True)
#hit_box_algorithm="Detailed")
self.mechandler_list = arcade.tilemap.process_layer(my_map,
'mec_handlers_layer',
SPRITE_SCALING_TILES,
#use_spatial_hash=True,
hit_box_algorithm="Detailed")
#self.master_status = "leverMid" #self.master_status_cyclist.next()
self.master_status = mechandler_texture_names_list[0] #self.master_status_cyclist.next()
self.mechandlers_textures = MECHANDLERS_TEXTURES
#self.master_status_png = arcade.Sprite VA ET VIENT SELON TMX
#rint(dir(self.mechandler_list[0]))
#print(self.mechandler_list[0].texture)
#print(self.mechandler_list[0].textures)
self.master_status_png = mechandler_texture_list[0]
self.master_status_name = mechandler_texture_names_list[0]
#self.master_status_png = self.mechandler_list[0].filename
print(f"SETUP self.master_status_png {self.master_status_png}")
self.master_status_cyclist = CYCLIST_OF_MECHANDLERS_TEXTURES
self.master_status_name_cyclist = cyclist_of_mechandler_texture_names_list
self.master_status_index = 0
self.stairs_list = arcade.tilemap.process_layer(my_map,
'Stairs',
SPRITE_SCALING_TILES,
use_spatial_hash=True,
hit_box_algorithm="Detailed")
self.enemy_list = arcade.tilemap.process_layer(my_map,
'enemies',
SPRITE_SCALING_TILES,
use_spatial_hash=True,
hit_box_algorithm="Detailed")
self.lowfric_list = arcade.tilemap.process_layer(my_map,
'low_friction_platforms',
SPRITE_SCALING_TILES,
use_spatial_hash=True,
hit_box_algorithm="Detailed")
startposition_layer_name = 'Startposition'
self.startposition_list = arcade.tilemap.process_layer(map_object=my_map,
layer_name=startposition_layer_name,
scaling=TILE_SCALING,
use_spatial_hash=True)
start_XY = tuple((self.startposition_list[0].center_x,self.startposition_list[0].center_y))
# Create player sprite
self.player_sprite = PlayerSprite(self.ladder_list, hit_box_algorithm="Detailed")
# Set player location
#grid_x = 1
#grid_y = 1
#grid_x = 7
#grid_y = 15
#self.player_sprite.center_x = SPRITE_SIZE * grid_x + SPRITE_SIZE / 2
#self.player_sprite.center_y = SPRITE_SIZE * grid_y + SPRITE_SIZE / 2
self.player_sprite.center_x = start_XY[0]
self.player_sprite.center_y = start_XY[1]
# Add to player sprite list
self.player_list.append(self.player_sprite)
# Moving Sprite
self.autonom_moving_sprites_list = arcade.tilemap.process_layer(my_map,
'Moving Platforms',
SPRITE_SCALING_TILES)
# --- Pymunk Physics Engine Setup ---
# The default damping for every object controls the percent of velocity
# the object will keep each second. A value of 1.0 is no speed loss,
# 0.9 is 10% per second, 0.1 is 90% per second.
# For top-down games, this is basically the friction for moving objects.
# For platformers with gravity, this should probably be set to 1.0.
# Default value is 1.0 if not specified.
damping = DEFAULT_DAMPING
# Set the gravity. (0, 0) is good for outer space and top-down.
gravity = (0, -GRAVITY)
# Create the physics engine
self.physics_engine = arcade.PymunkPhysicsEngine(damping=damping,
gravity=gravity)
def wall_hit_handler(bullet_sprite, _wall_sprite, _arbiter, _space, _data):
""" Called for bullet/wall collision """
bullet_sprite.remove_from_sprite_lists()
self.physics_engine.add_collision_handler("bullet", "wall", post_handler=wall_hit_handler)
def item_hit_handler(bullet_sprite, item_sprite, _arbiter, _space, _data):
""" Called for bullet/wall collision """
bullet_sprite.remove_from_sprite_lists()
item_sprite.remove_from_sprite_lists()
self.physics_engine.add_collision_handler("bullet", "item", post_handler=item_hit_handler)
#def mechanicshandler_hit_handler(self, bullet_sprite, mechandler_sprite, _arbiter, _space, _data):
def mechanicshandler_hit_handler(bullet_sprite, mechandler_sprite, _arbiter, _space, _data):
""" Called for bullet/wall collision """
bullet_sprite.remove_from_sprite_lists()
#print(f"mechandler_sprite.status {mechandler_sprite.status} self.master_status {self.master_status}")
print(f"1mechandler_sprite.properties['status'] {mechandler_sprite.properties['status']} self.master_status {self.master_status}")
#mechandler_sprite.status = leverRight
#mechandler_sprite.status = "leverRight"
#self.master_status ="leverRight"
#self.master_status_index += 1
#self.master_status_cyclist.next()
self.master_status_png = next(self.master_status_cyclist)
print(f"type(self.master_status_png) {type(self.master_status_png)}")
#self.master_status_name = next(self.master_status_name)
# cyclist_of_mechandler_texture_names_list
self.master_status_name = next(self.master_status_name_cyclist)
print(f"type(self.master_status_name) {type(self.master_status_name)}")
#cyclist_of_mechandler_texture_names_list
#print(f"self.master_status_png {self.master_status_png}")
print(f"2mechandler_sprite.properties['status'] {mechandler_sprite.properties['status']} self.master_status {self.master_status}")
print("\n")
print(f". self.master_status_index {self.master_status_index}")
print(f".. self.master_status_cyclist {self.master_status_cyclist}")
#print(f"... self.master_status_cyclist[self.master_status_index] {self.master_status_cyclist[self.master_status_index]}") CYCLE IS NOT SUSCRIPTABLE
self.physics_engine.add_collision_handler("bullet", "mechandler", post_handler=mechanicshandler_hit_handler)
# Add the player.
# For the player, we set the damping to a lower value, which increases
# the damping rate. This prevents the character from traveling too far
# after the player lets off the movement keys.
# Setting the moment to PymunkPhysicsEngine.MOMENT_INF prevents it from
# rotating.
# Friction normally goes between 0 (no friction) and 1.0 (high friction)
# Friction is between two objects in contact. It is important to remember
# in top-down games that friction moving along the 'floor' is controlled
# by damping.
self.physics_engine.add_sprite(self.player_sprite,
friction=PLAYER_FRICTION,
mass=PLAYER_MASS,
moment=arcade.PymunkPhysicsEngine.MOMENT_INF,
collision_type="player",
max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
# Create the walls.
# By setting the body type to PymunkPhysicsEngine.STATIC the walls can't
# move.
# Movable objects that respond to forces are PymunkPhysicsEngine.DYNAMIC
# PymunkPhysicsEngine.KINEMATIC objects will move, but are assumed to be
# repositioned by code and don't respond to physics forces.
# Dynamic is default.
self.physics_engine.add_sprite_list(self.wall_list,
friction=WALL_FRICTION,
collision_type="wall",
body_type=arcade.PymunkPhysicsEngine.STATIC)
self.physics_engine.add_sprite_list(self.lowfric_list,
friction=ICE_FRICTION,
collision_type="ice",
body_type=arcade.PymunkPhysicsEngine.STATIC)
# Create the items
self.physics_engine.add_sprite_list(self.coins_list,
friction=DYNAMIC_ITEM_FRICTION,
collision_type="item")
self.physics_engine.add_sprite_list(self.trap_list,
friction=WALL_FRICTION,
#collision_type="wall",
collision_type="traps",
body_type=arcade.PymunkPhysicsEngine.STATIC)
self.physics_engine.add_sprite_list(self.key_lock_door_list,
friction=WALL_FRICTION,
#collision_type="wall",
collision_type="kld",
body_type=arcade.PymunkPhysicsEngine.STATIC)
self.physics_engine.add_sprite_list(self.mechandler_list,
friction=WALL_FRICTION,
#collision_type="wall",
collision_type="mechandler",
body_type=arcade.PymunkPhysicsEngine.STATIC)
# Add kinematic sprites
self.physics_engine.add_sprite_list(self.mechanics_list, body_type=arcade.PymunkPhysicsEngine.KINEMATIC)
def trap_hit_handler(player_sprite, _trap_sprite, _arbiter, _space, _data):
self.physics_engine.add_collision_handler("player", "trap", post_handler=trap_hit_handler)
print("___trap_hit_handler , calling ********** respawn") # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ! ! !
def spawn_player(self, continue_position= None):
#continue are flaged position to avoid to respawn far at start level position, usefull for wide and hardcore maps
if continue_position is None:
self.physics_engine.remove_sprite(self.player_sprite)
#self.player_sprite.remove_from_sprite_lists()
start_XY = tuple((self.startposition_list[0].center_x,self.startposition_list[0].center_y))
# Create player sprite
self.player_sprite = PlayerSprite(self.ladder_list, hit_box_algorithm="Detailed")
self.player_sprite.center_x = start_XY[0]
self.player_sprite.center_y = start_XY[1]
#self.player_list.append(player_sprite)
#del self.player_list[:]
#self.player_list.append(self.player_sprite)
self.player_list[0] = self.player_sprite
self.physics_engine.add_sprite(self.player_sprite,
friction=PLAYER_FRICTION,
mass=PLAYER_MASS,
moment=arcade.PymunkPhysicsEngine.MOMENT_INF,
collision_type="player",
max_horizontal_velocity=PLAYER_MAX_HORIZONTAL_SPEED,
max_vertical_velocity=PLAYER_MAX_VERTICAL_SPEED)
# Add to player sprite list
#self.player_list.append(self.player_sprite)
def on_key_press(self, key, modifiers):
"""Called whenever a key is pressed. """
iced_ground_contact_list = arcade.check_for_collision_with_list(self.player_list[0], self.lowfric_list)
if iced_ground_contact_list == []:
if key == arcade.key.LEFT:
self.left_pressed = True
elif key == arcade.key.RIGHT:
self.right_pressed = True
elif key == arcade.key.UP:
self.up_pressed = True
# find out if player is standing on ground, and not on a ladder
if self.physics_engine.is_on_ground(self.player_sprite) \
and not self.player_sprite.is_on_ladder:
# She is! Go ahead and jump
impulse = (0, PLAYER_JUMP_IMPULSE)
self.physics_engine.apply_impulse(self.player_sprite, impulse)
elif key == arcade.key.DOWN:
self.down_pressed = True
def on_key_release(self, key, modifiers):
"""Called when the user releases a key. """
if key == arcade.key.LEFT:
self.left_pressed = False
elif key == arcade.key.RIGHT:
self.right_pressed = False
elif key == arcade.key.UP:
self.up_pressed = False
elif key == arcade.key.DOWN:
self.down_pressed = False
def on_mouse_press(self, x, y, button, modifiers):
""" Called whenever the mouse button is clicked. """
bullet = BulletSprite(20, 5, arcade.color.DARK_YELLOW)
self.bullet_list.append(bullet)
# Position the bullet at the player's current location
start_x = self.player_sprite.center_x
start_y = self.player_sprite.center_y
bullet.position = self.player_sprite.position
# Get from the mouse the destination location for the bullet
# IMPORTANT! If you have a scrolling screen, you will also need
# to add in self.view_bottom and self.view_left.
dest_x, dest_y = self.mouse_coordinates_to_world(x, y)
# Do math to calculate how to get the bullet to the destination.
# Calculation the angle in radians between the start points
# and end points. This is the angle the bullet will travel.
x_diff = dest_x - start_x
y_diff = dest_y - start_y
angle = math.atan2(y_diff, x_diff)
# What is the 1/2 size of this sprite, so we can figure out how far
# away to spawn the bullet
size = max(self.player_sprite.width, self.player_sprite.height) / 2
# Use angle to to spawn bullet away from player in proper direction
bullet.center_x += size * math.cos(angle)
bullet.center_y += size * math.sin(angle)
# Set angle of bullet
bullet.angle = math.degrees(angle)
# Gravity to use for the bullet
# If we don't use custom gravity, bullet drops too fast, or we have
# to make it go too fast.
# Force is in relation to bullet's angle.
bullet_gravity = (0, -BULLET_GRAVITY)
# Add the sprite. This needs to be done AFTER setting the fields above.
self.physics_engine.add_sprite(bullet,
mass=BULLET_MASS,
damping=1.0,
friction=0.6,
collision_type="bullet",
gravity=bullet_gravity,
elasticity=0.9)
# Add force to bullet
force = (BULLET_MOVE_FORCE, 0)
self.physics_engine.apply_force(bullet, force)
def on_mouse_motion(self, x, y, dx, dy):
self.mouse_pos = x, y
# noinspection PyMethodMayBeStatic
def on_joybutton_press(self, _joystick, button):
""" Handle button-down event for the joystick """
print("Button {} down".format(button))
if button == JUMPBTN:
iced_ground_contact_list = arcade.check_for_collision_with_list(self.player_list[0], self.lowfric_list)
if iced_ground_contact_list == []:
if self.physics_engine.is_on_ground(self.player_sprite) and not self.player_sprite.is_on_ladder:
# She is! Go ahead and jump
impulse = (0, PLAYER_JUMP_IMPULSE)
self.physics_engine.apply_impulse(self.player_sprite, impulse)
def on_update(self, delta_time):
print(f"------------DEBUG len(self.player_list) {len(self.player_list)}")
#def on_update(self):
# Movement and game logic
for mechandler in self.mechandler_list:
#self.status = self.master_status
#mechandler.properties['status'] = self.master_status
mechandler.properties['status'] = self.master_status_name
#mechandler.texture = self.mechandlers_textures[mechandler.properties['status']] #DICO de str => fichier png
mechandler.texture = self.master_status_png
# //////////////////////////////////////////////////////////////////////////
# If there is a joystick, grab the speed.
iced_ground_contact_list = arcade.check_for_collision_with_list(self.player_list[0], self.lowfric_list)
if self.joystick:
#print(self.joystick.x)
#print(f"joystick {self.joystick.x} {self.joystick.y}")
#MOVEMENT_SPEED = 1000
# x-axis
#self.change_x = self.joystick.x * MOVEMENT_SPEED
# Set a "dead zone" to prevent drive from a centered joystick
#if abs(self.change_x) > DEAD_ZONE:
# self.change_x = 0
# print("DZ")
if iced_ground_contact_list == []:
if self.joystick.x < -0.3: #and not self.right_pressed:
# Create a force to the left. Apply it.
#if is_on_ground or self.player_sprite.is_on_ladder:
if self.physics_engine.is_on_ground(self.player_sprite):# or self.player_sprite.is_on_ladder:
force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
else:
force = (-PLAYER_MOVE_FORCE_IN_AIR, 0)
self.physics_engine.apply_force(self.player_sprite, force)
# Set friction to zero for the player while moving
self.physics_engine.set_friction(self.player_sprite, 0)
elif self.joystick.x > 0.3: #and not self.left_pressed:
# Create a force to the right. Apply it.
if self.physics_engine.is_on_ground(self.player_sprite):# or self.player_sprite.is_on_ladder:
force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
else:
force = (PLAYER_MOVE_FORCE_IN_AIR, 0)
self.physics_engine.apply_force(self.player_sprite, force)
# Set friction to zero for the player while moving
self.physics_engine.set_friction(self.player_sprite, 0)
#if self.player_sprite.is_on_ladder:
if self.player_sprite.is_on_ladder:
if self.joystick.y > 0.3:
force = (0, -PLAYER_MOVE_FORCE_ON_GROUND)
self.physics_engine.apply_force(self.player_sprite, force)
# Set friction to zero for the player while moving
self.physics_engine.set_friction(self.player_sprite, 0)
elif self.joystick.y < -0.3:
force = (0, PLAYER_MOVE_FORCE_ON_GROUND)
self.physics_engine.apply_force(self.player_sprite, force)
# Set friction to zero for the player while moving
self.physics_engine.set_friction(self.player_sprite, 0)
# /////////////////////////////////////////////////////////////////////////
is_on_ground = self.physics_engine.is_on_ground(self.player_sprite)
if iced_ground_contact_list == []:
# Update player forces based on keys pressed
if self.left_pressed and not self.right_pressed:
# Create a force to the left. Apply it.
if is_on_ground or self.player_sprite.is_on_ladder:
force = (-PLAYER_MOVE_FORCE_ON_GROUND, 0)
else:
force = (-PLAYER_MOVE_FORCE_IN_AIR, 0)
self.physics_engine.apply_force(self.player_sprite, force)
# Set friction to zero for the player while moving
self.physics_engine.set_friction(self.player_sprite, 0)
elif self.right_pressed and not self.left_pressed:
# Create a force to the right. Apply it.
if is_on_ground or self.player_sprite.is_on_ladder:
force = (PLAYER_MOVE_FORCE_ON_GROUND, 0)
else:
force = (PLAYER_MOVE_FORCE_IN_AIR, 0)
self.physics_engine.apply_force(self.player_sprite, force)
# Set friction to zero for the player while moving
self.physics_engine.set_friction(self.player_sprite, 0)
elif self.up_pressed and not self.down_pressed:
# Create a force to the right. Apply it.
if self.player_sprite.is_on_ladder:
force = (0, PLAYER_MOVE_FORCE_ON_GROUND)
self.physics_engine.apply_force(self.player_sprite, force)
# Set friction to zero for the player while moving
self.physics_engine.set_friction(self.player_sprite, 0)
elif self.down_pressed and not self.up_pressed:
# Create a force to the right. Apply it.
if self.player_sprite.is_on_ladder:
force = (0, -PLAYER_MOVE_FORCE_ON_GROUND)
self.physics_engine.apply_force(self.player_sprite, force)
# Set friction to zero for the player while moving
self.physics_engine.set_friction(self.player_sprite, 0)
else:
# Player's feet are not moving. Therefore up the friction so we stop.
self.physics_engine.set_friction(self.player_sprite, 1.0)