#!/usr/bin/python
import time, random
import pygame
import pygame.camera
from pygame.locals import *

pygame.init()

class VideoCapturePlayer(object):
   size = ( 320, 240 )
   def __init__(self, **argd):
       self.__dict__.update(**argd)
       super(VideoCapturePlayer, self).__init__(**argd)
       self.display = pygame.display.set_mode( self.size )
       self.camera = pygame.camera.Camera("/dev/video0", self.size, "RGB")
       self.camera.start()
       self.camera.set_controls(True, False)
       self.clock = pygame.time.Clock()
       self.snapshot = pygame.surface.Surface(self.size, 0, 24)
       self.background = pygame.surface.Surface(self.size, 0, 24)
       self.thresh = pygame.surface.Surface(self.size, 0, 24)
       self.bubble = pygame.surface.Surface((50,50), 0, 16)
       self.bubble.set_colorkey((0,0,0))
       self.bubble.fill((0,0,0))
       pygame.draw.circle(self.bubble,(0,0,255), (25,25), 25, 0)
       self.bmask = pygame.mask.from_surface(self.bubble)
       self.thresh.set_colorkey((255,0,0))
       self.coord = (160,120)
       random.seed()

      
   def calibrate(self):
       self.background = self.camera.get_image(self.background)
       self.display.blit(self.background, (0,0))
       pygame.display.flip()

   def get_and_flip(self):
       self.snapshot = self.camera.get_image(self.snapshot)
       pygame.transform.threshold(self.thresh, self.snapshot, (255,0,0), (50,50,50), (255,0,0), True, self.background)
       mask = pygame.mask.from_surface(self.thresh)
       mask.invert() 
       self.display.fill((50,255,128))
       self.display.blit(self.thresh, (0,0))
       self.display.blit(self.bubble, self.coord)
       overlap = mask.overlap_area(self.bmask, self.coord)
    
       if overlap:
           pygame.draw.circle(self.display,(200,200,255),mask.overlap(self.bmask, self.coord), overlap/5, 0)
           while mask.overlap_area(self.bmask, self.coord):
               self.coord = (random.randint(0,270), random.randint(0,190))
       pygame.display.flip()

   def main(self):
       going = True
       while going:
           events = pygame.event.get()
           for e in events:
               if e.type == KEYDOWN:
                   pygame.time.wait(2000)
                   self.calibrate()
                   going = False
           self.calibrate()
       going = True
       while going:
           events = pygame.event.get()
           for e in events:
               if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
                   going = False

           self.get_and_flip()
           self.clock.tick()
#           print self.clock.get_fps()

VideoCapturePlayer().main()
