PRÁCTICA: TANGRAM 2D
Se mueve con las flechas del teclado, se selecciona la figura del 1 al 7
CÓDIGO:
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
ShapeID = 0
jump = 0.1
positions = {
1: [0.0, 0.0], 2: [0.0, 0.0], 3: [0.25, 0.25],
4: [0.0, 0.0], 5: [0.0, 0.0], 6: [-0.25, -0.25], 7: [0.5, 0.0]
}
def BlueTriangle():
inc = 0.5
glColor3f(0.0, 1.0, 1.0)
glBegin(GL_TRIANGLES)
glVertex2f(0.0, 0.0)
glVertex2f(-inc, inc)
glVertex2f(inc, inc)
glEnd()
def RedTriangle():
inc = 0.5
glColor3f(1.0, 0.0, 0.0)
glBegin(GL_TRIANGLES)
glVertex2f(0.0, 0.0)
glVertex2f(-inc, -inc)
glVertex2f(-inc, inc)
glEnd()
def GreenTriangle():
inc = 0.25
glColor3f(0.0, 1.0, 0.0)
glBegin(GL_TRIANGLES)
glVertex2f(0.0, 0.0)
glVertex2f(inc, inc)
glVertex2f(inc, -inc)
glEnd()
def YellowSquare():
inc = 0.25
glColor3f(1.0, 1.0, 0.0)
glBegin(GL_QUADS)
glVertex2f(0.0, 0.0)
glVertex2f(inc, inc)
glVertex2f(2.0 * inc, 0.0)
glVertex2f(inc, -inc)
glEnd()
def PinkTriangle():
inc = 0.25
glColor3f(1.0, 0.0, 0.5)
glBegin(GL_TRIANGLES)
glVertex2f(0.0, 0.0)
glVertex2f(inc, -inc)
glVertex2f(-inc, -inc)
glEnd()
def WhiteRhomboid():
inc = 0.25
glColor3f(1.0, 1.0, 1.0)
glBegin(GL_QUADS)
glVertex2f(0.0, 0.0)
glVertex2f(2.0 * inc, 0.0)
glVertex2f(inc, -inc)
glVertex2f(-inc, -inc)
glEnd()
def NavyTriangle():
inc = 0.5
glColor3f(0.3, 0.6, 1.0)
glBegin(GL_TRIANGLES)
glVertex2f(0.0, 0.0)
glVertex2f(0.0, -inc)
glVertex2f(-inc, -inc)
glEnd()
def DrawShape(shape_id):
if shape_id == 1:
BlueTriangle()
elif shape_id == 2:
RedTriangle()
elif shape_id == 3:
GreenTriangle()
elif shape_id == 4:
YellowSquare()
elif shape_id == 5:
PinkTriangle()
elif shape_id == 6:
WhiteRhomboid()
elif shape_id == 7:
NavyTriangle()
def DrawScene():
glClear(GL_COLOR_BUFFER_BIT)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
for shape_id, (x, y) in positions.items():
glPushMatrix()
glTranslatef(x, y, 0.0)
DrawShape(shape_id)
glPopMatrix()
glutSwapBuffers()
def handle_key(key, x, y):
global ShapeID
if isinstance(key, bytes):
key = key.decode("utf-8")
if key.isdigit():
ShapeID = int(key)
glutPostRedisplay()
def handle_special_key(key, x, y):
global ShapeID
if ShapeID in positions:
x_pos, y_pos = positions[ShapeID]
if key == GLUT_KEY_UP:
y_pos += jump
elif key == GLUT_KEY_DOWN:
y_pos -= jump
elif key == GLUT_KEY_RIGHT:
x_pos += jump
elif key == GLUT_KEY_LEFT:
x_pos -= jump
positions[ShapeID] = [x_pos, y_pos]
glutPostRedisplay()
def init():
glClearColor(0.0, 0.0, 0.0, 1.0)
gluOrtho2D(-2, 2, -1.5, 1.5)
def main():
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
glutInitWindowSize(800, 600)
glutCreateWindow(b"Tangram 2D")
init()
glutDisplayFunc(DrawScene)
glutKeyboardFunc(handle_key)
glutSpecialFunc(handle_special_key)
glutMainLoop()
if __name__ == "__main__":
main()