data/collision.py (view raw)
1import random
2import pygame as pg
3from . import constants as c
4
5class CollisionHandler(object):
6 """Handles collisions between the user, blockers and computer
7 characters"""
8 def __init__(self, player, blockers, sprites, level):
9 self.player = player
10 self.static_blockers = blockers
11 self.blockers = self.make_blocker_list(blockers, sprites)
12 self.sprites = sprites
13 self.level = level
14
15 def make_blocker_list(self, blockers, sprites):
16 """
17 Return a combined list of sprite blockers and object blockers.
18 """
19 blocker_list = []
20
21 for blocker in blockers:
22 blocker_list.append(blocker)
23
24 for sprite in sprites:
25 blocker_list.extend(sprite.blockers)
26
27 return blocker_list
28
29 def update(self, keys, current_time):
30 """
31 Check for collisions between game objects.
32 """
33 self.blockers = self.make_blocker_list(self.static_blockers,
34 self.sprites)
35 self.player.rect.move_ip(self.player.x_vel, self.player.y_vel)
36 self.check_for_blockers()
37
38 for sprite in self.sprites:
39 sprite.rect.move_ip(sprite.x_vel, sprite.y_vel)
40 self.check_for_blockers()
41
42 if self.player.rect.x % 32 == 0 and self.player.rect.y % 32 == 0:
43 if not self.player.state == 'resting':
44 self.check_for_battle()
45 self.player.begin_resting()
46
47 for sprite in self.sprites:
48 if sprite.state == 'automoving':
49 if sprite.rect.x % 32 == 0 and sprite.rect.y % 32 == 0:
50 sprite.begin_auto_resting()
51
52 def check_for_blockers(self):
53 """Checks for collisions with blocker rects"""
54 player_collided = False
55 sprite_collided_list = []
56
57 for blocker in self.blockers:
58 if self.player.rect.colliderect(blocker):
59 player_collided = True
60
61 if player_collided:
62 self.reset_after_collision(self.player)
63 self.player.begin_resting()
64
65 for sprite in self.sprites:
66 for blocker in self.static_blockers:
67 if sprite.rect.colliderect(blocker):
68 sprite_collided_list.append(sprite)
69 if sprite.rect.colliderect(self.player.rect):
70 sprite_collided_list.append(sprite)
71 sprite.kill()
72 if pg.sprite.spritecollideany(sprite, self.sprites):
73 sprite_collided_list.append(sprite)
74 self.sprites.add(sprite)
75 for blocker in sprite.wander_box:
76 if sprite.rect.colliderect(blocker):
77 sprite_collided_list.append(sprite)
78
79
80 for sprite in sprite_collided_list:
81 self.reset_after_collision(sprite)
82 sprite.begin_auto_resting()
83
84 def reset_after_collision(self, sprite):
85 """Put player back to original position"""
86 if sprite.x_vel != 0:
87 sprite.rect.x -= sprite.x_vel
88 else:
89 sprite.rect.y -= sprite.y_vel
90
91 def check_for_battle(self):
92 """
93 Switch scene to battle 1/5 times if battles are allowed.
94 """
95 if self.level.allow_battles:
96 self.level.game_data['battle counter'] -= 5
97
98 if self.level.game_data['battle counter'] <= 0:
99 self.level.switch_to_battle = True
100
101
102