data/components/person.py (view raw)
1from __future__ import division
2import math, random, copy
3import pygame as pg
4from .. import setup
5from .. import constants as c
6
7
8class Person(pg.sprite.Sprite):
9 """Base class for all world characters
10 controlled by the computer"""
11
12 def __init__(self, sheet_key, x, y, direction='down', state='resting', index=0):
13 super(Person, self).__init__()
14 self.alpha = 255
15 self.name = sheet_key
16 self.get_image = setup.tools.get_image
17 self.spritesheet_dict = self.create_spritesheet_dict(sheet_key)
18 self.animation_dict = self.create_animation_dict()
19 self.index = index
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.origin_pos = self.rect.topleft
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 = ['Location: ' + str(self.location)]
36 self.default_direction = direction
37 self.item = None
38 self.wander_box = self.make_wander_box()
39 self.observers = []
40 self.health = 0
41 self.death_image = pg.transform.scale2x(self.image)
42 self.battle = None
43
44 def create_spritesheet_dict(self, sheet_key):
45 """Implemented by inheriting classes"""
46 image_list = []
47 image_dict = {}
48 sheet = setup.GFX[sheet_key]
49
50 image_keys = ['facing up 1', 'facing up 2',
51 'facing down 1', 'facing down 2',
52 'facing left 1', 'facing left 2',
53 'facing right 1', 'facing right 2']
54
55 for row in range(2):
56 for column in range(4):
57 image_list.append(
58 self.get_image(column*32, row*32, 32, 32, sheet))
59
60 for key, image in zip(image_keys, image_list):
61 image_dict[key] = image
62
63 return image_dict
64
65 def create_animation_dict(self):
66 """Return a dictionary of image lists for animation"""
67 image_dict = self.spritesheet_dict
68
69 left_list = [image_dict['facing left 1'], image_dict['facing left 2']]
70 right_list = [image_dict['facing right 1'], image_dict['facing right 2']]
71 up_list = [image_dict['facing up 1'], image_dict['facing up 2']]
72 down_list = [image_dict['facing down 1'], image_dict['facing down 2']]
73
74 direction_dict = {'left': left_list,
75 'right': right_list,
76 'up': up_list,
77 'down': down_list}
78
79 return direction_dict
80
81 def create_state_dict(self):
82 """Return a dictionary of all state methods"""
83 state_dict = {'resting': self.resting,
84 'moving': self.moving,
85 'animated resting': self.animated_resting,
86 'autoresting': self.auto_resting,
87 'automoving': self.auto_moving,
88 'battle resting': self.battle_resting,
89 'attack': self.attack,
90 'enemy attack': self.enemy_attack,
91 c.RUN_AWAY: self.run_away,
92 c.VICTORY_DANCE: self.victory_dance,
93 c.KNOCK_BACK: self.knock_back,
94 c.FADE_DEATH: self.fade_death}
95
96 return state_dict
97
98 def create_vector_dict(self):
99 """Return a dictionary of x and y velocities set to
100 direction keys."""
101 vector_dict = {'up': (0, -1),
102 'down': (0, 1),
103 'left': (-1, 0),
104 'right': (1, 0)}
105
106 return vector_dict
107
108 def update(self, current_time, *args):
109 """Implemented by inheriting classes"""
110 self.blockers = self.set_blockers()
111 self.current_time = current_time
112 self.image_list = self.animation_dict[self.direction]
113 state_function = self.state_dict[self.state]
114 state_function()
115 self.location = self.get_tile_location()
116
117 def set_blockers(self):
118 """Sets blockers to prevent collision with other sprites"""
119 blockers = []
120
121 if self.state == 'resting' or self.state == 'autoresting':
122 blockers.append(pg.Rect(self.rect.x, self.rect.y, 32, 32))
123
124 elif self.state == 'moving' or self.state == 'automoving':
125 if self.rect.x % 32 == 0:
126 tile_float = self.rect.y / float(32)
127 tile1 = (self.rect.x, math.ceil(tile_float)*32)
128 tile2 = (self.rect.x, math.floor(tile_float)*32)
129 tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)
130 tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)
131 blockers.extend([tile_rect1, tile_rect2])
132
133 elif self.rect.y % 32 == 0:
134 tile_float = self.rect.x / float(32)
135 tile1 = (math.ceil(tile_float)*32, self.rect.y)
136 tile2 = (math.floor(tile_float)*32, self.rect.y)
137 tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)
138 tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)
139 blockers.extend([tile_rect1, tile_rect2])
140
141 return blockers
142
143 def get_tile_location(self):
144 """
145 Convert pygame coordinates into tile coordinates.
146 """
147 if self.rect.x == 0:
148 tile_x = 0
149 elif self.rect.x % 32 == 0:
150 tile_x = (self.rect.x / 32)
151 else:
152 tile_x = 0
153
154 if self.rect.y == 0:
155 tile_y = 0
156 elif self.rect.y % 32 == 0:
157 tile_y = (self.rect.y / 32)
158 else:
159 tile_y = 0
160
161 return [tile_x, tile_y]
162
163
164 def make_wander_box(self):
165 """
166 Make a list of rects that surround the initial location
167 of a sprite to limit his/her wandering.
168 """
169 x = int(self.location[0])
170 y = int(self.location[1])
171 box_list = []
172 box_rects = []
173
174 for i in range(x-3, x+4):
175 box_list.append([i, y-3])
176 box_list.append([i, y+3])
177
178 for i in range(y-2, y+3):
179 box_list.append([x-3, i])
180 box_list.append([x+3, i])
181
182 for box in box_list:
183 left = box[0]*32
184 top = box[1]*32
185 box_rects.append(pg.Rect(left, top, 32, 32))
186
187 return box_rects
188
189
190 def resting(self):
191 """
192 When the Person is not moving between tiles.
193 Checks if the player is centered on a tile.
194 """
195 self.image = self.image_list[self.index]
196
197 assert(self.rect.y % 32 == 0), ('Player not centered on tile: '
198 + str(self.rect.y) + " : " + str(self.name))
199 assert(self.rect.x % 32 == 0), ('Player not centered on tile'
200 + str(self.rect.x))
201
202 def moving(self):
203 """
204 Increment index and set self.image for animation.
205 """
206 self.animation()
207 assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \
208 'Not centered on tile'
209
210 def animated_resting(self):
211 self.animation(500)
212
213 def animation(self, freq=100):
214 """
215 Adjust sprite image frame based on timer.
216 """
217 if (self.current_time - self.timer) > freq:
218 if self.index < (len(self.image_list) - 1):
219 self.index += 1
220 else:
221 self.index = 0
222 self.timer = self.current_time
223
224 self.image = self.image_list[self.index]
225
226 def begin_moving(self, direction):
227 """
228 Transition the player into the 'moving' state.
229 """
230 self.direction = direction
231 self.image_list = self.animation_dict[direction]
232 self.timer = self.current_time
233 self.move_timer = self.current_time
234 self.state = 'moving'
235
236 if self.rect.x % 32 == 0:
237 self.y_vel = self.vector_dict[self.direction][1]
238 if self.rect.y % 32 == 0:
239 self.x_vel = self.vector_dict[self.direction][0]
240
241
242 def begin_resting(self):
243 """
244 Transition the player into the 'resting' state.
245 """
246 self.state = 'resting'
247 self.index = 1
248 self.x_vel = self.y_vel = 0
249
250 def begin_auto_moving(self, direction):
251 """
252 Transition sprite to a automatic moving state.
253 """
254 self.direction = direction
255 self.image_list = self.animation_dict[direction]
256 self.state = 'automoving'
257 self.x_vel = self.vector_dict[direction][0]
258 self.y_vel = self.vector_dict[direction][1]
259 self.move_timer = self.current_time
260
261 def begin_auto_resting(self):
262 """
263 Transition sprite to an automatic resting state.
264 """
265 self.state = 'autoresting'
266 self.index = 1
267 self.x_vel = self.y_vel = 0
268 self.move_timer = self.current_time
269
270
271 def auto_resting(self):
272 """
273 Determine when to move a sprite from resting to moving in a random
274 direction.
275 """
276 #self.image = self.image_list[self.index]
277 self.image_list = self.animation_dict[self.direction]
278 self.image = self.image_list[self.index]
279
280 assert(self.rect.y % 32 == 0), ('Player not centered on tile: '
281 + str(self.rect.y))
282 assert(self.rect.x % 32 == 0), ('Player not centered on tile'
283 + str(self.rect.x))
284
285 if (self.current_time - self.move_timer) > 2000:
286 direction_list = ['up', 'down', 'left', 'right']
287 random.shuffle(direction_list)
288 direction = direction_list[0]
289 self.begin_auto_moving(direction)
290 self.move_timer = self.current_time
291
292 def battle_resting(self):
293 """
294 Player stays still during battle state unless he attacks.
295 """
296 pass
297
298 def enter_attack_state(self, enemy):
299 """
300 Set values for attack state.
301 """
302 self.attacked_enemy = enemy
303 self.x_vel = -5
304 self.state = 'attack'
305
306
307 def attack(self):
308 """
309 Player does an attack animation.
310 """
311 FAST_FORWARD = -5
312 FAST_BACK = 5
313
314 self.rect.x += self.x_vel
315
316 if self.x_vel == FAST_FORWARD:
317 self.image = self.spritesheet_dict['facing left 1']
318 self.image = pg.transform.scale2x(self.image)
319 if self.rect.x <= self.origin_pos[0] - 110:
320 self.x_vel = FAST_BACK
321 self.notify(c.ENEMY_DAMAGED)
322 else:
323 if self.rect.x >= self.origin_pos[0]:
324 self.rect.x = self.origin_pos[0]
325 self.x_vel = 0
326 self.state = 'battle resting'
327 self.image = self.spritesheet_dict['facing left 2']
328 self.image = pg.transform.scale2x(self.image)
329 self.notify(c.PLAYER_FINISHED_ATTACK)
330
331 def enter_enemy_attack_state(self):
332 """
333 Set values for enemy attack state.
334 """
335 self.x_vel = -5
336 self.state = 'enemy attack'
337 self.origin_pos = self.rect.topleft
338 self.move_counter = 0
339
340 def enemy_attack(self):
341 """
342 Enemy does an attack animation.
343 """
344 FAST_LEFT = -5
345 FAST_RIGHT = 5
346 STARTX = self.origin_pos[0]
347
348 self.rect.x += self.x_vel
349
350 if self.move_counter == 3:
351 self.x_vel = 0
352 self.state = 'battle resting'
353 self.rect.x = STARTX
354 self.notify(c.PLAYER_DAMAGED)
355
356 elif self.x_vel == FAST_LEFT:
357 if self.rect.x <= (STARTX - 15):
358 self.x_vel = FAST_RIGHT
359 elif self.x_vel == FAST_RIGHT:
360 if self.rect.x >= (STARTX + 15):
361 self.move_counter += 1
362 self.x_vel = FAST_LEFT
363
364 def auto_moving(self):
365 """
366 Animate sprite and check to stop.
367 """
368 self.animation()
369
370 assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \
371 'Not centered on tile'
372
373 def notify(self, event):
374 """
375 Notify all observers of events.
376 """
377 for observer in self.observers:
378 observer.on_notify(event)
379
380 def calculate_hit(self, armor_list, inventory):
381 """
382 Calculate hit strength based on attack stats.
383 """
384 armor_power = 0
385 for armor in armor_list:
386 armor_power += inventory[armor]['power']
387 max_strength = max(1, (self.level * 5) - armor_power)
388 min_strength = 0
389 return random.randint(min_strength, max_strength)
390
391 def run_away(self):
392 """
393 Run away from battle state.
394 """
395 X_VEL = 5
396 self.rect.x += X_VEL
397 self.direction = 'right'
398 self.small_image_list = self.animation_dict[self.direction]
399 self.image_list = []
400 for image in self.small_image_list:
401 self.image_list.append(pg.transform.scale2x(image))
402 self.animation()
403
404 def victory_dance(self):
405 """
406 Post Victory Dance.
407 """
408 self.small_image_list = self.animation_dict[self.direction]
409 self.image_list = []
410 for image in self.small_image_list:
411 self.image_list.append(pg.transform.scale2x(image))
412 self.animation(500)
413
414 def knock_back(self):
415 """
416 Knock back when hit.
417 """
418 FORWARD_VEL = -2
419
420 self.rect.x += self.x_vel
421
422 if self.name == 'player':
423 if self.rect.x >= (self.origin_pos[0] + 10):
424 self.x_vel = FORWARD_VEL
425 elif self.rect.x <= self.origin_pos[0]:
426 self.rect.x = self.origin_pos[0]
427 self.state = 'battle resting'
428 self.x_vel = 0
429 else:
430 if self.rect.x <= (self.origin_pos[0] - 10):
431 self.x_vel = 2
432 elif self.rect.x >= self.origin_pos[0]:
433 self.rect.x = self.origin_pos[0]
434 self.state = 'battle resting'
435 self.x_vel = 0
436
437 def fade_death(self):
438 """
439 Make character become transparent in death.
440 """
441 self.image = pg.Surface((64, 64)).convert()
442 self.image.set_colorkey(c.BLACK)
443 self.image.set_alpha(self.alpha)
444 self.image.blit(self.death_image, (0, 0))
445 self.alpha -= 8
446 if self.alpha <= 0:
447 self.kill()
448 self.notify(c.ENEMY_DEAD)
449
450
451 def enter_knock_back_state(self):
452 """
453 Set values for entry to knock back state.
454 """
455 if self.name == 'player':
456 self.x_vel = 4
457 else:
458 self.x_vel = -4
459
460 self.state = c.KNOCK_BACK
461 self.origin_pos = self.rect.topleft
462
463
464class Player(Person):
465 """
466 User controlled character.
467 """
468
469 def __init__(self, direction, game_data, x=0, y=0, state='resting', index=0):
470 super(Player, self).__init__('player', x, y, direction, state, index)
471 self.damaged = False
472 self.healing = False
473 self.damage_alpha = 0
474 self.healing_alpha = 0
475 self.fade_in = True
476 self.game_data = game_data
477
478 @property
479 def level(self):
480 """
481 Make level property equal to player level in game_data.
482 """
483 return self.game_data['player stats']['Level']
484
485
486 def create_vector_dict(self):
487 """Return a dictionary of x and y velocities set to
488 direction keys."""
489 vector_dict = {'up': (0, -2),
490 'down': (0, 2),
491 'left': (-2, 0),
492 'right': (2, 0)}
493
494 return vector_dict
495
496 def update(self, keys, current_time):
497 """Updates player behavior"""
498 self.current_time = current_time
499 self.damage_animation()
500 self.healing_animation()
501 self.blockers = self.set_blockers()
502 self.keys = keys
503 self.check_for_input()
504 state_function = self.state_dict[self.state]
505 state_function()
506 self.location = self.get_tile_location()
507
508 def damage_animation(self):
509 """
510 Put a red overlay over sprite to indicate damage.
511 """
512 if self.damaged:
513 self.image = copy.copy(self.spritesheet_dict['facing left 2'])
514 self.image = pg.transform.scale2x(self.image).convert_alpha()
515 damage_image = copy.copy(self.image).convert_alpha()
516 damage_image.fill((255, 0, 0, self.damage_alpha), special_flags=pg.BLEND_RGBA_MULT)
517 self.image.blit(damage_image, (0, 0))
518 if self.fade_in:
519 self.damage_alpha += 25
520 if self.damage_alpha >= 255:
521 self.fade_in = False
522 self.damage_alpha = 255
523 elif not self.fade_in:
524 self.damage_alpha -= 25
525 if self.damage_alpha <= 0:
526 self.damage_alpha = 0
527 self.damaged = False
528 self.fade_in = True
529 self.image = self.spritesheet_dict['facing left 2']
530 self.image = pg.transform.scale2x(self.image)
531
532 def healing_animation(self):
533 """
534 Put a green overlay over sprite to indicate healing.
535 """
536 if self.healing:
537 self.image = copy.copy(self.spritesheet_dict['facing left 2'])
538 self.image = pg.transform.scale2x(self.image).convert_alpha()
539 healing_image = copy.copy(self.image).convert_alpha()
540 healing_image.fill((0, 255, 0, self.healing_alpha), special_flags=pg.BLEND_RGBA_MULT)
541 self.image.blit(healing_image, (0, 0))
542 if self.fade_in:
543 self.healing_alpha += 25
544 if self.healing_alpha >= 255:
545 self.fade_in = False
546 self.healing_alpha = 255
547 elif not self.fade_in:
548 self.healing_alpha -= 25
549 if self.healing_alpha <= 0:
550 self.healing_alpha = 0
551 self.healing = False
552 self.fade_in = True
553 self.image = self.spritesheet_dict['facing left 2']
554 self.image = pg.transform.scale2x(self.image)
555
556
557
558 def check_for_input(self):
559 """Checks for player input"""
560 if self.state == 'resting':
561 if self.keys[pg.K_UP]:
562 self.begin_moving('up')
563 elif self.keys[pg.K_DOWN]:
564 self.begin_moving('down')
565 elif self.keys[pg.K_LEFT]:
566 self.begin_moving('left')
567 elif self.keys[pg.K_RIGHT]:
568 self.begin_moving('right')
569
570 def calculate_hit(self):
571 """
572 Calculate hit strength based on attack stats.
573 """
574 weapon = self.game_data['player inventory']['equipped weapon']
575 if not weapon:
576 weapon_power = 0
577 else:
578 weapon_power = self.game_data['player inventory'][weapon]['power']
579 max_strength = weapon_power + (self.level * 5)
580 min_strength = max_strength // 2
581 return random.randint(min_strength, max_strength)
582
583
584class Enemy(Person):
585 """
586 Enemy sprite.
587 """
588 def __init__(self, sheet_key, x, y, direction='down', state='resting', index=0):
589 super(Enemy, self).__init__(sheet_key, x, y, direction, state, index)
590 self.level = 1
591 self.type = 'enemy'
592
593
594class Chest(Person):
595 """
596 Treasure chest that contains items to collect.
597 """
598 def __init__(self, x, y, id):
599 super(Chest, self).__init__('treasurechest', x, y)
600 self.spritesheet_dict = self.make_image_dict()
601 self.image_list = self.make_image_list()
602 self.image = self.image_list[self.index]
603 self.rect = self.image.get_rect(x=x, y=y)
604 self.id = id
605
606 def make_image_dict(self):
607 """
608 Make a dictionary for the sprite's images.
609 """
610 sprite_sheet = setup.GFX['treasurechest']
611 image_dict = {'closed': self.get_image(0, 0, 32, 32, sprite_sheet),
612 'opened': self.get_image(32, 0, 32, 32, sprite_sheet)}
613
614 return image_dict
615
616 def make_image_list(self):
617 """
618 Make the list of two images for the chest.
619 """
620 image_list = [self.spritesheet_dict['closed'],
621 self.spritesheet_dict['opened']]
622
623 return image_list
624
625 def update(self, current_time, *args):
626 """Implemented by inheriting classes"""
627 self.blockers = self.set_blockers()
628 self.current_time = current_time
629 state_function = self.state_dict[self.state]
630 state_function()
631 self.location = self.get_tile_location()
632
633
634
635