You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pygame中修改整个区块的颜色以实现迷宫绘制功能?

代码问题及修复方案

存在的问题

  • 代码内有4个未定义的变量:block_sizex、block_sizey、wall_width、wall_height,运行会直接抛出变量未定义错误
  • 绘制逻辑冗余,四重循环完全没必要,外层遍历屏幕坐标、内层重复遍历迷宫单元格,会导致大量重复绘制,逻辑混乱
  • 迷宫尺寸和屏幕尺寸没有做适配,绘制位置计算错误
  • 清屏操作只在初始化阶段执行一次,后续绘制会留下大量画面残留

修复后可直接运行的代码

import pygame
import numpy as np

pygame.init()
running = True


def exit_game():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

white = (255, 255, 255)
grey3 = (64, 64, 64)
bgcolour = white
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Maze")

# 7行7列的迷宫数据
maze = np.asarray([
          [0, 0, 1, 1, 1, 1, 1],
          [0, 0, 1, 1, 1, 1, 1],
          [1, 0, 1, 0, 0, 0, 1],
          [1, 0, 0, 0, 0, 0, 1],
          [1, 1, 0, 0, 1, 0, 1],
          [1, 1, 1, 0, 1, 0, 1],
          [1, 1, 1, 1, 1, 0, 1]])

# 根据迷宫行列数自动计算每个单元格的绘制尺寸,适配屏幕
block_sizex = screen_width // maze.shape[1]
block_sizey = screen_height // maze.shape[0]

def draw_rect():
    # 仅遍历迷宫单元格即可完成绘制
    for y0 in range(maze.shape[0]):
        for x0 in range(maze.shape[1]):
            if maze[y0][x0] == 1:
                # 计算当前单元格对应的屏幕坐标
                x1 = x0 * block_sizex
                y1 = y0 * block_sizey
                # 尺寸减1留出缝隙,方便看清格子边界,不需要可删掉-1即可取消缝隙
                rect = pygame.Rect(x1, y1, block_sizex - 1, block_sizey - 1)
                pygame.draw.rect(screen, grey3, rect)

while running:
    exit_game()
    # 每次绘制前清屏,避免上一帧画面残留
    screen.fill(bgcolour)
    draw_rect()
    pygame.display.flip()

内容的提问来源于stack exchange,提问作者Juhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:39:03