[pyopengl][Reproduced] Draw a rotating cube combined with pygame

#---Export module---
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
  
#---initialize pygame and define window size---
pygame.init()
#OPENGL| DOUBLEBUF=DOUBLEBUF|OPENGL
#DOUBLEBUF: Double buffer mode (recommended to be used with HWSURFACE or OPENGL) #Create
an OPENGL rendered display
pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF)
  
#---Tuple definition-- -
#Define the xyz coordinate points of the cube
CUBE_POINTS = ((0.5, -0.5, -0.5), (0.5, 0.5, -0.5), (-0.5, 0.5, -0.5), (-0.5, -0.5, -0.5) ,(0.5, -0.5, 0.5), (0.5, 0.5, 0.5),(-0.5, -0.5, 0.5), (-0.5, 0.5, 0.5)) #define
RGB colors
CUBE_COLORS = ((1, 0, 0 ), (1, 1, 0), (0, 1, 0), (0, 0, 0), (1, 0, 1), (1, 1, 1), (0, 0, 1), (0, 1, 1))
# Define a surface, four points form a surface
CUBE_QUAD_VERTS = ((0, 1, 2, 3), (3, 2, 7, 6), (6, 7, 5, 4), (4, 5, 1, 0), (1, 5, 7, 2), (4, 0, 3, 6))
# Define the line, two points form a line
CUBE_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 the cube drawing function---
def drawcube():
    # "Draw a cube", zip and list methods
    allpoints = list(zip(CUBE_POINTS, CUBE_COLORS)) #Draw
     
    area---start---end---
    glBegin(GL_QUADS)
    for face in CUBE_QUAD_VERTS:
        for vert in face:
            pos, color = allpoints[vert] #under
            the second for
            glColor3fv(color)
            glVertex3fv(pos) #align
    with the first for
    glEnd()
  
    #edge color Black
    glColor3f(0, 0, 0)
  
    # Draw a line---start---end---
    glBegin(GL_LINES)
    for line in CUBE_EDGES:
        for vert in line:
            pos, color = allpoints[vert]
            glVertex3fv(pos)
    glEnd()
  
#---Main function- -
def main():
    glEnable(GL_DEPTH_TEST)     #Initialize the
    camera
glMatrixMode(GL_PROJECTION)
    gluPerspective(45.0,640/480.0,0.1,100.0)
    glTranslatef(0.0, 0.0, -3.0)
    glRotatef(25, 1, 0, 0)
    # Start the loop ---
    while True:         #event
        detection
event = pygame.event.poll() #Define the
        exit mechanism. In the while loop of pygame, this step must be set
        if event.type == QUIT or (event.type = = KEYDOWN and event.key == K_ESCAPE):
            break         #Clear the
        screen
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) #Camera
        rotation
        glRotatef(1,0,1,0)
        drawcube() #Refresh the
        screen
        pygame.display.flip()
  
if __name__ =='__main__':
main()

The results show that:

 

Guess you like

Origin blog.csdn.net/FL1623863129/article/details/113995593