ixxra

Triangulo de Sierpinski a la Logo

Feb 28th, 2013
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. import turtle
  2. import math
  3. import sys
  4.  
  5. COMPLEMENT=120
  6. FACTOR = math.sqrt(3)/2
  7.  
  8. class Carpet:
  9.   def __init__(self, x, y, side):
  10.     self.x = x
  11.     self.y = y
  12.     self.side = side
  13.     self.height = FACTOR*side
  14.    
  15.   def _children(self, x, y, side, height, step=0):
  16.     if step==0:
  17.       yield (x, y)
  18.    
  19.     else:
  20.       newSide = side/2
  21.       newHeight = height/2
  22.  
  23.       for f in self._children(x, y, newSide, newHeight, step - 1):
  24.         yield f
  25.       for f in self._children(x + newSide, y, newSide, newHeight, step - 1):
  26.         yield f
  27.       for f in self._children(x + newSide/2, y + newHeight, newSide, newHeight, step - 1):
  28.         yield f
  29.        
  30.   def children(self, step=0):
  31.     return self._children(self.x, self.y, self.side, self.height, step)
  32.  
  33.  
  34. def paintTriangle(t, x, y, size):
  35.     t.penup()
  36.     t.goto(x, y)
  37.     t.pendown()
  38.     t.fillcolor(0, 0, 0)
  39.     t.begin_fill()
  40.     t.forward(size)
  41.     t.left(COMPLEMENT)
  42.     t.forward(size)
  43.     t.left(COMPLEMENT)
  44.     t.forward(size)
  45.     t.end_fill()
  46.     t.left(COMPLEMENT)
  47.  
  48. if __name__ == '__main__':
  49.   try:
  50.     steps = int(sys.argv[1])
  51.   except IndexError:
  52.     steps = 3
  53.  
  54.   sw, sh = turtle.screensize()
  55.   size = 2*sh
  56.   tx = -sh
  57.   ty = -math.sqrt(3)/4*size
  58.  
  59.   t = turtle.Pen()
  60.   t.hideturtle()
  61.   t.speed('fastest')
  62.   carpet = Carpet(tx, ty, size)
  63.  
  64.   turtle.tracer(False)
  65.   triangles = 0
  66.   for x, y in carpet.children(steps):
  67.     paintTriangle(t, x, y, size/2**steps)
  68.     triangles += 1
  69.     turtle.title('Number of triangles: ' + str(triangles))
  70.     turtle.update()
  71.    
  72.   turtle.title("Sierpinski's triangle <" + str(triangles) + " triangles>")
  73.   turtle.exitonclick()
Advertisement
Add Comment
Please, Sign In to add comment