This repository has been archived by the owner on May 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathworld.py
1642 lines (1426 loc) · 57.9 KB
/
world.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pygame
import engine as eng
# from graphics import *
from itertools import cycle
import ipdb
import random
DATA_STAGES = {"raw": 1, "crunched": 2, "paper": 3}
ASSET_FOLDER = "assets/"
GRAVITY_VELOCITY = 4 # lets cheat for now
FLOOR_Y = 580
PLAYER_SPEED = 50
PLAYER_THROW_SPEED = eng.Vector(20, -5)
FOLLOWER_SPEED = PLAYER_SPEED - 3 # just slower than the players
PATROL_SPEED = 4 # just slower than the players
JUMP_VELOCITY = -40
DATA_DEVICE_TIMER = 120
TIMER_WIDTH = 100
PLAYER_INTERACT_DIST = 50
EJECT_SPEED = eng.Vector(20, -20)
PLAYER_MASH_NUMBER = 10 # the number of times the player has to mash a button to escape
MEETING_EVENT_HORIZON = 100 # the distance where the player will need to escape
MEETING_GRAVITAIONAL_SPHERE = 150 # the distance where the player begins to be pulled in
MEETING_PULL = 5
MEETING_TIMER = .01
DEBUG = True
STUN_VELOCITY_LOSER = eng.Vector(30, -20)
STUN_VELOCITY_WINNER = eng.Vector(10, -10)
STUN_WINNER_TIMER = 10
STUN_LOSER_TIMER = 20
LEFT_FRAME_ID = 'l_'
LADDER_CLIMB_SPEED = eng.Vector(0, 30)
MAGIC_STAIR_CONSTANT = 2 # DO NOT TOUCH, THIS IS MAGIC
def extract_dict(obj_dict):
"""
get the width, height, x and y from a json dict
:param obj_dict: A dictionary containing rect data
:type obj_dict: dict
"""
x = int(obj_dict.get('x'))
y = int(obj_dict.get('y'))
width = int(obj_dict.get('width'))
height = int(obj_dict.get('height'))
return x, y, width, height
# TODO: add more things to do
class GameObject(object):
id = 0
def __init__(self, startx, starty, width, height, obj_id=None):
"""
The top level game object. All game objects inherit from this class.
Creates a game object with at least a Pygame rect and other attributes that are needed
by all game object types
:param startx: the starting x position of the object
:type startx: int
:param starty: the starting y position of the object
:type starty: int
:param width: width of the object (sometimes not used in the child object, specifically sprite objects)
:type width: int
:param height: height of the object (sometimes not used in the child object, specifically sprite objects)
:type height: int
:param obj_id: a specified id, useful for making an object on the client side with the same id
:type obj_id: int
"""
self.rect = pygame.Rect((startx, starty, width, height))
if not obj_id:
self.id = GameObject.id # assign
GameObject.id += 1
else:
self.id = obj_id
self.render = True
self.to_del = False
self.physics = False # Does this class need physics? i.e. movement
self.collision = True # Does this class need collisions
self.dirt_sprite = True # only draw sprite if dirty
def update(self):
"""Called every frame. Put behavior that the object needs to do every frame"""
return
class NetworkedObject(object):
def __init__(self, attribute_list):
"""
An object that builds and reads packets. Packets are in the form of dictionaries with the
attribute as the key. Packets are NOT binary strings but python dicts, the serialization
of the objects is handled at a lower level.
:param attribute_list: the list of attributes that the object wants to send in the build packet methods
:type attribute_list: list[str]
"""
self.attribute_list = attribute_list
self.send_data = True
def build_packet(self, accumulator):
"""
Builds the packet if send data is true.
:param accumulator: the running list to add this packet too.
:type accumulator: list[dict]
"""
if self.send_data:
packet = {}
for attribute in self.attribute_list:
packet[attribute] = self.__getattribute__(attribute)
accumulator.append(packet)
def read_packet(self, packet):
"""
Reads the packet and updates this objects attributes.
:param packet: a packet containing the updated attributes
:type packet: dict
"""
for attribute in self.attribute_list:
self.__setattr__(attribute, packet[attribute])
class AnimateSpriteObject(object):
def __init__(self, animation_dict, start_animation='idle', convert_alpha=True):
"""
A stand alone object that allows the inherited game object to have animation sprites
Initilize all the frames of the animated sprite object
:param animation_dict: a dictionary that is keyed on the name of the animation. The dictionary
contains a tuple pair, with the name of the file at [0] and the number of frames of the sprite sheet
at [1][0] for the x and [1][1] for the y. So animation_dict[animation_name] -> (sprite_sheet_filename,
(sprite_sheet_x, sprite_sheet_y)
:type animation_dict: dict
"""
object.__init__(self)
frame_dict = {}
self.animation_frames = {}
self.sprite_sheets = {}
# not to self, don't ever unpack a tuple like this again
for animation_name, (filename, (width, height), vertical_offset, (frame_width, frame_height)) in animation_dict.items():
self.sprite_sheets[animation_name], self.animation_frames[animation_name] = self._get_frames(
ASSET_FOLDER + filename, int(width),
int(height), vertical_offset=int(vertical_offset),frame_width=int(frame_width),
frame_height=int(frame_height), convert_alpha=convert_alpha)
# get the left facing sprite
left_animation = LEFT_FRAME_ID + animation_name
self.sprite_sheets[left_animation] = pygame.transform.flip(self.sprite_sheets[animation_name], 1, 0)
self.animation_frames[left_animation] = self.animation_frames[animation_name][::-1]
self.current_animation = start_animation
self.current_cycle = cycle(self.animation_frames[self.current_animation])
self.current_frame = next(self.current_cycle)
self.animation_time = 3
self.animation_timer = 0
self.pause = False # set to true for animations where the end should be held (like falling)
self.pause_frame = None
def pause_animation(self):
"""Pauses the current animation by setting it's pause attribute true"""
self.pause = True
def stop_pause_animation(self):
"""
Unsets pause. Yes I know this isn't java and a getter and setter are dumb but I forgot why I
did this so I'm just leaving it here cause I am not coding anymore on this project merely
documenting it and crying as I see my mistakes and mishaps.
"""
self.pause = False
def reset_current_animation(self):
"""
Resets the current animation to the start
"""
self.change_animation(self.current_animation)
def change_animation(self, frame):
"""
change the frames that player object is currently cycling through.
:param frame: a key that maps to a list of animation frames in self.animation_frames
:type frame: str
"""
if not frame in self.animation_frames:
frame = 'idle'
previous_rect = self.rect.copy()
self.current_animation = frame # TODO: evaluate if we need this member
self.current_cycle = cycle(self.animation_frames[self.current_animation])
self.rect = self.animation_frames[self.current_animation][0].copy()
self.rect.centerx = previous_rect.centerx
self.rect.bottom = previous_rect.bottom
def reverse_animation(self, direction):
"""
take the current animation and point it in the other direction specified
returns new animation name the object needs to change to or None
"""
is_left = True if LEFT_FRAME_ID in self.current_animation else False
new_animation = None
if direction == -1 and not is_left:
# moving right, but trying to flip to the left
new_animation = LEFT_FRAME_ID + self.current_animation
elif direction == 1 and is_left:
# moving left, but trying to flip right
new_animation = self.current_animation[len(LEFT_FRAME_ID):]
return new_animation
def animate(self):
"""
Updates the animation timer goes to next frame in current animation cycle
after the alloted animation time has passed.
"""
if not self.pause:
self.animation_timer += 1
if self.animation_timer == self.animation_time:
self.current_frame = next(self.current_cycle)
self.animation_timer = 0
def draw(self, surface):
"""Draws the player object onto surface
:param surface: the surface to draw the object, typically the window
:type surface: pygame.Surface"""
surface.blit(self.sprite_sheets[self.current_animation], self.rect, area=self.current_frame)
def _get_frames(self, filename, columns, rows,vertical_offset=None, frame_width=None,
frame_height=None, convert_alpha=True):
"""
Returns a new sprite sheet and a list of rectangular coordinates in the
file that correspond to frames in the file name. It also manipulates the spritesheet
so each frame will have the des_width and des_height
:param filename: sprite sheet file
:type filename: str
:param columns: the number of columns in the sprite sheet
:type columns: int
:param rows: the number of rows in the sprite sheet
:type rows: int
:param vertical_offset: how far down to crop out the frames
:type frame_width: int
:param frame_width: the native width of a single frame
:type frame_width: int
:param frame_height: the native width of a single frame
:type frame_height: int
"""
# OLD code cause rick insisted on using actual sizes but was a neat bit of code for resizing
# sprite sheets dynamically so I can't part with it
# if convert_alpha:
# sheet = pygame.image.load(filename).convert_alpha()
# else:
# sheet = pygame.image.load(filename).convert()
# sheet_rect = sheet.get_rect()
# sheet_width = columns * des_width
# sheet_height = rows * des_height
# sheet = pygame.transform.smoothscale(sheet, (sheet_width, sheet_height))
# sheet_rect = sheet.get_rect()
# for x in range(0, sheet_rect.width, des_width):
# for y in range(0, sheet_rect.height, des_height):
# frames.append(pygame.Rect(x, y, des_width, des_height))
# Note: des_width and des_height are ignored, assuming sprites are at
# correct size already.
if convert_alpha:
sheet = pygame.image.load(filename).convert_alpha()
else:
sheet = pygame.image.load(filename).convert()
sheet_rect = sheet.get_rect()
full_frame_width = sheet_rect.width / columns
left_offset = int((full_frame_width - frame_width) / 2)
full_frame_height = sheet_rect.height / rows
frames = []
for x in range(0, columns):
# next for loop assumes vertical_offset is less than frame height
for y in range(0, rows):
frames.append(pygame.Rect(x * full_frame_width + left_offset,
y * full_frame_height + vertical_offset, frame_width, frame_height))
return sheet, frames
class Constructor(object):
def __init__(self, game):
"""
A special object that contains a reference to the entire game. Inherited
by classes that need to construct objects in the game world
:param game: an instance of a game object
:type game: MasterPlatformer
"""
object.__init__(self)
self.game = game
def add_to_world(self, obj):
"""
Adds the object to the games added list. Note, the game object needs an added list attribute
:param obj: a game object to be added to the game world
:type obj: GameObject
"""
if self.game:
self.game.added.append(obj)
else:
ipdb.set_trace()
class MovableGameObject(GameObject):
def __init__(self, startx, starty, width, height, obj_id=None):
"""
Any game object that moves can.
:param startx: the starting x position of the object
:type startx: int
:param starty: the starting y position of the object
:type starty: int
:param width: width of the object (sometimes not used in the child object, specifically sprite objects)
:type width: int
:param height: height of the object (sometimes not used in the child object, specifically sprite objects)
:type height: int
:param obj_id: a specified id, useful for making an object on the client side with the same id
:type obj_id: int
"""
super(MovableGameObject, self).__init__(startx, starty, width, height, obj_id=obj_id)
self.velocity = eng.Vector(0, 0)
self.physics = True # most movable game objects need physics
self.last_rect = self.rect.copy()
self.on_ground = True
def move(self, velocity):
"""
sets the objects velocity. Movement is handled by the physics engine
:param velocity: the velocity vector along the x and they y axis
:type velocity: Vector
"""
self.velocity = velocity
def stop(self):
"""Sets the objects velocity to 0"""
self.velocity = eng.Vector(0, 0)
def hide_object(self):
"""Hides the object and turns off physics"""
self.render = False
self.physics = False
self.rect.x, self.rect.y = -1000, -1000 # move somewhere far off screen to
def unhide_object(self):
"""
Unhides object by turning on phyics and rendering. Function calling will need to
move the object into view though.
"""
self.render = True
self.physics = True
def respond_to_collision(self, obj, axis=None):
"""
Contains the callback for the collision between a move able object and the
object passed in. If the object passed in is the environment (i.e. SimpleScenery)
it will treate the environment as a wall and stop the object.
:param obj: object player is colliding with
:type obj: GameObject
:param axis: which axis was the player moving along.
:type axis: str
"""
if isinstance(obj, BackGroundScenery):
if axis == 'y':
self._handle_background_collision(obj)
return
if axis == 'x':
if self.velocity.x > 0:
self.rect.right = obj.rect.left
if self.velocity.x < 0:
self.rect.left = obj.rect.right
self.velocity.x = 0
if axis == 'y':
if self.velocity.y > 0:
self.rect.bottom = obj.rect.top
self.on_ground = True
if self.velocity.y < 0:
self.rect.top = obj.rect.bottom
self.velocity.y = 0
def _handle_background_collision(self, obj):
"""
collisions with things that are in the background i.e. things you can
jump on but walk through
"""
if self.velocity.y >= 0 and self.last_rect.bottom <= obj.rect.top:
# only collide going down (rember +y = down)
self.rect.bottom = obj.rect.top
self.velocity.y = 0 # stop the object
self.on_ground = True
def update(self):
"""Update the last rect attribute and checks if the object is no longer on the ground"""
self.last_rect = self.rect.copy()
if self.velocity.y != 0:
# no longer on ground
self.on_ground = False
class BackGroundScenery(GameObject):
"""
objects that you can jump on top of but can run through. Think of them as
in the background that the player jumps up on. For example a platform in mario.
TODO: This is should really just be incorporated as an attribute of simple
scenery as the backgroundness of the object comes from other objects checking
if it's a BackGroundScenery type.
"""
def draw(self, surface):
pygame.draw.rect(surface, (128, 0, 128), self.rect, 3)
@classmethod
def create_from_dict(self, obj_dict):
"""
Create an instance of this object from a dictionary
:param obj_dict: dictionary containing various inital values needed to instantiate object
:type obj_dict: dict
:returns: an instance of this object
:rtype: BackGroundScenery
"""
startx = int(obj_dict.get('x'))
starty = int(obj_dict.get('y'))
width = int(obj_dict.get('width'))
height = int(obj_dict.get('height'))
obj_id = obj_dict.get('id')
obj_id = int(obj_id) if obj_id else None
return self(startx, starty, width, height, obj_id=obj_id)
class SimpleScenery(GameObject):
"""
Simple SimpleScenery object. Game objects that are just simple shapes, don't
move and can't have objects pass through them.
TODO: Why does this and BackGroundScenery exist? It seems like it's just
to allow other objects to check for this type in collision, maybe it would
be better served as an attribute in gameobject?
"""
@classmethod
def create_from_dict(self, obj_dict):
"""
Create an instance of this object from a dictionary
:param obj_dict: dictionary containing various inital values needed to instantiate object
:type obj_dict: dict
:returns: an instance of this object
:rtype: SimpleScenery
"""
startx = int(obj_dict.get('x'))
starty = int(obj_dict.get('y'))
width = int(obj_dict.get('width'))
height = int(obj_dict.get('height'))
obj_id = obj_dict.get('id')
obj_id = int(obj_id) if obj_id else None
return self(startx, starty, width, height, obj_id=obj_id)
class Player(AnimateSpriteObject, MovableGameObject, NetworkedObject):
def __init__(self, startx, starty, width, height, sprite_sheet=None, obj_id=None, team='blue'):
"""
The object that that the user controls.
:param startx: the starting x position of the object
:type startx: int
:param starty: the starting y position of the object
:type starty: int
:param width: width of the object (ignored)
:type width: int
:param height: height of the object (ignored)
:type height: int
:param sprites_heet: the spritesheet dict of the object
:type sprite_sheet: dict
:param obj_id: a specified id, useful for making an object on the client side with the same id
:type obj_id: int
"""
MovableGameObject.__init__(self, startx, starty, width, height, obj_id=obj_id)
AnimateSpriteObject.__init__(self, sprite_sheet)
NetworkedObject.__init__(self, ['rect', 'current_frame', 'current_animation', 'id', 'render'])
self.rect = self.animation_frames[self.current_animation][0].copy()
self.sprite_sheet = sprite_sheet
self.data = None
self.direction = 1
self.moving = False
self.mash_left = 0
self.mash_right = 0
self.interact_dist = PLAYER_INTERACT_DIST # The max distance needed for the player to interact with something
self.trapped = False
self.trapper = None # Object trapping the player
self.mash_left = False
self.mash_right = False
self.escape_hit = 0
self.score = 0
self.movement_event = False # set to true if another object is mucking with the players velocity
self.escape_mash_number = PLAYER_MASH_NUMBER
self.stunned_timer = 0
self.stunned_velocity = eng.Vector(0, 0)
self.invincible_timer = 0
self.invincible = False
self.jumping = False
self.on_ladder = False
self.near_ladder = False
self.climbing = 0 # climbing modifier 1 for DOWN, -1 for up
self.team = team
@classmethod
def create_from_dict(self, obj_dict):
"""
Create an instance of this object from a dictionary
:param obj_dict: dictionary containing various inital values needed to instantiate object
:type obj_dict: dict
:returns: an instance of this object
:rtype: Player
"""
startx = int(obj_dict.get('x'))
starty = int(obj_dict.get('y'))
team = obj_dict.get('team')
sprite_sheet = obj_dict.get('sprite_sheet')
obj_id = obj_dict.get('id')
obj_id = int(obj_id) if obj_id else None
return self(startx, starty, 1, 1, sprite_sheet=sprite_sheet, obj_id=obj_id, team=team)
def jump(self):
"""Sets the player y velocity up"""
if not self.trapped and not self.stunned_timer and self.on_ground:
self.jumping = True
self.velocity.y = JUMP_VELOCITY
def up_interact(self, climable_objects):
"""
Player pressed up so may be attempting to climb something. Checks the objects
to see if any objects are close enough to climb
:param climable_objects: a list of objects that the player can climb
:type climable_objects: list[ClimableObject]
"""
if self.on_ladder:
self.climbing = -1
return
for game_obj in climable_objects:
# Check if the center of the player is inbwteen the left and right coordinates
if self.rect.colliderect(game_obj.rect):
# if (game_obj.rect.left < self.rect.centerx < game_obj.rect.right and
# game_obj.rect.top < self.rect.centery < game_obj.rect.bottom):
# On ladder, turn off physics
self.physics = False
self.on_ladder = True
self.climbing = -1
self.ladder = game_obj
self.rect.centerx = self.ladder.rect.centerx
break
def down_interact(self, climable_objects):
"""
Player pressed up so may be attempting to climb something. Checks the objects
to see if any objects are close enough to climb
:param climable_objects: a list of objects that the player can climb
:type climable_objects: list[ClimableObject]
"""
# ipdb.set_trace()
if self.on_ladder:
self.climbing = 1
return
for game_obj in climable_objects:
# Check if the center of the player is inbwteen the left and right coordinates
if (game_obj.rect.left < self.rect.centerx < game_obj.rect.right and
(game_obj.rect.top < self.rect.bottom < game_obj.rect.bottom or
game_obj.rect.top == self.rect.bottom)):
# On ladder, turn off physics
self.physics = False
self.on_ladder = True
self.climbing = 1
self.ladder = game_obj
self.rect.centerx = self.ladder.rect.centerx
break
def do_door(self, door):
"""
Do door like things, like go to the doors end_point
:param door: the doo the player is walking through
:type door: Door
"""
self.rect.x = door.end_point[0]
self.rect.y = door.end_point[1]
def cancel_up_down_interact(self):
"""stop climbing"""
self.climbing = 0
def update(self):
"""set velocity to be moved by the physics engine"""
MovableGameObject.update(self)
if self.stunned_timer:
self.stunned_timer -= 1
# self.velocity.x = self.stunned_velocity.x
elif not self.movement_event and self.moving and not self.trapped:
self.velocity.x = self.direction * PLAYER_SPEED
if self.jumping: # do things that involve jumping
self.jumping = False
if self.invincible_timer:
self.invincible_timer -= 1
else:
self.invincible = False
if self.climbing:
self.handle_ladddery_things()
# self.rect.y += self.ladder.climb_speed.y
def escape(self, direction):
"""
mash a button to escape students or meetings. An escape hit is only added when
the player hits both left and right.
:param direction: The direction the player is pressing.
:type direction: int
"""
if self.trapped:
if direction == 1:
self.mash_left = True
elif direction == 2:
self.mash_right = True
if self.mash_left and self.mash_right:
self.mash_left = False
self.mash_right = False
self.escape_hit += 1
if self.escape_hit > self.escape_mash_number:
self.trapper.un_trap(self)
self.trapper = None
self.trapped = False
self.mash_left = False
self.mash_right = False
self.escape_hit = 0
self.invincible_timer = 60
self.invincible = True
def move_right(self):
"""DEPRICATED: use move(1): sets velocity of player to move right"""
self.move(1)
def move_left(self):
"""DEPRICATED use move(-1): sets velocity of player to move left"""
self.move(-1)
def move(self, direction):
"""
Sets move to the direction passed in.
:param direction: the direction to move the player. -1 for left, 1 for right
:type direction: int
"""
if self.on_ladder:
self._turn_physics_on() # cancel being on ladder so we can move
self.direction = direction
self.moving = True
self.change_animation('moving')
new_animation = self.reverse_animation(direction) # change animation frame if need be
if new_animation:
self.change_animation(new_animation)
def stop_right(self):
"""sets velocity to 0"""
if self.direction == 1:
self.velocity.x = 0
self.moving = False
self.change_animation('idle')
# TODO: why have two methods for stop
def stop_left(self):
"""sets velocity to 0"""
if self.direction == -1:
self.velocity.x = 0
self.moving = False
self.change_animation('idle')
def read_packet(self, packet):
"""
Same as the NetworkedObject read packet but a little more work to change the
animation
:param packet: the packet containing updated information for the player
:type packet: dict
"""
if packet['current_animation'] != self.current_frame:
self.change_animation(packet['current_animation'])
super(Player, self).read_packet(packet)
def interact(self, game_objs):
"""
a catch all function that called when hitting the interact button. It will
look through the game_objs and if it's with a minimum threshold(self.interact_dist), call specific functions
based on what the objects are.
:param game_objs: A list of game objects that the player can potentially interact with
:type game_objs: list of GameObject
"""
if self.data:
throw_data = True
else:
throw_data = False
interact_obj = None
for game_obj in game_objs:
if isinstance(game_obj, DataDevice):
if self.rect.colliderect(game_obj.rect):
interact_obj = game_obj
if not interact_obj and throw_data:
self.throw_data()
elif isinstance(interact_obj, DataCruncher) and self.data:
interact_obj.interact(self)
elif isinstance(interact_obj, DataDevice) and self.data:
self.throw_data()
elif isinstance(interact_obj, DataDevice) and not self.data:
interact_obj.interact(self)
def handle_ladddery_things(self):
"""do laddery things like climb up and down"""
self.rect.y += (self.ladder.climb_speed.y * self.climbing)
if self.rect.bottom <= self.ladder.top: # hit the top
self.last_rect = self.rect.copy()
self.last_rect.bottom = self.ladder.top - 1 # this is the most hacked thing I've ever done ever
# at the top
self.rect.bottom = self.ladder.top
self._turn_physics_on()
elif self.rect.bottom >= self.ladder.bottom:
self.rect.bottom = self.ladder.bottom
self._turn_physics_on()
def _turn_physics_on(self):
"""turn the player physics on"""
self.physics = True
self.on_ladder = False
self.climbing = False
def draw(self, surface):
"""
Draws the player object onto surface
:param surface: the surface to draw the object, typically the window
:type surface: pygame.Surface
"""
AnimateSpriteObject.draw(self, surface)
def respond_to_collision(self, obj, axis=None):
"""
Contains the callback for the collision between a player object and a game object passed in. Axis is needed
for collisions that halt movement
:param obj: object player is colliding with
:type obj: GameObject
:param axis: which axis was the player moving along.
:type axis: str
"""
if type(obj) == Data:
if self.data is None and obj.team == self.team:
self.data = obj
self.data.hide_object()
self.change_animation('hasdata')
self.data.player = self
elif type(obj) == Door:
self.do_door(obj)
else:
if self.on_ladder and type(obj) == SimpleScenery:
if type(obj) != SimpleScenery:
super(Player, self).respond_to_collision(obj, axis)
else:
super(Player, self).respond_to_collision(obj, axis)
if isinstance(obj, Player) and not self.stunned_timer:
self.joust_attack(obj)
if (isinstance(obj, Meeting) or isinstance(obj, Follower)) and not self.trapped:
# got sucked trapped by something
obj.trap(self)
def joust_attack(self, other_player):
"""The player collided with another, determine who 'won' and properly stun the player"""
if self.rect.centery < other_player.rect.centery:
dominate_player = self
losing_player = other_player
elif self.rect.centery > other_player.rect.centery:
dominate_player = other_player
losing_player = self
else:
return # are currently on the same plane
# figure out which way the dominate player bumped into the loser were going
if dominate_player.rect.centerx > losing_player.rect.centerx:
# hit right side of loser, push to the left
losing_player.velocity.x = -STUN_VELOCITY_LOSER.x
dominate_player.velocity.x = STUN_VELOCITY_WINNER.x
elif dominate_player.rect.centerx < losing_player.rect.centerx:
losing_player.velocity.x = STUN_VELOCITY_LOSER.x
dominate_player.velocity.x = -STUN_VELOCITY_WINNER.x
else:
# on top of the other player, pick one at random
modifier = random.randint(0, 1) * 2 - 1
losing_player.velocity.x = STUN_VELOCITY_LOSER.x * modifier
dominate_player.velocity.x = STUN_VELOCITY_WINNER.x * -modifier
losing_player.stunned_timer = STUN_LOSER_TIMER
dominate_player.stunned_timer = STUN_WINNER_TIMER
dominate_player.velocity.y = STUN_VELOCITY_WINNER.y
losing_player.velocity.y = STUN_VELOCITY_LOSER.y
if losing_player.data:
losing_player.drop_data()
def drop_data(self):
"""drop the data by calling the throw data funciton."""
self.throw_data()
def throw_data(self):
"""Through the data that the player is holding"""
# ipdb.set_trace()
if self.data:
if self.moving:
exit_buff = PLAYER_SPEED # if the player is moving, have to throw the data ahead a frame
else:
exit_buff = 20
if self.direction == -1:
self.data.rect.right = self.rect.left + (exit_buff * self.direction)
else:
self.data.rect.left = self.rect.right + (exit_buff * self.direction)
self.data.velocity.x = self.velocity.x + PLAYER_THROW_SPEED.x * self.direction
self.data.rect.y = self.rect.y
self.data.velocity.y = PLAYER_THROW_SPEED.y
self.data.unhide_object()
self.data = None
class DataDevice(BackGroundScenery, Constructor, NetworkedObject):
def __init__(self, startx, starty, width, height, obj_id=None, game=None):
"""
Devices that are scenery, but output data when interacted with. The inte
:param startx: the starting x position of the object
:type startx: int
:param starty: the starting y position of the object
:type starty: int
:param width: width of the object
:type width: int
:param height: height of the object
:type height: int
:param obj_id: a specified id, useful for making an object on the client side with the same id
:type obj_id: int
"""
BackGroundScenery.__init__(self, startx, starty, width, height, obj_id=obj_id)
Constructor.__init__(self, game)
NetworkedObject.__init__(self, ['rect', 'id'])
self.active_timer = None
self.timer_count = 0
self.data = None
self.collision = False # for now, only interaction comes with explicit buttons
@classmethod
def create_from_dict(self, obj_dict):
"""
Create an instance of this object from a dictionary
:param obj_dict: dictionary containing various inital values needed to instantiate object
:type obj_dict: dict
:returns: an instance of this object
:rtype: SimpleScenery
"""
startx, starty, width, height = extract_dict(obj_dict)
game = obj_dict.get('game')
obj_id = obj_dict.get('id')
obj_id = int(obj_id) if obj_id else None
tmp = self(startx, starty, width, height, obj_id=obj_id, game=game)
effect_json = obj_dict.get('effect_json')
if 'rawdata' in obj_dict:
tmp.load_data(obj_dict['rawdata'], effect_json)
if effect_json:
timer_blue, timer_red = tmp.load_effects(obj_dict['timer'], effect_json,
obj_dict['timer-red-pos'], obj_dict['timer-blue-pos'])
return [tmp, timer_red, timer_blue]
else:
return tmp
def generate_data(self):
"""Create a data object and eject it """
if self.active_timer == self.blue_timer:
game_obj = Data(20, 20, 40, 40, self.data_dict_blue, team='blue')
else:
game_obj = Data(20, 20, 40, 40, self.data_dict_red, team='red')
game_obj.rect.center = self.active_timer.rect.center
game_obj.velocity.y = random.randint(EJECT_SPEED.y, EJECT_SPEED.y / 2)
game_obj.velocity.x = random.randint(-EJECT_SPEED.x, EJECT_SPEED.x)
self.add_to_world(game_obj)
return game_obj
def interact(self, player):
"""
Called when a player is trying to start a timer on this object.
:param player: the player that is trying to start a timer
:type player: Player
"""
if not self.active_timer: # only allow one timer at a time
if player.team == 'blue':
self.active_timer = self.blue_timer
else:
self.active_timer = self.red_timer
self.timer_count = 0
self.active_timer.reset_current_animation()
self.active_timer.render = True
self.active_timer.pause = False
self.active_timer.send_data = True
self.active_timer.clear = False
def load_effects(self, effect_name, effect_dict, red_loc=(0,0), blue_loc=(0,0)):
"""
Load the effects for this data object. Effects are stored
as the red and blue timer.
:param effect_name: the name of the timer to load
:type effect_name: str
:param effect_dict: the dict containing all the effect information.
:type effect_dict: dict
:param red_loc: the location to place the red timer
:type red_loc: tuple
:param blue_loc: the location to place the blue timer
:type blue_loc: tuple
:returns: the blue and red timer objects
:rtype: Effect
"""
self.red_timer = self.__load_effect(effect_name, effect_dict, 'Red', red_loc)
self.blue_timer = self.__load_effect(effect_name, effect_dict, 'Blue', blue_loc)
self.timer_total = self.red_timer.animation_time * len(
self.red_timer.animation_frames[self.red_timer.current_animation]) + self.red_timer.animation_time
return self.blue_timer, self.red_timer
def __load_effect(self, effect_name, effect_dict, team, location):
"""Loads effects based on the team passed in."""
animation_dict = effect_dict[effect_name + '-' + team]
effect = Effect(self.rect.x + int(location[0]), self.rect.y - int(location[1]), 200,
200, animation_dict)
effect.physics = False
effect.collision = False
effect.animation_time = DATA_DEVICE_TIMER / len(effect.animation_frames[effect.current_animation])
return effect
def load_data(self, data_name, data_json):
"""
Stores the data_dict that is needed later to create a data object after a timer expires
:param data_name: the name of the data object, used as a key in data json + teamname
:type data_name: str
:param data_json: the dict containing all the sprite information of the data objects
:type data_json: dict
"""
self.data_dict_blue = data_json[data_name + '-Blue']
self.data_dict_red = data_json[data_name + '-Red']
def draw(self, surface):
"""should never be called, but just in case, set render to false so it wouldn't be called"""
self.render = False # nothing to draw. Should never be called but just a safefy net
def update(self):
"""
Checks if a timer is running and ticks down if that is the case. Genereates data
once the timer runs down
:returns: Whether or not the the timer finished and created more data
:rtype: bool
"""
if self.active_timer:
self.timer_count += 1
if self.timer_count >= self.timer_total:
self.generate_data()
self.active_timer.render = False
self.active_timer.reset_current_animation()
self.active_timer.pause_animation()
self.active_timer.clear = True
self.active_timer = None
self.timer_count = 0
return True # tell the sub classes that the timer is done
return False
class DataCruncher(DataDevice):
ACCEPT_STAGE = 1
def __init__(self, startx, starty, width, height, obj_id=None, game=None):
"""
Second stage of collecting data. Works like a data device in terms of timer
creation but doesn't create data, only advances it.
:param startx: the starting x position of the object
:type startx: int
:param starty: the starting y position of the object