Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#MonthOfCode day 22 - whirlpool
import pygame
from time import sleep
import random
import math
DISP_WIDTH = 640
DISP_HEIGHT = 480
DIST_THRESHOLD = 256
class MovingPix():
def __init__(self , x,y):
self.x = float(x)
self.y = float( y)
self.disp_x ,self.disp_y= x, y
self.color= tuple( [random.randint(64,255) for i in xrange(3) ] )
self.mass = random.random()*9
def moveTowardsHole( self, pos_hole ):
dest_x,dest_y = pos_hole
if(self.disp_x==dest_x and self.disp_y==dest_y):
return
colinear_vect = (dest_x-self.x, dest_y-self.y)
angle = math.pi/2
ortho_vect = ( math.cos(angle) * colinear_vect[0] - math.sin(angle)*colinear_vect[1],
math.cos(angle)*colinear_vect[1] + math.sin(angle)*colinear_vect[0] )
grav_factor = 8.0 / self.distance( pos_hole)
grav_factor /= self.mass
turn_factor = 0.5
turn_factor /= self.mass
self.x = self.x + (grav_factor)*colinear_vect[0] + turn_factor *ortho_vect[0]
self.y = self.y + (grav_factor)*colinear_vect[1] + turn_factor *ortho_vect[1]
self.disp_x , self.disp_y = int(round(self.x)), int(round(self.y))
def distance(self, targ_pos ):
return math.sqrt( (self.x - targ_pos[0])**2 + (self.y - targ_pos[1])**2 )
def refreshScreen():
window.fill( pygame.Color('black') )
for pix in l_pix:
window.set_at( (pix.disp_x, pix.disp_y), pix.color)
window.set_at( (pix.disp_x-1, pix.disp_y), pix.color)
window.set_at( (pix.disp_x+1, pix.disp_y), pix.color)
window.set_at( (pix.disp_x, pix.disp_y-1), pix.color)
window.set_at( (pix.disp_x, pix.disp_y+1), pix.color)
pygame.display.flip()
# init. pygame libr; create the screen and diplays a help message in the console
pygame.init()
window = pygame.display.set_mode( (DISP_WIDTH, DISP_HEIGHT) )
pygame.display.set_caption('press & hold a mouse button to clean pixels!')
l_pix = list()
for i in xrange( DISP_HEIGHT):
for j in xrange( DISP_WIDTH):
if random.choice( range(96) )==0 :
l_pix.append( MovingPix( j,i))
program_done = False ; sucking = False
refreshScreen()
while not program_done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
program_done = True
break
if event.type == pygame.MOUSEBUTTONDOWN :
sucking = True
if event.type == pygame.MOUSEBUTTONUP :
sucking = False
if sucking:
m_pos = pygame.mouse.get_pos()
for pix in l_pix:
if(pix.distance(m_pos)>DIST_THRESHOLD ):
continue
pix.moveTowardsHole( m_pos)
# display
refreshScreen()
sleep(0.02)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment