# A fancier solution to Assignment 1. # This program saves all the triangles that it draws in # a list, so that it can redraw them whenever the window # is resized or exposed. # # Dave Pape # 27 September 2003 import sys from random import * from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * # 'triangles' is to be a list of triangle data; # each triangle's data will be a dictionary; # e.g. after 1 triangle has been added, it will look something like: # [ { "color":[1,0,0] , "points":[ [0, 0], [0.5, 0.1], [-0.7, 0.4] ] } ] triangles = [ ] def draw(): global triangles glClear(GL_COLOR_BUFFER_BIT) glBegin(GL_TRIANGLES) for t in triangles: glColor3fv(t["color"]) for p in t["points"]: glVertex2fv(p) glEnd() glFlush() def keyboard(key, x, y): global triangles, values if key == chr(27): sys.exit(0) elif key == ' ': color = [ random(), random(), random() ] points = [ ] for i in range(0,3): points.append([random()*2-1, random()*2-1]) tri = { "color":color, "points":points } triangles.append(tri) elif key == 'c': triangles = [ ] elif key == 'n': print len(triangles), "triangles" for t in triangles: print t glutPostRedisplay() print "Press space bar to add a triangle" print "Press 'c' key to clear all triangles" glutInit([]) glutCreateWindow("triangles") glutDisplayFunc(draw) glutKeyboardFunc(keyboard) glutMainLoop()