all repos — Legends-RPG @ fcf0f9b3eaa3beed201cf7b7e1b9b147f6c0ef7b

A fantasy mini-RPG built with Python and Pygame.

data/components/person.py (view raw)

  1__author__ = 'justinarmstrong'
  2import math
  3import pygame as pg
  4from .. import setup
  5
  6
  7class Person(pg.sprite.Sprite):
  8    """Base class for all world characters
  9    controlled by the computer"""
 10
 11    def __init__(self, sheet_key, x, y, direction='down'):
 12        super(Person, self).__init__()
 13        self.get_image = setup.tools.get_image
 14        self.spritesheet_dict = self.create_spritesheet_dict(sheet_key)
 15        self.animation_dict = self.create_animation_dict()
 16        self.index = 0
 17        self.direction = direction
 18        self.image_list = self.animation_dict[self.direction]
 19        self.image = self.image_list[self.index]
 20        self.rect = self.image.get_rect(left=x, top=y)
 21        self.old_rect = self.rect
 22        self.state_dict = self.create_state_dict()
 23        self.vector_dict = self.create_vector_dict()
 24        self.x_vel = 0
 25        self.y_vel = 0
 26        self.timer = 0.0
 27        self.current_time = 0.0
 28        self.state = 'resting'
 29        self.blockers = self.set_blockers()
 30        self.location = self.get_tile_location()
 31        self.dialogue = 'Hello there!'
 32
 33
 34    def create_spritesheet_dict(self, sheet_key):
 35        """Implemented by inheriting classes"""
 36        image_list = []
 37        image_dict = {}
 38        sheet = setup.GFX[sheet_key]
 39
 40        image_keys = ['facing up 1', 'facing up 2',
 41                      'facing down 1', 'facing down 2',
 42                      'facing left 1', 'facing left 2',
 43                      'facing right 1', 'facing right 2']
 44
 45        for row in range(2):
 46            for column in range(4):
 47                image_list.append(
 48                    self.get_image(self, column*32, row*32, 32, 32, sheet))
 49
 50        for key, image in zip(image_keys, image_list):
 51            image_dict[key] = image
 52
 53        return image_dict
 54
 55
 56    def create_animation_dict(self):
 57        """Return a dictionary of image lists for animation"""
 58        image_dict = self.spritesheet_dict
 59
 60        left_list = [image_dict['facing left 1'], image_dict['facing left 2']]
 61        right_list = [image_dict['facing right 1'], image_dict['facing right 2']]
 62        up_list = [image_dict['facing up 1'], image_dict['facing up 2']]
 63        down_list = [image_dict['facing down 1'], image_dict['facing down 2']]
 64
 65        direction_dict = {'left': left_list,
 66                          'right': right_list,
 67                          'up': up_list,
 68                          'down': down_list}
 69
 70        return direction_dict
 71
 72
 73    def create_state_dict(self):
 74        """Return a dictionary of all state methods"""
 75        state_dict = {'resting': self.resting,
 76                      'moving': self.moving}
 77
 78        return state_dict
 79
 80
 81    def create_vector_dict(self):
 82        """Return a dictionary of x and y velocities set to
 83        direction keys."""
 84        vector_dict = {'up': (0, -2),
 85                       'down': (0, 2),
 86                       'left': (-2, 0),
 87                       'right': (2, 0)}
 88
 89        return vector_dict
 90
 91
 92    def update(self, keys, current_time):
 93        """Implemented by inheriting classes"""
 94        self.blockers = self.set_blockers()
 95        self.current_time = current_time
 96        self.check_for_input()
 97        state_function = self.state_dict[self.state]
 98        state_function()
 99        self.location = self.get_tile_location()
