all repos — Legends-RPG @ 9ee373a472b1ac434cf268cdcf3875ada4c57b29

A fantasy mini-RPG built with Python and Pygame.

data/components/person.py (view raw)

  1import math, random
  2import pygame as pg
  3from .. import setup
  4
  5
  6class Person(pg.sprite.Sprite):
  7    """Base class for all world characters
  8    controlled by the computer"""
  9
 10    def __init__(self, sheet_key, x, y, direction='right', state='resting'):
 11        super(Person, self).__init__()
 12        self.name = sheet_key
 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        if direction == 'left':
 17            self.index = 1
 18        else:
 19            self.index = 0
 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.state_dict = self.create_state_dict()
 25        self.vector_dict = self.create_vector_dict()
 26        self.x_vel = 0
 27        self.y_vel = 0
 28        self.timer = 0.0
 29        self.move_timer = 0.0
 30        self.current_time = 0.0
 31        self.state = state
 32        self.blockers = self.set_blockers()
 33        self.location = self.get_tile_location()
 34        self.dialogue = ['Location: ' + str(self.location)]
 35        self.default_direction = direction
 36        self.item = None
 37
 38
 39    def create_spritesheet_dict(self, sheet_key):
 40        """Implemented by inheriting classes"""
 41        image_list = []
 42        image_dict = {}
 43        sheet = setup.GFX[sheet_key]
 44
 45        image_keys = ['facing up 1', 'facing up 2',
 46                      'facing down 1', 'facing down 2',
 47                      'facing left 1', 'facing left 2',
 48                      'facing right 1', 'facing right 2']
 49
 50        for row in range(2):
 51            for column in range(4):
 52                image_list.append(
 53                    self.get_image(column*32, row*32, 32, 32, sheet))
 54
 55        for key, image in zip(image_keys, image_list):
 56            image_dict[key] = image
 57
 58        return image_dict
 59
 60
 61    def create_animation_dict(self):
 62        """Return a dictionary of image lists for animation"""
 63        image_dict = self.spritesheet_dict
 64
 65        left_list = [image_dict['facing left 1'], image_dict['facing left 2']]
 66        right_list = [image_dict['facing right 1'], image_dict['facing right 2']]
 67        up_list = [image_dict['facing up 1'], image_dict['facing up 2']]
 68        down_list = [image_dict['facing down 1'], image_dict['facing down 2']]
 69
 70        direction_dict = {'left': left_list,
 71                          'right': right_list,
 72                          'up': up_list,
 73                          'down': down_list}
 74
 75        return direction_dict
 76
 77
 78    def create_state_dict(self):
 79        """Return a dictionary of all state methods"""
 80        state_dict = {'resting': self.resting,
 81                      'moving': self.moving,
 82                      'animated resting': self.animated_resting,
 83                      'autoresting': self.auto_resting,
 84                      'automoving': self.auto_moving}
 85
 86        return state_dict
 87
 88
 89    def create_vector_dict(self):
 90        """Return a dictionary of x and y velocities set to
 91        direction keys."""
 92        vector_dict = {'up': (0, -1),
 93                       'down': (0, 1),
 94                       'left': (-1, 0),
 95                       'right': (1, 0)}
 96
 97        return vector_dict
 98
 99
