Pygame 和 PyOpenGL:屏幕上没有显示任何形状

Pygame and PyOpenGL: No shapes appear on screen

我之前使用 C++ 和 OpenGL 创建了一个完整的蛇游戏,我想使用 Python、pygame 和 PyOpenGL 来做同样的事情。我目前遇到的问题是,在我生成水果后,它没有出现在屏幕上。这是我的主要功能的代码:

def main():     # Main function
    # Initialize game components
    game = Game(800, 600)
    test_fruit = game.spawn_fruit(Point(100, 100))

    # Initialize pygame module
    pygame.init()
    pygame.display.set_mode(game.get_window_size(), DOUBLEBUF | OPENGL)
    pygame.display.set_caption("Python Game")

    # Define variable to control main loop
    running = True

    # Main loop
    while running:
        # event handling, gets all event from the event queue
        for event in pygame.event.get():
            # only do something if the event is of type QUIT
            if event.type == pygame.QUIT:
                # change the value to False, to exit the main loop
                running = False

        # Modify game properties
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        game.draw_shapes()
        pygame.display.flip()
        pygame.time.wait(5)

我可能缺少 pygame 或 pyopengl 函数,但我不确定。我也试过将 pygame.display.flip() 更改为 pygame.display.update(),但它给了我一个错误(“无法更新 OpenGL 显示”)。

这是我要显示的形状的代码:

class Circle:
    def __init__(self, pivot: Point, radius: int, sides: int, fill: bool, color: Color):
        self.pivot = pivot
        self.radius = radius
        self.sides = sides
        self.fill = fill
        self.color = color

    # Draw the shape of the circle
    def draw(self):
        glColor3f(self.color.r, self.color.g, self.color.b)
        if self.fill:
            glBegin(GL_POLYGON)
        else:
            glBegin(GL_LINE_LOOP)
        for i in range(100):
            cosine = self.radius * cos(i*2*pi/self.sides) + self.pivot.x
            sine = self.radius * sin(i*2*pi/self.sides) + self.pivot.y
            glVertex2f(cosine, sine)
        glEnd()

OpenGL 坐标在 [-1.0, 1.0] 范围内(标准化设备 Space)。 Normalized device space 是从左下近(-1, -1, -1)到右上远(1, 1, 1)的唯一立方体。
如果要使用“window”坐标,则必须指定一个Orthographic projection using glOrtho:

glOrtho(0, 800, 600, 0, -1, 1)

glMatrixMode and load the Identity matrix with glLoadIdentity选择矩阵模式。

示例:

def main():     # Main function
    # Initialize game components
    game = Game(800, 600)
    test_fruit = game.spawn_fruit(Point(100, 100))

    # Initialize pygame module
    pygame.init()
    pygame.display.set_mode(game.get_window_size(), DOUBLEBUF | OPENGL)
    pygame.display.set_caption("Python Game")

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0, 800, 600, 0, -1, 1)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity() 

    # Define variable to control main loop
    running = True

    # [...]