all repos — Legends-RPG @ 16fdbad96b09182ddd52b7640fac99e317638dfa

A fantasy mini-RPG built with Python and Pygame.

data/components/person.py (view raw)

  1from __future__ import division
  2import math, random, copy
  3import pygame as pg
  4from .. import setup, observer
  5from .. import constants as c
  6
  7
  8class Person(pg.sprite.Sprite):
  9    """Base class for all world characters
 10    controlled by the computer"""
 11
 12    def __init__(self, sheet_key, x, y, direction='down', state='resting', index=0):
 13        super(Person, self).__init__()
 14        self.alpha = 255
 15        self.name = sheet_key
 16        self.get_image = setup.tools.get_image
 17        self.spritesheet_dict = self.create_spritesheet_dict(sheet_key)
 18        self.animation_dict = self.create_animation_dict()
 19        self.index = index
 20        self.direction = direction
 21        self.image_list = self.animation_dict[self.direction]
 22        self.image = self.image_list[self.index]
 23        self.rect = self.image.get_rect(left=x, top=y)
 24        self.origin_pos = self.rect.topleft
 25        self.state_dict = self.create_state_dict()
 26        self.vector_dict = self.create_vector_dict()
 27        self.x_vel = 0
 28        self.y_vel = 0
 29        self.timer = 0.0
 30        self.move_timer = 0.0
 31        self.current_time = 0.0
 32        self.state = state
 33        self.blockers = self.set_blockers()
 34        self.location = self.get_tile_location()
 35        self.dialogue = ['Location: ' + str(self.location)]
 36        self.default_direction = direction
 37        self.item = None
 38        self.wander_box = self.make_wander_box()
 39        self.observers = [observer.SoundEffects()]
 40        self.health = 0
 41        self.death_image = pg.transform.scale2x(self.image)
 42        self.battle = None
 43
 44    def create_spritesheet_dict(self, sheet_key):
 45        """Implemented by inheriting classes"""
 46        image_list = []
 47        image_dict = {}
 48        sheet = setup.GFX[sheet_key]
 49
 50        image_keys = ['facing up 1', 'facing up 2',
 51                      'facing down 1', 'facing down 2',
 52                      'facing left 1', 'facing left 2',
 53                      'facing right 1', 'facing right 2']
 54
 55        for row in range(2):
 56            for column in range(4):
 57                image_list.append(
 58                    self.get_image(column*32, row*32, 32, 32, sheet))
 59
 60        for key, image in zip(image_keys, image_list):
 61            image_dict[key] = image
 62
 63        return image_dict
 64
 65    def create_animation_dict(self):
 66        """Return a dictionary of image lists for animation"""
 67        image_dict = self.spritesheet_dict
 68
 69        left_list = [image_dict['facing left 1'], image_dict['facing left 2']]
 70        right_list = [image_dict['facing right 1'], image_dict['facing right 2']]
 71        up_list = [image_dict['facing up 1'], image_dict['facing up 2']]
 72        down_list = [image_dict['facing down 1'], image_dict['facing down 2']]
 73
 74        direction_dict = {'left': left_list,
 75                          'right': right_list,
 76                          'up': up_list,
 77                          'down': down_list}
 78
 79        return direction_dict
 80
 81    def create_state_dict(self):
 82        """Return a dictionary of all state methods"""
 83        state_dict = {'resting': self.resting,
 84                      'moving': self.moving,
 85                      'animated resting': self.animated_resting,
 86                      'autoresting': self.auto_resting,
 87                      'automoving': self.auto_moving,
 88                      'battle resting': self.battle_resting,
 89                      'attack': self.attack,
 90                      'enemy attack': self.enemy_attack,
 91                      c.RUN_AWAY: self.run_away,
 92                      c.VICTORY_DANCE: self.victory_dance,
 93                      c.KNOCK_BACK: self.knock_back,
 94                      c.FADE_DEATH: self.fade_death}
 95
 96        return state_dict
 97
 98    def create_vector_dict(self):
 99        """Return a dictionary of x and y velocities set to
100        direction keys."""
101        vector_dict = {'up': (0, -1),
102                       'down': (0, 1),
103                       'left': (-1, 0),
104                       'right': (1, 0)}
105
106        return vector_dict
107
108    def update(self, current_time, *args):
109        """Implemented by inheriting classes"""
110        self.blockers = self.set_blockers()
111        self.current_time = current_time
112        self.image_list = self.animation_dict[self.direction]
113        state_function = self.state_dict[self.state]
114        state_function()
115        self.location = self.get_tile_location()
116
117    def set_blockers(self):
118        """Sets blockers to prevent collision with other sprites"""
119        blockers = []
120
121        if self.state == 'resting' or self.state == 'autoresting':
122            blockers.append(pg.Rect(self.rect.x, self.rect.y, 32, 32))
123
124        elif self.state == 'moving' or self.state == 'automoving':
125            if self.rect.x % 32 == 0:
126                tile_float = self.rect.y / float(32)
127                tile1 = (self.rect.x, math.ceil(tile_float)*32)
128                tile2 = (self.rect.x, math.floor(tile_float)*32)
129                tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)
130                tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)
131                blockers.extend([tile_rect1, tile_rect2])
132
133            elif self.rect.y % 32 == 0:
134                tile_float = self.rect.x / float(32)
135                tile1 = (math.ceil(tile_float)*32, self.rect.y)
136                tile2 = (math.floor(tile_float)*32, self.rect.y)
137                tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)
138                tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)
139                blockers.extend([tile_rect1, tile_rect2])
140
141        return blockers
142
143    def get_tile_location(self):
144        """
145        Convert pygame coordinates into tile coordinates.
146        """
147        if self.rect.x == 0:
148            tile_x = 0
149        elif self.rect.x % 32 == 0:
150            tile_x = (self.rect.x / 32)
151        else:
152            tile_x = 0
153
154        if self.rect.y == 0:
155            tile_y = 0
156        elif self.rect.y % 32 == 0:
157            tile_y = (self.rect.y / 32)
158        else:
159            tile_y = 0
160
161        return [tile_x, tile_y]
162
163
164    def make_wander_box(self):
165        """
166        Make a list of rects that surround the initial location
167        of a sprite to limit his/her wandering.
168        """
169        x = int(self.location[0])
170        y = int(self.location[1])
171        box_list = []
172        box_rects = []
173
174        for i in range(x-3, x+4):
175            box_list.append([i, y-3])
176            box_list.append([i, y+3])
177
178        for i in range(y-2, y+3):
179            box_list.append([x-3, i])
180            box_list.append([x+3, i])
181
182        for box in box_list:
183            left = box[0]*32
184            top = box[1]*32
185            box_rects.append(pg.Rect(left, top, 32, 32))
186
187        return box_rects
188
189
190    def resting(self):
191        """
192        When the Person is not moving between tiles.
193        Checks if the player is centered on a tile.
194        """
195        self.image = self.image_list[self.index]
196
197        assert(self.rect.y % 32 == 0), ('Player not centered on tile: '
198                                        + str(self.rect.y) + " : " + str(self.name))
199        assert(self.rect.x % 32 == 0), ('Player not centered on tile'
200                                        + str(self.rect.x))
201
202    def moving(self):
203        """
204        Increment index and set self.image for animation.
205        """
206        self.animation()
207        assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \
208            'Not centered on tile'
209
210    def animated_resting(self):
211        self.animation(500)
212
213    def animation(self, freq=100):
214        """
215        Adjust sprite image frame based on timer.
216        """
217        if (self.current_time - self.timer) > freq:
218            if self.index < (len(self.image_list) - 1):
219                self.index += 1
220            else:
221                self.index = 0
222            self.timer = self.current_time
223
224        self.image = self.image_list[self.index]
225
226    def begin_moving(self, direction):
227        """
228        Transition the player into the 'moving' state.
229        """
230        self.direction = direction
231        self.image_list = self.animation_dict[direction]
232        self.timer = self.current_time
233        self.move_timer = self.current_time
234        self.state = 'moving'
235
236        if self.rect.x % 32 == 0:
237            self.y_vel = self.vector_dict[self.direction][1]
238        if self.rect.y % 32 == 0:
239            self.x_vel = self.vector_dict[self.direction][0]
240
241
242    def begin_resting(self):
243        """
244        Transition the player into the 'resting' state.
245        """
246        self.state = 'resting'
247        self.index = 1
248        self.x_vel = self.y_vel = 0
249
250    def begin_auto_moving(self, direction):
251        """
252        Transition sprite to a automatic moving state.
253        """
254        self.direction = direction
255        self.image_list = self.animation_dict[direction]
256        self.state = 'automoving'
257        self.x_vel = self.vector_dict[direction][0]
258        self.y_vel = self.vector_dict[direction][1]
259        self.move_timer = self.current_time
260
261    def begin_auto_resting(self):
262        """
263        Transition sprite to an automatic resting state.
264        """
265        self.state = 'autoresting'
266        self.index = 1
267        self.x_vel = self.y_vel = 0
268        self.move_timer = self.current_time
269
270
271    def auto_resting(self):
272        """
273        Determine when to move a sprite from resting to moving in a random
274        direction.
275        """
276        #self.image = self.image_list[self.index]
277        self.image_list = self.animation_dict[self.direction]
278        self.image = self.image_list[self.index]
279
280        assert(self.rect.y % 32 == 0), ('Player not centered on tile: '
281                                        + str(self.rect.y))
282        assert(self.rect.x % 32 == 0), ('Player not centered on tile'
283                                        + str(self.rect.x))
284
285        if (self.current_time - self.move_timer) > 2000:
286            direction_list = ['up', 'down', 'left', 'right']
287            random.shuffle(direction_list)
288            direction = direction_list[0]
289            self.begin_auto_moving(direction)
290            self.move_timer = self.current_time
291
292    def battle_resting(self):
293        """
294        Player stays still during battle state unless he attacks.
295        """
296        pass
297
298    def enter_attack_state(self, enemy):
299        """
300        Set values for attack state.
301        """
302        self.notify(c.SWORD)
303        self.attacked_enemy = enemy
304        self.x_vel = -5
305        self.state = 'attack'
306
307
308    def attack(self):
309        """
310        Player does an attack animation.
311        """
312        FAST_FORWARD = -5
313        FAST_BACK = 5
314
315        self.rect.x += self.x_vel
316
317        if self.x_vel == FAST_FORWARD:
318            self.image = self.spritesheet_dict['facing left 1']
319            self.image = pg.transform.scale2x(self.image)
320            if self.rect.x <= self.origin_pos[0] - 110:
321                self.x_vel = FAST_BACK
322                self.notify(c.ENEMY_DAMAGED)
323        else:
324            if self.rect.x >= self.origin_pos[0]:
325                self.rect.x = self.origin_pos[0]
326                self.x_vel = 0
327                self.state = 'battle resting'
328                self.image = self.spritesheet_dict['facing left 2']
329                self.image = pg.transform.scale2x(self.image)
330                self.notify(c.PLAYER_FINISHED_ATTACK)
331
332    def enter_enemy_attack_state(self):
333        """
334        Set values for enemy attack state.
335        """
336        self.x_vel = -5
337        self.state = 'enemy attack'
338        self.origin_pos = self.rect.topleft
339        self.move_counter = 0
340
341    def enemy_attack(self):
342        """
343        Enemy does an attack animation.
344        """
345        FAST_LEFT = -5
346        FAST_RIGHT = 5
347        STARTX = self.origin_pos[0]
348
349        self.rect.x += self.x_vel
350
351        if self.move_counter == 3:
352            self.x_vel = 0
353            self.state = 'battle resting'
354            self.rect.x = STARTX
355            self.notify(c.PLAYER_DAMAGED)
356
357        elif self.x_vel == FAST_LEFT:
358            if self.rect.x <= (STARTX - 15):
359                self.x_vel = FAST_RIGHT
360        elif self.x_vel == FAST_RIGHT:
361            if self.rect.x >= (STARTX + 15):
362                self.move_counter += 1
363                self.x_vel = FAST_LEFT
364
365    def auto_moving(self):
366        """
367        Animate sprite and check to stop.
368        """
369        self.animation()
370
371        assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \
372            'Not centered on tile'
373
374    def notify(self, event):
375        """
376        Notify all observers of events.
377        """
378        for observer in self.observers:
379            observer.on_notify(event)
380
381    def calculate_hit(self, armor_list, inventory):
382        """
383        Calculate hit strength based on attack stats.
384        """
385        armor_power = 0
386        for armor in armor_list:
387            armor_power += inventory[armor]['power']
388        max_strength = max(1, (self.level * 5) - armor_power)
389        min_strength = 0
390        return random.randint(min_strength, max_strength)
391
392    def run_away(self):
393        """
394        Run away from battle state.
395        """
396        X_VEL = 5
397        self.rect.x += X_VEL
398        self.direction = 'right'
399        self.small_image_list = self.animation_dict[self.direction]
400        self.image_list = []
401        for image in self.small_image_list:
402            self.image_list.append(pg.transform.scale2x(image))
403        self.animation()
404
405    def victory_dance(self):
406        """
407        Post Victory Dance.
408        """
409        self.small_image_list = self.animation_dict[self.direction]
410        self.image_list = []
411        for image in self.small_image_list:
412            self.image_list.append(pg.transform.scale2x(image))
413        self.animation(500)
414
415    def knock_back(self):
416        """
417        Knock back when hit.
418        """
419        FORWARD_VEL = -2
420
421        self.rect.x += self.x_vel
422
423        if self.name == 'player':
424            if self.rect.x >= (self.origin_pos[0] + 10):
425                self.x_vel = FORWARD_VEL
426            elif self.rect.x <= self.origin_pos[0]:
427                self.rect.x = self.origin_pos[0]
428                self.state = 'battle resting'
429                self.x_vel = 0
430        else:
431            if self.rect.x <= (self.origin_pos[0] - 10):
432                self.x_vel = 2
433            elif self.rect.x >= self.origin_pos[0]:
434                self.rect.x = self.origin_pos[0]
435                self.state = 'battle resting'
436                self.x_vel = 0
437
438    def fade_death(self):
439        """
440        Make character become transparent in death.
441        """
442        self.image = pg.Surface((64, 64)).convert()
443        self.image.set_colorkey(c.BLACK)
444        self.image.set_alpha(self.alpha)
445        self.image.blit(self.death_image, (0, 0))
446        self.alpha -= 8
447        if self.alpha <= 0:
448            self.kill()
449            self.notify(c.ENEMY_DEAD)
450
451
452    def enter_knock_back_state(self):
453        """
454        Set values for entry to knock back state.
455        """
456        if self.name == 'player':
457            self.x_vel = 4
458        else:
459            self.x_vel = -4
460
461        self.state = c.KNOCK_BACK
462        self.origin_pos = self.rect.topleft
463
464
465class Player(Person):
466    """
467    User controlled character.
468    """
469
470    def __init__(self, direction, game_data, x=0, y=0, state='resting', index=0):
471        super(Player, self).__init__('player', x, y, direction, state, index)
472        self.damaged = False
473        self.healing = False
474        self.damage_alpha = 0
475        self.healing_alpha = 0
476        self.fade_in = True
477        self.game_data = game_data
478
479    @property
480    def level(self):
481        """
482        Make level property equal to player level in game_data.
483        """
484        return self.game_data['player stats']['Level']
485
486
487    def create_vector_dict(self):
488        """Return a dictionary of x and y velocities set to
489        direction keys."""
490        vector_dict = {'up': (0, -2),
491                       'down': (0, 2),
492                       'left': (-2, 0),
493                       'right': (2, 0)}
494
495        return vector_dict
496
497    def update(self, keys, current_time):
498        """Updates player behavior"""
499        self.current_time = current_time
500        self.damage_animation()
501        self.healing_animation()
502        self.blockers = self.set_blockers()
503        self.keys = keys
504        self.check_for_input()
505        state_function = self.state_dict[self.state]
506        state_function()
507        self.location = self.get_tile_location()
508
509    def damage_animation(self):
510        """
511        Put a red overlay over sprite to indicate damage.
512        """
513        if self.damaged:
514            self.image = copy.copy(self.spritesheet_dict['facing left 2'])
515            self.image = pg.transform.scale2x(self.image).convert_alpha()
516            damage_image = copy.copy(self.image).convert_alpha()
517            damage_image.fill((255, 0, 0, self.damage_alpha), special_flags=pg.BLEND_RGBA_MULT)
518            self.image.blit(damage_image, (0, 0))
519            if self.fade_in:
520                self.damage_alpha += 25
521                if self.damage_alpha >= 255:
522                    self.fade_in = False
523                    self.damage_alpha = 255
524            elif not self.fade_in:
525                self.damage_alpha -= 25
526                if self.damage_alpha <= 0:
527                    self.damage_alpha = 0
528                    self.damaged = False
529                    self.fade_in = True
530                    self.image = self.spritesheet_dict['facing left 2']
531                    self.image = pg.transform.scale2x(self.image)
532
533    def healing_animation(self):
534        """
535        Put a green overlay over sprite to indicate healing.
536        """
537        if self.healing:
538            self.image = copy.copy(self.spritesheet_dict['facing left 2'])
539            self.image = pg.transform.scale2x(self.image).convert_alpha()
540            healing_image = copy.copy(self.image).convert_alpha()
541            healing_image.fill((0, 255, 0, self.healing_alpha), special_flags=pg.BLEND_RGBA_MULT)
542            self.image.blit(healing_image, (0, 0))
543            if self.fade_in:
544                self.healing_alpha += 25
545                if self.healing_alpha >= 255:
546                    self.fade_in = False
547                    self.healing_alpha = 255
548            elif not self.fade_in:
549                self.healing_alpha -= 25
550                if self.healing_alpha <= 0:
551                    self.healing_alpha = 0
552                    self.healing = False
553                    self.fade_in = True
554                    self.image = self.spritesheet_dict['facing left 2']
555                    self.image = pg.transform.scale2x(self.image)
556
557    def check_for_input(self):
558        """Checks for player input"""
559        if self.state == 'resting':
560            if self.keys[pg.K_UP]:
561                self.begin_moving('up')
562            elif self.keys[pg.K_DOWN]:
563                self.begin_moving('down')
564            elif self.keys[pg.K_LEFT]:
565                self.begin_moving('left')
566            elif self.keys[pg.K_RIGHT]:
567                self.begin_moving('right')
568
569    def calculate_hit(self):
570        """
571        Calculate hit strength based on attack stats.
572        """
573        weapon = self.game_data['player inventory']['equipped weapon']
574        if not weapon:
575            weapon_power = 0
576        else:
577            weapon_power = self.game_data['player inventory'][weapon]['power']
578        max_strength = weapon_power + (self.level * 5)
579        min_strength = max_strength // 2
580        return random.randint(min_strength, max_strength)
581
582
583class Enemy(Person):
584    """
585    Enemy sprite.
586    """
587    def __init__(self, sheet_key, x, y, direction='down', state='resting', index=0):
588        super(Enemy, self).__init__(sheet_key, x, y, direction, state, index)
589        self.level = 1
590        self.type = 'enemy'
591
592
593class Chest(Person):
594    """
595    Treasure chest that contains items to collect.
596    """
597    def __init__(self, x, y, id):
598        super(Chest, self).__init__('treasurechest', x, y)
599        self.spritesheet_dict = self.make_image_dict()
600        self.image_list = self.make_image_list()
601        self.image = self.image_list[self.index]
602        self.rect = self.image.get_rect(x=x, y=y)
603        self.id = id
604
605    def make_image_dict(self):
606        """
607        Make a dictionary for the sprite's images.
608        """
609        sprite_sheet = setup.GFX['treasurechest']
610        image_dict = {'closed': self.get_image(0, 0, 32, 32, sprite_sheet),
611                      'opened': self.get_image(32, 0, 32, 32, sprite_sheet)}
612
613        return image_dict
614
615    def make_image_list(self):
616        """
617        Make the list of two images for the chest.
618        """
619        image_list = [self.spritesheet_dict['closed'],
620                      self.spritesheet_dict['opened']]
621
622        return image_list
623
624    def update(self, current_time, *args):
625        """Implemented by inheriting classes"""
626        self.blockers = self.set_blockers()
627        self.current_time = current_time
628        state_function = self.state_dict[self.state]
629        state_function()
630        self.location = self.get_tile_location()
631
632
633
634