python - 从 pygame 中的二维列表渲染背景框类时出现问题

标签 python python-3.x pygame

我正在尝试通过迭代二维数组并绘制盒子来为简单的蛇游戏制作盒子背景,我将这些盒子存储为数组的每个部分中的类BackgroundCube的实例。当我运行该程序时,没有错误,但 pygame 屏幕上没有显示任何内容。

我已经打印了每个子列表的长度,其中显示的长度为 20,这是我想要的网格大小。我还刚刚打印了整个数组,其中显示了我认为是该类实例的内容,如下所示: <ma​​in.BackgroundCube object at 0x11186e090> 将是列表中的一个条目。所以我相信问题在于我如何绘制矩形。

python

WIDTH = 400
HEIGHT = 420
screen = pygame.display.set_mode((WIDTH, HEIGHT))

class BackgroundCube:
    def __init__(self, x, y, width, height, color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color

    def draw(self, screen):
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height), 2)

def redrawGameWindow():
    for x in range(20):
        for y in range(20):
            cube2 = background_cube_list[x][y]
            cube2.draw(screen)

run = True
background_cube_list = [[0 for x in range(int(WIDTH/20))] for x in range(int((HEIGHT-20)/20))]
while run:
    for cube in range(int(WIDTH / 20)):
        for cube1 in range(int((HEIGHT - 20) / 20)):
            background_cube_list[cube][cube1] = BackgroundCube(cube * 20, cube1 * 20, 20, 20, (144, 144, 144))
    clock.tick(30)

    redrawGameWindow()

同样,没有错误,只是一个空白的白色窗口。谢谢。

最佳答案

您忘记添加

pygame.display.update()

在你的主循环中。将其添加到 redrawGameWindow() 之后。

您还需要定义clock,我猜是clock = pygame.time.Clock()。将其添加到主循环之前。

关于python - 从 pygame 中的二维列表渲染背景框类时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57275425/

相关文章:

python - Pygame 文本换行符

Python 3.3 pygame 1.9.2a0(64 位)图形窗口显示第一个图像但随后卡住

python - 统一码编码错误 : 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)?

python - 根据 groupby 和条件对列求和

python - 如何使用 python 从 git 存储库获取特定文件版本

python - 在 while 循环中使用 += 但需要排除最大数字

Python BeautifulSoup - 循环多个页面

python - 我可以将 curio 与 sanic 一起使用吗?为什么不?

python - struct.unpack 导致TypeError :'int' 不支持buffer接口(interface)

Python 帮助 Pygame 和多处理