# Example for in-class assignment - bounce a triangle import sys, random, time, math from OpenGL.GLUT import * from OpenGL.GL import * from OpenGL.GLU import * class Triangle: def __init__(self): self.startTime = time.time() self.x = random.uniform(-1,1) self.y = -1 self.rgb = [random.uniform(0,1), random.uniform(0,1), random.uniform(0,1)] def update(self, t): self.y = abs(math.sin(t - self.startTime)) * 2 - 1 def draw(self): glColor3fv(self.rgb) glBegin(GL_TRIANGLES) glVertex2f(self.x-0.1, self.y-0.1) glVertex2f(self.x+0.1, self.y-0.1) glVertex2f(self.x, self.y+0.1) glEnd() triangles = [Triangle()] def draw(): glClearColor(0,0,0,0) glClear(GL_COLOR_BUFFER_BIT) for t in triangles: t.draw() glutSwapBuffers() def keyboard(key, x, y): if key == chr(27): sys.exit(0) elif key == ' ': triangles.append(Triangle()) def update(v): glutTimerFunc(16, update, 0) currentTime = time.time() for t in triangles: t.update(currentTime) glutPostRedisplay() glutInit([]) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB) glutInitWindowSize(500, 500) glutInitWindowPosition(0,0) glutCreateWindow(sys.argv[0]) glutDisplayFunc(draw) glutKeyboardFunc(keyboard) glutTimerFunc(0, update, 0) glutMainLoop()