Circle Game in PyGame - POP the Bubbles

How to write a Python Program to Circle Game in PyGame - POP the Bubbles ?


Solution:

#!/usr/bin/env python
#Created by Kris Occhipinti
#http://FilmsByKris.com December 29th 2010
#GPLv3 - http://www.gnu.org/licenses/gpl-3.0.html

import pygame, sys, random          #load pygame module
from pygame.locals import *

w = 800                 #set width of screen
h = 600                 #set height

miss = 0

screen = pygame.display.set_mode((w, h)) #make screen

pygame.display.flip()


class Ball:
   def __init__(self, radius, speed, x, y, color, size):
       if speed == 0:
          speed=2
       self.d = 15
       self.y=y
       self.x=x
       self.size=size
       #speed
       self.yy=speed
       self.xx=speed
       self.radius=radius
       self.color=color
       pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius )


   def cir_mov(self):
       global h, w
       self.d-=1
       self.x+=self.xx
       self.y+=self.yy
       if self.x > w - self.radius:
          self.xx = self.xx*-1
       elif self.x < 0 + self.radius:
          self.xx = self.xx*-1
       elif self.y > h - self.radius:
          self.yy = self.yy*-1
       elif self.y < 0 + self.radius:
          self.yy = self.yy*-1
       pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius )

   def cir_click(self, x, y):
       global miss
       if self.d < 0:
           if x > self.x - self.radius and x < self.x + self.radius:
               if y > self.y - self.radius and y < self.y + self.radius:
                   miss = 1
                   ball.remove(self)
                   if self.size == "L":
                       ball.append(Ball(25, 2, self.x, self.y, (random.randint(1,255),random.randint(1,255),random.randint(1,255)), "S"))
                       ball.append(Ball(25, -2, self.x, self.y, (random.randint(1,255),random.randint(1,255),random.randint(1,255)), "S"))
                 
clock = pygame.time.Clock()
ball = []
ball.append(Ball(50, random.randint(-3,3), 250, 250, (random.randint(1,255),random.randint(1,255),random.randint(1,255)),"L"))
ball.append(Ball(50, random.randint(-3,3), 150, 150, (random.randint(1,255),random.randint(1,255),random.randint(1,255)),"L"))


while 1:
   clock.tick(60)
   for event in pygame.event.get():
       if event.type == pygame.QUIT:
           sys.exit()
       elif event.type == MOUSEBUTTONDOWN:
           print "click"
           x,y = pygame.mouse.get_pos()
           for i in ball:
               i.cir_click(x,y)
       elif event.type == MOUSEBUTTONUP:
           if miss == 0:
               ball.append(Ball(50, random.randint(-3,3), x, y, (random.randint(1,255),random.randint(1,255),random.randint(1,255)),"L"))
           miss = 0

   screen.fill((0,0,0))
   for i in ball:
       i.cir_mov()

   pygame.display.flip()


Learn More :