all repos — Legends-RPG @ 5dc45a6a3236bb0f37cda02f65aecb54b0e7212e

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