由于代码缺少 Pygame 的事件循环,因此在运行时会出现错误。为了解决这个问题,需要在代码中添加一个事件循环以监听和处理 Pygame 的事件。

以下是修正后的代码:

import pygame
import sys

# 初始化 Pygame
pygame.init()

# 设置窗口大小和标题
screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('可操作的立方体')

# 定义立方体的顶点坐标
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)
]

# 定义立方体的面
faces = [
    (0, 1, 2, 3),   # 前面
    (1, 5, 6, 2),   # 右面
    (5, 4, 7, 6),   # 后面
    (4, 0, 3, 7),   # 左面
    (4, 5, 1, 0),   # 上面
    (3, 2, 6, 7)    # 下面
]

# 定义立方体的初始位置、大小和旋转角度
cube_position = pygame.math.Vector3(0, 0, 0)
cube_scale = 100
cube_rotation = pygame.math.Vector3(0, 0, 0)

# 定义相机的初始位置和旋转角度
camera_position = pygame.math.Vector3(0, 0, -1000)
camera_rotation = pygame.math.Vector3(0, 0, 0)

# 定义移动和旋转的速度
movement_speed = 5
rotation_speed = 0.03

# 渲染立方体
def render_cube():
    for face in faces:
        vertex_list = []
        for index in face:
            vertex = vertices[index]
            # 缩放
            scaled_vertex = pygame.math.Vector3(vertex) * cube_scale
            # 旋转
            rotated_vertex = scaled_vertex.rotate(cube_rotation)
            # 平移
            translated_vertex = rotated_vertex + cube_position
            vertex_list.append(translated_vertex)

        pygame.draw.polygon(screen, (255, 255, 255), vertex_list)

# 主循环
while True:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # 获取键盘输入
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:  # 前移
        cube_position += pygame.math.Vector3(0, 0, movement_speed)
    if keys[pygame.K_s]:  # 后移
        cube_position += pygame.math.Vector3(0, 0, -movement_speed)
    if keys[pygame.K_a]:  # 左移
        cube_position += pygame.math.Vector3(-movement_speed, 0, 0)
    if keys[pygame.K_d]:  # 右移
        cube_position += pygame.math.Vector3(movement_speed, 0, 0)
    if keys[pygame.K_q]:  # 上移
        cube_position += pygame.math.Vector3(0, movement_speed, 0)
    if keys[pygame.K_e]:  # 下移
        cube_position += pygame.math.Vector3(0, -movement_speed, 0)
    if keys[pygame.K_LEFT]:  # 左旋转
        cube_rotation += pygame.math.Vector3(0, -rotation_speed, 0)
    if keys[pygame.K_RIGHT]:  # 右旋转
        cube_rotation += pygame.math.Vector3(0, rotation_speed, 0)
    if keys[pygame.K_UP]:  # 上旋转
        cube_rotation += pygame.math.Vector3(-rotation_speed, 0, 0)
    if keys[pygame.K_DOWN]:  # 下旋转
        cube_rotation += pygame.math.Vector3(rotation_speed, 0, 0)

    # 清屏
    screen.fill((0, 0, 0))

    # 渲染立方体
    render_cube()

    # 更新屏幕显示
    pygame.display.flip()

这样修改后的代码将添加一个事件循环,以监听并处理 Pygame 的事件。请注意,为了能够正常退出程序,我们在事件循环中捕获了 QUIT 事件并调用 pygame.quit()sys.exit() 来退出程序。

希望这次的修改能够解决您提到的错误。如果您还有其他问题,请随时提问。

Pygame 代码错误:缺少事件循环 - 如何修复

原文地址: https://www.cveoy.top/t/topic/TDg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录