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):
381 """
382 Calculate hit strength based on attack stats.
383 """
384 max_strength = self.level * 5
385 min_strength = 0
386 return random.randint(min_strength, max_strength)
387
388 def run_away(self):
389 """
390 Run away from battle state.
391 """
392 X_VEL = 5
393 self.rect.x += X_VEL
394 self.direction = 'right'
395 self.small_image_list = self.animation_dict[self.direction]
396 self.image_list = []
397 for image in self.small_image_list:
398 self.image_list.append(pg.transform.scale2x(image))
399 self.animation()
400
401 def victory_dance(self):
402 """
403 Post Victory Dance.
404 """
405 self.small_image_list = self.animation_dict[self.direction]
406 self.image_list = []
407 for image in self.small_image_list:
408 self.image_list.append(pg.transform.scale2x(image))
409 self.animation(500)
410
411 def knock_back(self):
412 """
413 Knock back when hit.
414 """
415 FORWARD_VEL = -2
416
417 self.rect.x += self.x_vel
418
419 if self.name == 'player':
420 if self.rect.x >= (self.origin_pos[0] + 10):
421 self.x_vel = FORWARD_VEL
422 elif self.rect.x <= self.origin_pos[0]:
423 self.rect.x = self.origin_pos[0]
424 self.state = 'battle resting'
425 self.x_vel = 0
426 else:
427 if self.rect.x <= (self.origin_pos[0] - 10):
428 self.x_vel = 2
429 elif self.rect.x >= self.origin_pos[0]:
430 self.rect.x = self.origin_pos[0]
431 self.state = 'battle resting'
432 self.x_vel = 0
433
434 def fade_death(self):
435 """
436 Make character become transparent in death.
437 """
438 self.image = pg.Surface((64, 64)).convert()
439 self.image.set_colorkey(c.BLACK)
440 self.image.set_alpha(self.alpha)
441 self.image.blit(self.death_image, (0, 0))
442 self.alpha -= 8
443 if self.alpha <= 0:
444 self.kill()
445 self.notify(c.ENEMY_DEAD)
446
447
448 def enter_knock_back_state(self):
449 """
450 Set values for entry to knock back state.
451 """
452 if self.name == 'player':
453 self.x_vel = 4
454 else:
455 self.x_vel = -4
456
457 self.state = c.KNOCK_BACK
458 self.origin_pos = self.rect.topleft
459
460
461class Player(Person):
462 """
463 User controlled character.
464 """
465
466 def __init__(self, direction, game_data, x=0, y=0, state='resting', index=0):
467 super(Player, self).__init__('player', x, y, direction, state, index)
468 self.damaged = False
469 self.healing = False
470 self.damage_alpha = 0
471 self.healing_alpha = 0
472 self.fade_in = True
473 self.game_data = game_data
474
475 @property
476 def level(self):
477 """
478 Make level property equal to player level in game_data.
479 """
480 return self.game_data['player stats']['Level']
481
482
483 def create_vector_dict(self):
484 """Return a dictionary of x and y velocities set to
485 direction keys."""
486 vector_dict = {'up': (0, -2),
487 'down': (0, 2),
488 'left': (-2, 0),
489 'right': (2, 0)}
490
491 return vector_dict
492
493 def update(self, keys, current_time):
494 """Updates player behavior"""
495 self.current_time = current_time
496 self.damage_animation()
497 self.healing_animation()
498 self.blockers = self.set_blockers()
499 self.keys = keys
500 self.check_for_input()
501 state_function = self.state_dict[self.state]
502 state_function()
503 self.location = self.get_tile_location()
504
505 def damage_animation(self):
506 """
507 Put a red overlay over sprite to indicate damage.
508 """
509 if self.damaged:
510 self.image = copy.copy(self.spritesheet_dict['facing left 2'])
511 self.image = pg.transform.scale2x(self.image).convert_alpha()
512 damage_image = copy.copy(self.image).convert_alpha()
513 damage_image.fill((255, 0, 0, self.damage_alpha), special_flags=pg.BLEND_RGBA_MULT)
514 self.image.blit(damage_image, (0, 0))
515 if self.fade_in:
516 self.damage_alpha += 25
517 if self.damage_alpha >= 255:
518 self.fade_in = False
519 self.damage_alpha = 255
520 elif not self.fade_in:
521 self.damage_alpha -= 25
522 if self.damage_alpha <= 0:
523 self.damage_alpha = 0
524 self.damaged = False
525 self.fade_in = True
526 self.image = self.spritesheet_dict['facing left 2']
527 self.image = pg.transform.scale2x(self.image)
528
529 def healing_animation(self):
530 """
531 Put a green overlay over sprite to indicate healing.
532 """
533 if self.healing:
534 self.image = copy.copy(self.spritesheet_dict['facing left 2'])
535 self.image = pg.transform.scale2x(self.image).convert_alpha()
536 healing_image = copy.copy(self.image).convert_alpha()
537 healing_image.fill((0, 255, 0, self.healing_alpha), special_flags=pg.BLEND_RGBA_MULT)
538 self.image.blit(healing_image, (0, 0))
539 if self.fade_in:
540 self.healing_alpha += 25
541 if self.healing_alpha >= 255:
542 self.fade_in = False
543 self.healing_alpha = 255
544 elif not self.fade_in:
545 self.healing_alpha -= 25
546 if self.healing_alpha <= 0:
547 self.healing_alpha = 0
548 self.healing = False
549 self.fade_in = True
550 self.image = self.spritesheet_dict['facing left 2']
551 self.image = pg.transform.scale2x(self.image)
552
553
554
555 def check_for_input(self):
556 """Checks for player input"""
557 if self.state == 'resting':
558 if self.keys[pg.K_UP]:
559 self.begin_moving('up')
560 elif self.keys[pg.K_DOWN]:
561 self.begin_moving('down')
562 elif self.keys[pg.K_LEFT]:
563 self.begin_moving('left')
564 elif self.keys[pg.K_RIGHT]:
565 self.begin_moving('right')
566
567 def calculate_hit(self):
568 """
569 Calculate hit strength based on attack stats.
570 """
571 max_strength = 5 + (self.level * 5)
572 print max_strength
573 min_strength = max_strength // 2
574 return random.randint(min_strength, max_strength)
575
576
577class Enemy(Person):
578 """
579 Enemy sprite.
580 """
581 def __init__(self, sheet_key, x, y, direction='down', state='resting', index=0):
582 super(Enemy, self).__init__(sheet_key, x, y, direction, state, index)
583 self.level = 1
584
585
586class Chest(Person):
587 """
588 Treasure chest that contains items to collect.
589 """
590 def __init__(self, x, y, id):
591 super(Chest, self).__init__('treasurechest', x, y)
592 self.spritesheet_dict = self.make_image_dict()
593 self.image_list = self.make_image_list()
594 self.image = self.image_list[self.index]
595 self.rect = self.image.get_rect(x=x, y=y)
596 self.id = id
597
598 def make_image_dict(self):
599 """
600 Make a dictionary for the sprite's images.
601 """
602 sprite_sheet = setup.GFX['treasurechest']
603 image_dict = {'closed': self.get_image(0, 0, 32, 32, sprite_sheet),
604 'opened': self.get_image(32, 0, 32, 32, sprite_sheet)}
605
606 return image_dict
607
608 def make_image_list(self):
609 """
610 Make the list of two images for the chest.
611 """
612 image_list = [self.spritesheet_dict['closed'],
613 self.spritesheet_dict['opened']]
614
615 return image_list
616
617 def update(self, current_time, *args):
618 """Implemented by inheriting classes"""
619 self.blockers = self.set_blockers()
620 self.current_time = current_time
621 state_function = self.state_dict[self.state]
622 state_function()
623 self.location = self.get_tile_location()
624
625
626
627