import sys from random import * from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from math import * iterations = 1 def generatePlant(iterations=3): rules = { 'X':'F-[[X]+X]+F[+FX]-X', 'F' : 'FF' } s = 'X' for i in range(iterations): s2 = '' for c in s: if rules.has_key(c): s2 += rules[c] else: s2 += c s = s2 return s.replace('X','') def drawPlant(s): stack = [] p = [0,0] angle = 0 for c in s: if c == 'F': if len(stack) < 5: glLineWidth(5.0-len(stack)) else: glLineWidth(1.0) glBegin(GL_LINES) glVertex2fv(p) p[0] += sin(angle) p[1] += cos(angle) glVertex2fv(p) glEnd() elif c == '-': angle -= radians(25) elif c == '+': angle += radians(25) elif c == '[': stack.append( (p[:],angle) ) elif c == ']': p,angle = stack.pop() def draw(): glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(-100,100,0,150) glMatrixMode(GL_MODELVIEW) glLoadIdentity() plant = generatePlant(iterations) print plant drawPlant(plant) glutSwapBuffers() def keyboard(key, x, y): global iterations if key == chr(27): sys.exit(0) elif key == '+': iterations += 1 elif key == '-': iterations -= 1 glutPostRedisplay() glutInit([]) glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE) glutInitWindowSize(800,600) glutCreateWindow(sys.argv[0]) glutDisplayFunc(draw) glutKeyboardFunc(keyboard) glutMainLoop()