Search code examples
pythonpygamepyopengl

I want to make a cube using OpenGL and pygame in python


I want to make a cube using OpenGL and pygame but it gives an error.

here is the code:

import pygame
from pygame.locals import *
from OpenGL import *
from OpenGL.GLU import *

verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (1, -1, 1),
    (1, 1, 1),
    (-1, -1, 1),
    (-1, 1, 1),
    )

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),
)


def Cube():
    glBegin(GL_LINES)
    for edge in edges:
        for index in edge:
            glVertex3fv(vertices[index])
    glEnd()
    glEnd()
def main():
    pygame.init()
    display = (800,600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
    gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
    glTranslatef(0.0,0.0, -5)
    glRotatef(0,0,0,0)
    
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
    Cube()
    pygame.display.flip()
    pygame.time.wait(10)
main()   

here is the error:

   error                                     Traceback (most recent call last)
   Input In [3], in <cell line: 50>()
        47     glRotatef(0,0,0,0)
        49 while True:
   ---> 50     for event in pygame.event.get():
        51         if event.type == pygame.QUIT:
        52             pygame.quit()
   
   error: video system not initialized

actually the output is a empty cube that rotates and it's made by vertices and edges. but the codes error is error: video system not initialized and I think that the error is from the frame or the video.


Solution

  • It is a matter of Indentation. The application loop needs to be run in main after pygame.display.set_mode:

    def main():
        pygame.init()
        display = (800,600)
        pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
        gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
        glTranslatef(0.0,0.0, -5)
        glRotatef(0,0,0,0)
        
        # INDENTATION
    #-->|
    
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                
            glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
            Cube()
            pygame.display.flip()
            pygame.time.wait(10)
    
    main()