Advertisement
Guest User

mondrian.py

a guest
Aug 27th, 2010
401
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.2, 0.8)
  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.         if width < 100 or height < 100:
  30.             return
  31.         rect = pygame.Rect(xpos, ypos, width, height)
  32.         surface.fill(self.colour, rect)
  33.         pygame.draw.rect(surface, (0, 0, 0), rect, 3)
  34.        
  35.         if self.children:
  36.             if self.subdivide_direction == "horizontal":
  37.                 self.children[0].draw(surface, width * self.subdivide_point, height, xpos, ypos)
  38.                 self.children[1].draw(surface, width * (1.0 - self.subdivide_point), height, xpos + width * self.subdivide_point, ypos)
  39.             else:
  40.                 self.children[0].draw(surface, width, height * self.subdivide_point, xpos, ypos)
  41.                 self.children[1].draw(surface, width, height * (1.0 - self.subdivide_point), xpos, ypos + height * self.subdivide_point)
  42.  
  43.  
  44. def main():
  45.     tree = MondrianNode()
  46.     tree.generate()
  47.     screen = pygame.display.set_mode((1024, 768))
  48.     while True:
  49.         for event in pygame.event.get():
  50.             if event.type == pygame.QUIT: sys.exit()
  51.         tree.draw(screen, 1024, 768, 0, 0)
  52.         pygame.display.flip()
  53.        
  54.  
  55.  
  56. if __name__ == "__main__":
  57.     main()
Advertisement
RAW Paste Data Copied
Advertisement