Create a gist now

Instantly share code, notes, and snippets.

@wkta /day_12.py
Last active Aug 29, 2015

What would you like to do?
#MonthOfCode day 12 - pixel
import pygame
from time import sleep
import random
import sys
BLACK = ( 0, 0, 0)
NB_PIX_BATCH = 64
DISP_WIDTH = 640
DISP_HEIGHT = 480
REFR_RATE = 0.008
class MovingPix():
def __init__(self , x,y):
self.x = float( x)
self.y = float( y)
#random color and speed
self.color= tuple( [random.randint(64,255) for i in xrange(3) ] )
self.x_speed = random.choice( (-1,1) ) * 256.0 * random.random()
self.y_speed = -1.0 * 380.0 * random.random()
self.disp_x, self.disp_y = int(self.x), int(self.y)
def isOut( self):
#we calculate the next pos
#is it out of bounds?
return( self.disp_y>=DISP_HEIGHT-1
or self.disp_x>=DISP_WIDTH-1
or self.disp_x<1
or self.disp_y<1 )
def move(self, delay):
self.x += (self.x_speed * delay)
self.y += (self.y_speed * delay)
self.y_speed += (700.0 * delay ) # simulates gravity
new_x, new_y = int(round(self.x)), int(round(self.y))
self.disp_x, self.disp_y = new_x, new_y
def display(self, window):
window.set_at((self.disp_x, self.disp_y), self.color)
window.set_at((self.disp_x-1, self.disp_y), self.color)
window.set_at((self.disp_x+1, self.disp_y), self.color)
window.set_at((self.disp_x, self.disp_y-1), self.color)
window.set_at((self.disp_x, self.disp_y+1), self.color)
window.set_at((self.disp_x-1, self.disp_y-1), self.color)
window.set_at((self.disp_x+1, self.disp_y-1), self.color)
window.set_at((self.disp_x-1, self.disp_y+1), self.color)
window.set_at((self.disp_x+1, self.disp_y+1), self.color)
def refreshScreen():
window.fill( BLACK )
for pix in pixel_list:
pix.display( window)
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) )
# diplays the state and then loops for input handling
pixel_list = list()
pix_to_gen = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
if event.type == pygame.MOUSEBUTTONDOWN :
m_pos = pygame.mouse.get_pos()
pix_to_gen = NB_PIX_BATCH
# adding and removing pixels from the list
for pix in pixel_list:
pix.move( REFR_RATE )
if( pix.isOut() ):
pixel_list.remove(pix )
if( pix_to_gen>0):
pixel_list.append( MovingPix( *m_pos) )
pix_to_gen-=1
# display
refreshScreen()
sleep( REFR_RATE )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment