all repos — Legends-RPG @ 35c220742eca1ddd56f886e71e2140a27df951af

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'):
 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.move_timer = 0.0
 28        self.current_time = 0.0
 29        self.state = 'animated resting'
 30        self.blockers = self.set_blockers()
 31        self.location = self.get_tile_location()
 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(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                      'animated resting': self.animated_resting,
 78                      'autoresting': self.auto_resting,
 79                      'automoving': self.auto_moving}
 80
 81        return state_dict
 82
 83
 84    def create_vector_dict(self):
 85        """Return a dictionary of x and y velocities set to
 86        direction keys."""
 87        vector_dict = {'up': (0, -1),
 88                       'down': (0, 1),
 89                       'left': (-1, 0),
 90                       'right': (1, 0)}
 91
 92        return vector_dict
 93
 94
 95    def update(self, current_time):
 96        """Implemented by inheriting classes"""
 97        self.blockers = self.set_blockers()
 98        self.current_time = current_time
 99        state_function = self.state_dict[self.state]
100        state_function()
101        self.location = self.get_tile_location()
102
103
104    def set_blockers(self):
105        """Sets blockers to prevent collision with other sprites"""
106        blockers = []
107
108        if self.state == 'animated resting' or self.state == 'autoresting':
109            blockers.append(pg.Rect(self.rect.x, self.rect.y, 32, 32))
110
111        elif self.state == 'moving' or self.state == 'automoving':
112            if self.rect.x % 32 == 0:
113                tile_float = self.rect.y / float(32)
114                tile1 = (self.rect.x, math.ceil(tile_float)*32)
115                tile2 = (self.rect.x, math.floor(tile_float)*32)
116                tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)
117                tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)
118                blockers.extend([tile_rect1, tile_rect2])
119
120            elif self.rect.y % 32 == 0:
121                tile_float = self.rect.x / float(32)
122                tile1 = (math.ceil(tile_float)*32, self.rect.y)
123                tile2 = (math.floor(tile_float)*32, self.rect.y)
124                tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)
125                tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)
126                blockers.extend([tile_rect1, tile_rect2])
127
128        return blockers
129
130
131    def get_tile_location(self):
132        """Converts pygame coordinates into tile coordinates"""
133        if self.rect.x == 0:
134            tile_x = 1
135        elif self.rect.x % 32 == 0:
136            tile_x = (self.rect.x / 32) + 1
137        else:
138            tile_x = 0
139
140        if self.rect.y == 0:
141            tile_y = 1
142        elif self.rect.y % 32 == 0:
143            tile_y = (self.rect.y / 32) + 1
144        else:
145            tile_y = 0
146
147        return (tile_x, tile_y)
148
149
150    def resting(self):
151        """
152        When the Person is not moving between tiles.
153        Checks if the player is centered on a tile.
154        """
155        self.image = self.image_list[self.index]
156
157        assert(self.rect.y % 32 == 0), ('Player not centered on tile: '
158                                        + str(self.rect.y))
159        assert(self.rect.x % 32 == 0), ('Player not centered on tile'
160                                        + str(self.rect.x))
161
162
163    def moving(self):
164        """Increment index and set self.image for animation."""
165        self.animation()
166
167        assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \
168            'Not centered on tile'
169
170
171    def animated_resting(self):
172        self.animation(500)
173
174
175    def animation(self, freq=100):
176        """Adjust sprite image frame based on timer"""
177        if (self.current_time - self.timer) > freq:
178            if self.index < (len(self.image_list) - 1):
179                self.index += 1
180            else:
181                self.index = 0
182            self.timer = self.current_time
183
184        self.image = self.image_list[self.index]
185
186
187
188    def begin_moving(self, direction):
189        """Transition the player into the 'moving' state."""
190        self.direction = direction
191        self.image_list = self.animation_dict[direction]
192        self.timer = self.current_time
193        self.move_timer = self.current_time
194        self.state = 'moving'
195
196        if self.rect.x % 32 == 0:
197            self.y_vel = self.vector_dict[self.direction][1]
198        if self.rect.y % 32 == 0:
199            self.x_vel = self.vector_dict[self.direction][0]
200
201
202    def begin_resting(self):
203        """Transition the player into the 'resting' state."""
204        self.state = 'resting'
205        self.index = 1
206        self.x_vel = self.y_vel = 0
207
208
209    def begin_auto_moving(self, direction):
210        """Transition sprite to a automatic moving state"""
211        self.direction = direction
212        self.image_list = self.animation_dict[direction]
213        self.state = 'automoving'
214        self.x_vel = self.vector_dict[direction][0]
215        self.y_vel = self.vector_dict[direction][1]
216        self.move_timer = self.current_time
217
218
219    def begin_auto_resting(self):
220        """Transition sprite to an automatic resting state"""
221        self.state = 'autoresting'
222        self.index = 0
223        self.x_vel = self.y_vel = 0
224        self.move_timer = self.current_time
225
226
227    def auto_resting(self):
228        """
229        Determine when to move a sprite from resting to moving in a random
230        direction.
231        """
232        #self.image = self.image_list[self.index]
233        self.animation(700)
234
235        assert(self.rect.y % 32 == 0), ('Player not centered on tile: '
236                                        + str(self.rect.y))
237        assert(self.rect.x % 32 == 0), ('Player not centered on tile'
238                                        + str(self.rect.x))
239
240        if (self.current_time - self.move_timer) > 2000:
241            direction_list = ['up', 'down', 'left', 'right']
242            random.shuffle(direction_list)
243            direction = direction_list[0]
244            self.begin_auto_moving(direction)
245            self.move_timer = self.current_time
246
247
248
249    def auto_moving(self):
250        """Animate sprite and check to stop"""
251        self.animation()
252
253        assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \
254            'Not centered on tile'
255
256
257
258class Player(Person):
259    """User controlled character"""
260
261    def __init__(self, direction):
262        super(Player, self).__init__('player', 0, 0, direction)
263
264
265    def create_vector_dict(self):
266        """Return a dictionary of x and y velocities set to
267        direction keys."""
268        vector_dict = {'up': (0, -2),
269                       'down': (0, 2),
270                       'left': (-2, 0),
271                       'right': (2, 0)}
272
273        return vector_dict
274
275
276    def update(self, keys, current_time):
277        """Updates player behavior"""
278        self.blockers = self.set_blockers()
279        self.keys = keys
280        self.current_time = current_time
281        self.check_for_input()
282        state_function = self.state_dict[self.state]
283        state_function()
284        self.location = self.get_tile_location()
285
286
287    def check_for_input(self):
288        """Checks for player input"""
289        if self.state == 'resting':
290            if self.keys[pg.K_UP]:
291                self.begin_moving('up')
292            elif self.keys[pg.K_DOWN]:
293                self.begin_moving('down')
294            elif self.keys[pg.K_LEFT]:
295                self.begin_moving('left')
296            elif self.keys[pg.K_RIGHT]:
297                self.begin_moving('right')
298
299
300
301class Soldier(Person):
302    """Soldier for the castle"""
303
304    def __init__(self, x, y):
305        super(Soldier, self).__init__('soldier', x, y)
306        self.state = 'animated resting'
307
308
309
310class FemaleVillager(Person):
311    """Female Person for town"""
312
313    def __init__(self, x, y):
314        super(FemaleVillager, self).__init__('femalevillager', x, y)
315
316
317class MaleVillager(Person):
318    """Male Person for town"""
319
320    def __init__(self):
321        super(MaleVillager, self).__init__('male villager', x, y)
322