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