all repos — Legends-RPG @ c34273ecf367cfde3fa95f9181f1e4ca13095502

A fantasy mini-RPG built with Python and Pygame.

data/components/person.py (view raw)

  1__author__ = 'justinarmstrong'
  2import math, random
  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', state='animated resting'):
 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        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.old_rect = self.rect
 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 = ['Placeholder Dialogue']
 36        self.name = sheet_key
 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 == 'animated 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 = 1
143        elif self.rect.x % 32 == 0:
144            tile_x = (self.rect.x / 32) + 1
145        else:
146            tile_x = 0
147
148        if self.rect.y == 0:
149            tile_y = 1
150        elif self.rect.y % 32 == 0:
151            tile_y = (self.rect.y / 32) + 1
152        else:
153            tile_y = 0
154
155        return (tile_x, tile_y)
156
157
158    def resting(self):
159        """
160        When the Person is not moving between tiles.
161        Checks if the player is centered on a tile.
162        """
163        self.image = self.image_list[self.index]
164
165        assert(self.rect.y % 32 == 0), ('Player not centered on tile: '
166                                        + str(self.rect.y))
167        assert(self.rect.x % 32 == 0), ('Player not centered on tile'
168                                        + str(self.rect.x))
169
170
171    def moving(self):
172        """Increment index and set self.image for animation."""
173        self.animation()
174
175        assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \
176            'Not centered on tile'
177
178
179    def animated_resting(self):
180        self.animation(500)
181
182
183    def animation(self, freq=100):
184        """Adjust sprite image frame based on timer"""
185        if (self.current_time - self.timer) > freq:
186            if self.index < (len(self.image_list) - 1):
187                self.index += 1
188            else:
189                self.index = 0
190            self.timer = self.current_time
191
192        self.image = self.image_list[self.index]
193
194
195
196    def begin_moving(self, direction):
197        """Transition the player into the 'moving' state."""
198        self.direction = direction
199        self.image_list = self.animation_dict[direction]
200        self.timer = self.current_time
201        self.move_timer = self.current_time
202        self.state = 'moving'
203
204        if self.rect.x % 32 == 0:
205            self.y_vel = self.vector_dict[self.direction][1]
206        if self.rect.y % 32 == 0:
207            self.x_vel = self.vector_dict[self.direction][0]
208
209
210    def begin_resting(self):
211        """Transition the player into the 'resting' state."""
212        self.state = 'resting'
213        self.index = 1
214        self.x_vel = self.y_vel = 0
215
216
217    def begin_auto_moving(self, direction):
218        """Transition sprite to a automatic moving state"""
219        self.direction = direction
220        self.image_list = self.animation_dict[direction]
221        self.state = 'automoving'
222        self.x_vel = self.vector_dict[direction][0]
223        self.y_vel = self.vector_dict[direction][1]
224        self.move_timer = self.current_time
225
226
227    def begin_auto_resting(self):
228        """Transition sprite to an automatic resting state"""
229        self.state = 'autoresting'
230        self.index = 0
231        self.x_vel = self.y_vel = 0
232        self.move_timer = self.current_time
233
234
235    def auto_resting(self):
236        """
237        Determine when to move a sprite from resting to moving in a random
238        direction.
239        """
240        #self.image = self.image_list[self.index]
241        self.animation(700)
242
243        assert(self.rect.y % 32 == 0), ('Player not centered on tile: '
244                                        + str(self.rect.y))
245        assert(self.rect.x % 32 == 0), ('Player not centered on tile'
246                                        + str(self.rect.x))
247
248        if (self.current_time - self.move_timer) > 2000:
249            direction_list = ['up', 'down', 'left', 'right']
250            random.shuffle(direction_list)
251            direction = direction_list[0]
252            self.begin_auto_moving(direction)
253            self.move_timer = self.current_time
254
255
256
257    def auto_moving(self):
258        """Animate sprite and check to stop"""
259        self.animation()
260
261        assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \
262            'Not centered on tile'
263
264
265
266class Player(Person):
267    """User controlled character"""
268
269    def __init__(self, direction):
270        super(Player, self).__init__('player', 0, 0, direction)
271
272
273    def create_vector_dict(self):
274        """Return a dictionary of x and y velocities set to
275        direction keys."""
276        vector_dict = {'up': (0, -2),
277                       'down': (0, 2),
278                       'left': (-2, 0),
279                       'right': (2, 0)}
280
281        return vector_dict
282
283
284    def update(self, keys, current_time):
285        """Updates player behavior"""
286        self.blockers = self.set_blockers()
287        self.keys = keys
288        self.current_time = current_time
289        self.check_for_input()
290        state_function = self.state_dict[self.state]
291        state_function()
292        self.location = self.get_tile_location()
293
294
295    def check_for_input(self):
296        """Checks for player input"""
297        if self.state == 'resting':
298            if self.keys[pg.K_UP]:
299                self.begin_moving('up')
300            elif self.keys[pg.K_DOWN]:
301                self.begin_moving('down')
302            elif self.keys[pg.K_LEFT]:
303                self.begin_moving('left')
304            elif self.keys[pg.K_RIGHT]:
305                self.begin_moving('right')
306
307
308
309class Soldier(Person):
310    """Soldier for the castle"""
311
312    def __init__(self, x, y, direction='down', state='animated resting'):
313        super(Soldier, self).__init__('soldier', x, y, direction, state)
314
315
316
317class FemaleVillager(Person):
318    """Female Person for town"""
319
320    def __init__(self, x, y):
321        super(FemaleVillager, self).__init__('femalevillager', x, y)
322
323
324class MaleVillager(Person):
325    """Male Person for town"""
326
327    def __init__(self):
328        super(MaleVillager, self).__init__('male villager', x, y)
329