100    def update(self, current_time, *args):
101        """Implemented by inheriting classes"""
102        self.blockers = self.set_blockers()
103        self.current_time = current_time
104        self.image_list = self.animation_dict[self.direction]
105        state_function = self.state_dict[self.state]
106        state_function()
107        self.location = self.get_tile_location()
108
109
110
111    def set_blockers(self):
112        """Sets blockers to prevent collision with other sprites"""
113        blockers = []
114
115        if self.state == 'resting' or self.state == 'autoresting':
116            blockers.append(pg.Rect(self.rect.x, self.rect.y, 32, 32))
117
118        elif self.state == 'moving' or self.state == 'automoving':
119            if self.rect.x % 32 == 0:
120                tile_float = self.rect.y / float(32)
121                tile1 = (self.rect.x, math.ceil(tile_float)*32)
122                tile2 = (self.rect.x, math.floor(tile_float)*32)
123                tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)
124                tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)
125                blockers.extend([tile_rect1, tile_rect2])
126
127            elif self.rect.y % 32 == 0:
128                tile_float = self.rect.x / float(32)
129                tile1 = (math.ceil(tile_float)*32, self.rect.y)
130                tile2 = (math.floor(tile_float)*32, self.rect.y)
131                tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)
132                tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)
133                blockers.extend([tile_rect1, tile_rect2])
134
135        return blockers
136
137
138
139    def get_tile_location(self):
140        """Converts pygame coordinates into tile coordinates"""
141        if self.rect.x == 0:
142            tile_x = 0
143        elif self.rect.x % 32 == 0:
144            tile_x = (self.rect.x / 32)
145        else:
146            tile_x = 0
147
148
149        if self.rect.y == 0:
150            tile_y = 0
151        elif self.rect.y % 32 == 0:
152            tile_y = (self.rect.y / 32)
153
154        else:
155            tile_y = 0
156
157        return [tile_x, tile_y]
158
159
160    def resting(self):
161        """
162        When the Person is not moving between tiles.
163        Checks if the player is centered on a tile.
164        """
165        self.image = self.image_list[self.index]
166
167        assert(self.rect.y % 32 == 0), ('Player not centered on tile: '
168                                        + str(self.rect.y))
169        assert(self.rect.x % 32 == 0), ('Player not centered on tile'
170                                        + str(self.rect.x))
171
172
173    def moving(self):
174        """Increment index and set self.image for animation."""
175        self.animation()
176
177        assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \
178            'Not centered on tile'
179
180
181    def animated_resting(self):
182        self.animation(500)
183
184
185    def animation(self, freq=100):
186        """Adjust sprite image frame based on timer"""
187        if (self.current_time - self.timer) > freq:
188            if self.index < (len(self.image_list) - 1):
189                self.index += 1
190            else:
191                self.index = 0
192            self.timer = self.current_time
193
194        self.image = self.image_list[self.index]
195
196
197
198    def begin_moving(self, direction):
199        """Transition the player into the 'moving' state."""
200        self.direction = direction
201        self.image_list = self.animation_dict[direction]
202        self.timer = self.current_time
203        self.move_timer = self.current_time
204        self.state = 'moving'
205
206        if self.rect.x % 32 == 0:
207            self.y_vel = self.vector_dict[self.direction][1]
208        if self.rect.y % 32 == 0:
209            self.x_vel = self.vector_dict[self.direction][0]
210
211
212    def begin_resting(self):
213        """Transition the player into the 'resting' state."""
214        self.state = 'resting'
215        self.index = 1
216        self.x_vel = self.y_vel = 0
217
218
219    def begin_auto_moving(self, direction):
220        """Transition sprite to a automatic moving state"""
221        self.direction = direction
222        self.image_list = self.animation_dict[direction]
223        self.state = 'automoving'
224        self.x_vel = self.vector_dict[direction][0]
225        self.y_vel = self.vector_dict[direction][1]
226        self.move_timer = self.current_time
227
228
229    def begin_auto_resting(self):
230        """Transition sprite to an automatic resting state"""
231        self.state = 'autoresting'
232        self.index = 1
233        self.x_vel = self.y_vel = 0
234        self.move_timer = self.current_time
235
236
237    def auto_resting(self):
238        """
239        Determine when to move a sprite from resting to moving in a random
240        direction.
241        """
242        #self.image = self.image_list[self.index]
243        self.image_list = self.animation_dict[self.direction]
244        self.image = self.image_list[self.index]
245
246        assert(self.rect.y % 32 == 0), ('Player not centered on tile: '
247                                        + str(self.rect.y))
248        assert(self.rect.x % 32 == 0), ('Player not centered on tile'
249                                        + str(self.rect.x))
250
251        if (self.current_time - self.move_timer) > 2000:
252            direction_list = ['up', 'down', 'left', 'right']
253            random.shuffle(direction_list)
254            direction = direction_list[0]
255            self.begin_auto_moving(direction)
256            self.move_timer = self.current_time
257
258
259
260    def auto_moving(self):
261        """Animate sprite and check to stop"""
262        self.animation()
263
264        assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \
265            'Not centered on tile'
266
267
268
269class Player(Person):
270    """User controlled character"""
271
272    def __init__(self, direction, x=0, y=0):
273        super(Player, self).__init__('player', x, y, direction)
274
275
276    def create_vector_dict(self):
277        """Return a dictionary of x and y velocities set to
278        direction keys."""
279        vector_dict = {'up': (0, -2),
280                       'down': (0, 2),
281                       'left': (-2, 0),
282                       'right': (2, 0)}
283
284        return vector_dict
285
286
287    def update(self, keys, current_time):
288        """Updates player behavior"""
289        self.blockers = self.set_blockers()
290        self.keys = keys
291        self.current_time = current_time
292        self.check_for_input()
293        state_function = self.state_dict[self.state]
294        state_function()
295        self.location = self.get_tile_location()
296
297
298    def check_for_input(self):
299        """Checks for player input"""
300        if self.state == 'resting':
301            if self.keys[pg.K_UP]:
302                self.begin_moving('up')
303            elif self.keys[pg.K_DOWN]:
304                self.begin_moving('down')
305            elif self.keys[pg.K_LEFT]:
306                self.begin_moving('left')
307            elif self.keys[pg.K_RIGHT]:
308                self.begin_moving('right')
309
310
311
312class Soldier(Person):
313    """Soldier for the castle"""
314
315    def __init__(self, x, y, direction='down', state='resting'):
316        super(Soldier, self).__init__('soldier', x, y, direction, state)
317
318
319
320class FemaleVillager(Person):
321    """Female Person for town"""
322
323    def __init__(self, x, y):
324        super(FemaleVillager, self).__init__('femalevillager', x, y)
325        self.index = 1
326
327
328class FemaleVillager2(Person):
329    """A second female person for town"""
330    def __init__(self, x, y):
331        super(FemaleVillager2, self).__init__('femvillager2', x, y)
332        self.index = 1
333
334
335class MaleVillager(Person):
336    """Male Person for town"""
337
338    def __init__(self):
339        super(MaleVillager, self).__init__('male villager', x, y)
340
341
342class King(Person):
343    """King of the town"""
344    def __init__(self, x, y, direction='down', state='resting'):
345        super(King, self).__init__('king', x, y, direction, state)
346
347
348class Devil(Person):
349    """Devil-like villager"""
350    def __init__(self, x, y, direction='down', state='autoresting'):
351        super(Devil, self).__init__('devil', x, y, direction, state)
352
353
354class Well(pg.sprite.Sprite):
355    """Talking well"""
356    def __init__(self, x, y):
357        super(Well, self).__init__()
358        self.image = pg.Surface((32, 32))
359        self.image.set_colorkey((0,0,0))
360        self.rect = self.image.get_rect(left=x, top=y)
361        self.location = self.get_location()
362        self.dialogue = ["I'm a well!"]
363        self.blockers = [self.rect]
364        self.x_vel = self.y_vel = 0
365        self.state = 'resting'
366        self.direction = 'down'
367        self.default_direction = self.direction
368        self.item = None
369
370    def get_location(self):
371        """Get tile location"""
372        x = self.rect.x / 32
373        y = self.rect.y / 32
374
375        return [x, y]
376
377    def begin_auto_resting(self):
378        """Placeholder"""
379        pass
380
381