#coding: utf-8

import pygame

class Pilota(pygame.sprite.Sprite):
    
    def __init__(self, image, pos, vel):
        super(Pilota, self).__init__()
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.center = pos
        self.dir = [-1, -1]
        self.vel = vel

    def update(self, ample, alt, maons, raqueta):
        despl = self.vel[0]*self.dir[0], self.vel[1]*self.dir[1]
        antic_rect = self.rect
        self.rect = self.rect.move(despl)
        lr = pygame.sprite.spritecollide(self, [raqueta], dokill=False)
        lm = pygame.sprite.spritecollide(self, maons, dokill=True)
        for elem in lm+lr:
            self.actualitza_xoc_bloc(elem.rect, antic_rect)
        self.actualitza_xoc_parets(ample, alt)

    def actualitza_xoc_parets(self, ample, alt):
        if self.rect.left < 0:
            self.dir[0] = 1
        elif self.rect.right >= ample:
            self.dir[0] = -1
        if self.rect.top < 0:
            self.dir[1] = 1
        elif self.rect.bottom >= alt:
            self.dir[1] = -1

    def actualitza_xoc_bloc(self, r_bloc, r_antic):
        """
        Sabem que la pilota acaba de xocar amb un bloc.
        Donat el rectangle d'un bloc, i el rectangle de la pilota just
        abans de topar, actualitza la direcció en què ha d'anar la
        pilota després de xocar.
        """
        if r_antic.bottom <= r_bloc.top :
            self.dir[1] = -1
        if r_antic.top >= r_bloc.bottom :
            self.dir[1] = 1
        if r_antic.left >= r_bloc.right :
            self.dir[0] = 1
        if r_antic.right <= r_bloc.left :
            self.dir[0] = -1

