Skip to content

Instantly share code, notes, and snippets.

@wkta
Created March 28, 2014 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wkta/9836062 to your computer and use it in GitHub Desktop.
Save wkta/9836062 to your computer and use it in GitHub Desktop.
#MonthOfCode day 19 - tree
# this program draws a random TREE-LIKE shape, inspired by L-Systems
import pygame
from time import sleep
import random
import sys
DISP_WIDTH = 640
DISP_HEIGHT = 480
def randPeriod():
return random.choice((1, 16, 64) ) #determines the slope with wich the emerging branch grows
class MovingPix():
def __init__(self , x,y, vert_grow=None, period=None ):
self.x = x
self.y = y
self.vert_grow = random.choice((True,False)) if vert_grow==None else vert_grow
self.period =randPeriod() if period==None else period
def isOut( self):
#is it out of bounds?
return( self.y>=DISP_HEIGHT
or self.x>=DISP_WIDTH
or self.x<0
or self.y<0 )
def simulateGrowth(self, i ):
res = [ self.x, self.y ]
if self.vert_grow:
res[1]+=1
if i%self.period==0:
res[0]+=1
else:
res[0]+=1
if i%self.period==0:
res[1]+=1
return MovingPix( res[0], res[1], self.vert_grow, self.period)
def letGrowthDirMutate(self):
if( random.randint(1,8)==8):
self.period = randPeriod()
def display(self, window):
window.set_at( (self.x, self.y), pygame.Color('BLACK') )
def refreshScreen():
window.fill( pygame.Color('WHITE') )
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()
growing_pix = list()
tmp_pix = MovingPix(10,10)
pixel_list.append( tmp_pix)
growing_pix.append( tmp_pix)
counter=0
branch_proba_adjuster = 2
drawing =True
while True:
# in case the user wants to abord
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
if not drawing:
continue
# simulating growth
n_growing_pix = list()
for gpix in growing_pix:
tmp_pix = gpix.simulateGrowth( counter )
if( gpix.isOut() ):
continue
pixel_list.append( tmp_pix)
n_growing_pix.append( tmp_pix )
tmp_pix.letGrowthDirMutate()
#branching possibility
if( random.randint(1,4+branch_proba_adjuster)==4+branch_proba_adjuster ): #the more branches, the smaller the probability to branch
branch_proba_adjuster=branch_proba_adjuster+(4*4)
branched_pix =MovingPix(tmp_pix.x, tmp_pix.y,not tmp_pix.vert_grow)
pixel_list.append( branched_pix)
n_growing_pix.append( branched_pix)
growing_pix = n_growing_pix
counter+=1
# drawing-halt condition
if( 0==len(growing_pix )):
drawing=False
print "drawing done."
# display + delay
refreshScreen()
sleep(0.001)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment