Advertisement
Guest User

mondrian.py

a guest
Aug 27th, 2010
706
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import random
  2. import sys
  3.  
  4. import pygame
  5.  
  6. pygame.init()
  7.  
  8. class MondrianNode(object):
  9.     def __init__(self):
  10.         self.children = []
  11.         self.subdivide_point = 0.0
  12.         self.subdivide_direction = "horizontal"
  13.         self.colour = pygame.Color(255, 0, 0)
  14.  
  15.     def generate(self, chance_of_end = 0.0, max_levels = 10.0):
  16.         self.colour.r = random.randint(0, 255)
  17.         self.colour.g = random.randint(0, 255)
  18.         self.colour.b = random.randint(0, 255)
  19.         if random.random() > chance_of_end:   #Decide whether to stop subdividing
  20.             self.subdivide_direction = random.choice(["horizontal", "vertical"])
  21.             self.subdivide_point = random.uniform(0.1, 0.9)
  22.             self.children = [MondrianNode(), MondrianNode()]
  23.             new_chance_of_end = chance_of_end + 1.0/max_levels
  24.             for child in self.children:
  25.                 child.generate(new_chance_of_end, max_levels)
  26.  
  27.  
  28.     def draw(self, surface, width, height, xpos, ypos):
  29.         rect = pygame.Rect(xpos, ypos, width, height)
  30.         surface.fill(self.colour, rect)
  31.         pygame.draw.rect(surface, (0, 0, 0), rect, 3)
  32.        
  33.         if self.children:
  34.             if self.subdivide_direction == "horizontal":
  35.                 self.children[0].draw(surface, width * self.subdivide_point, height, xpos, ypos)
  36.                 self.children[1].draw(surface, width * (1.0 - self.subdivide_point), height, xpos + width * self.subdivide_point, ypos)
  37.             else:
  38.                 self.children[0].draw(surface, width, height * self.subdivide_point, xpos, ypos)
  39.                 self.children[1].draw(surface, width, height * (1.0 - self.subdivide_point), xpos, ypos + height * self.subdivide_point)
  40.  
  41.  
  42. def main():
  43.     tree = MondrianNode()
  44.     tree.generate()
  45.     screen = pygame.display.set_mode((1024, 768))
  46.     while True:
  47.         for event in pygame.event.get():
  48.             if event.type == pygame.QUIT: sys.exit()
  49.         tree.draw(screen, 1024, 768, 0, 0)
  50.         pygame.display.flip()
  51.        
  52.  
  53.  
  54. if __name__ == "__main__":
  55.     main()
Advertisement
RAW Paste Data Copied
Advertisement