all repos — Legends-RPG @ 107d1b4f334c643b35bd44f6d8865a9e9a42e3b7

A fantasy mini-RPG built with Python and Pygame.

data/collision.py (view raw)

 1__author__ = 'justinarmstrong'
 2import pygame as pg
 3
 4class CollisionHandler(object):
 5    """Handles collisions between the user, blockers and computer
 6    characters"""
 7    def __init__(self, player, blockers, sprites):
 8        self.player = player
 9        self.blockers = self.make_blocker_list(blockers, sprites)
10        self.sprites = sprites
11        self.collided = False
12
13
14    def make_blocker_list(self, blockers, sprites):
15        """Return a combined list of sprite blockers and object blockers"""
16        for sprite in sprites:
17            blockers.extend(sprite.blockers)
18
19        return blockers
20
21    def update(self):
22        """Checks for collisions between game objects"""
23        self.update_blockers()
24        self.player.rect.x += self.player.x_vel
25        self.player.rect.y += self.player.y_vel
26        self.check_for_blockers()
27
28        self.update_blockers()
29        for sprite in self.sprites:
30            sprite.rect.x += sprite.x_vel
31            sprite.rect.y += sprite.y_vel
32        self.check_for_blockers()
33
34        if self.player.rect.x % 32 == 0 and self.player.rect.y % 32 == 0:
35            self.player.begin_resting()
36
37
38    def update_blockers(self):
39        """Update blockers list"""
40
41
42
43    def check_for_blockers(self):
44        """Checks for collisions with blocker rects"""
45        for blocker in self.blockers:
46            if self.player.rect.colliderect(blocker):
47                self.collided = True
48
49        if self.collided:
50            self.reset_after_collision()
51            self.collided = False
52            self.player.begin_resting()
53
54
55    def reset_after_collision(self):
56        """Put player back to original position"""
57        if self.player.x_vel != 0:
58                self.player.rect.x -= self.player.x_vel
59        else:
60            self.player.rect.y -= self.player.y_vel
61
62
63