Search code examples
pythonopenglpygamepyopengl

Drawing a cube with Pygame and OpenGL in Python environment


I got this code to draw an OpenGL cube in a pygame window with python but every time i try to compile it says this line 34, in Cube glVertex3f(vertices[vertex]) TypeError: tuple indices must be integers or slices, not tuple Anyone who knows how to correct code so that i can make the program achieve its intended function.

import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
##Define the vertices. usually a cube contains 8 vertices
vertices=( (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (1, -1, 1),
    (1, 1, 1),
    (-1, -1, 1),
    (-1, 1, 1))
##define 12 edges for the body
edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )
##define function to draw the cube
def Cube():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in vertices:
            glVertex3f(vertices[vertex])
    glEnd
##Define main function to draw a window for the openGL
def main():
    pygame.init()
    display=(600,600)
    pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
    gluPerspective(45, (display[0] / display[1]), 0.1, 50.0)
    glTranslatef(0.0, 0.0, -5)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        glRotatef(1, 3, 1, 1)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        Cube()
        pygame.display.flip()
        pygame.time.wait(10)


main()

What could i be doing wrong please help..


Solution

  • vertex is a 3-component tuple, so it cannot be used for subscriptions. glVertex3f expects 3 arguments. Therefore you either have to unzip the tuple or use the OpenGL instruction glVertex3fv instead of glVertex3f (see glVertex):

    glVertex3f(vertices[vertex])

    glVertex3fv(vertex)
    

    or

    glVertex3f(*vertex)
    

    Furthermore, the parentheses after glEnd are missing:

    glEnd

    glEnd()
    

    But if you want to draw a wireframe cube, you need to draw line segments for each edge of the cube:

    def Cube():
        glBegin(GL_LINES)
        for edge in edges:
            for index in edge:
                glVertex3fv(vertices[index])
        glEnd()