100
101
102    def set_blockers(self):
103        """Sets blockers to prevent collision with other sprites"""
104        blockers = []
105
106        if self.state == 'resting':
107            blockers.append(pg.Rect(self.rect.x, self.rect.y, 32, 32))
108
109        elif self.state == 'moving':
110            if self.rect.x % 32 == 0:
111                tile_float = self.rect.y / float(32)
112                tile1 = (self.rect.x, math.ceil(tile_float)*32)
113                tile2 = (self.rect.x, math.floor(tile_float)*32)
114                tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)
115                tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)
116                blockers.extend([tile_rect1, tile_rect2])
117
118            elif self.rect.y % 32 == 0:
119                tile_float = self.rect.x / float(32)
120                tile1 = (math.ceil(tile_float)*32, self.rect.y)
121                tile2 = (math.floor(tile_float)*32, self.rect.y)
122                tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)
123                tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)
124                blockers.extend([tile_rect1, tile_rect2])
125
126        return blockers
127
128
129    def get_tile_location(self):
130        """Converts pygame coordinates into tile coordinates"""
131        if self.rect.x == 0:
132            tile_x = 1
133        elif self.rect.x % 32 == 0:
134            tile_x = (self.rect.x / 32) + 1
135        else:
136            tile_x = 0
137
138        if self.rect.y == 0:
139            tile_y = 1
140        elif self.rect.y % 32 == 0:
141            tile_y = (self.rect.y / 32) + 1
142        else:
143            tile_y = 0
144
145        return (tile_x, tile_y)
146
147
148    def resting(self):
149        """
150        When the Person is not moving between tiles.
151        Checks if the player is centered on a tile.
152        """
153        self.image = self.image_list[self.index]
154
155        assert(self.rect.y % 32 == 0), ('Player not centered on tile: '
156                                        + str(self.rect.y))
157        assert(self.rect.x % 32 == 0), ('Player not centered on tile'
158                                        + str(self.rect.x))
159
160
161    def moving(self):
162        """Increment index and set self.image for animation."""
163        self.animation()
164
165        assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \
166            'Not centered on tile'
167
168
169    def animation(self):
170        """Adjust sprite image frame based on timer"""
171        if (self.current_time - self.timer) > 100:
172            if self.index < (len(self.image_list) - 1):
173                self.index += 1
174            else:
175                self.index = 0
176            self.timer = self.current_time
177
178        self.image = self.image_list[self.index]
179
180
181
182    def begin_moving(self, direction):
183        """Transition the player into the 'moving' state."""
184        self.direction = direction
185        self.image_list = self.animation_dict[direction]
186        self.timer = self.current_time
187        self.state = 'moving'
188        self.old_rect = self.rect
189
190        if self.rect.x % 32 == 0:
191            self.y_vel = self.vector_dict[self.direction][1]
192        if self.rect.y % 32 == 0:
193            self.x_vel = self.vector_dict[self.direction][0]
194
195
196    def begin_resting(self):
197        """Transition the player into the 'resting' state."""
198        self.state = 'resting'
199        self.index = 1
200        self.x_vel = self.y_vel = 0
201
202
203class Player(Person):
204    """User controlled character"""
205
206    def __init__(self, direction):
207        super(Player, self).__init__('player', 0, 0, direction)
208
209
210    def update(self, keys, current_time):
211        """Updates player behavior"""
212        self.blockers = self.set_blockers()
213        self.keys = keys
214        self.current_time = current_time
215        self.check_for_input()
216        state_function = self.state_dict[self.state]
217        state_function()
218        self.location = self.get_tile_location()
219
220
221    def check_for_input(self):
222        """Checks for player input"""
223        if self.state == 'resting':
224            if self.keys[pg.K_UP]:
225                self.begin_moving('up')
226            elif self.keys[pg.K_DOWN]:
227                self.begin_moving('down')
228            elif self.keys[pg.K_LEFT]:
229                self.begin_moving('left')
230            elif self.keys[pg.K_RIGHT]:
231                self.begin_moving('right')
232
233
234
235class Soldier(Person):
236    """Soldier for the castle"""
237
238    def __init__(self, x, y):
239        super(Soldier, self).__init__('soldier', x, y)
240
241
242
243class FemaleVillager(Person):
244    """Female Person for town"""
245
246    def __init__(self, x, y):
247        super(FemaleVillager, self).__init__('femalevillager', x, y)
248
249
250class MaleVillager(Person):
251    """Male Person for town"""
252
253    def __init__(self):
254        super(MaleVillager, self).__init__('male villager', x, y)
255