我正在尝试通过迭代二维数组并绘制盒子来为简单的蛇游戏制作盒子背景,我将这些盒子存储为数组的每个部分中的类BackgroundCube的实例。当我运行该程序时,没有错误,但 pygame 屏幕上没有显示任何内容。
我已经打印了每个子列表的长度,其中显示的长度为 20,这是我想要的网格大小。我还刚刚打印了整个数组,其中显示了我认为是该类实例的内容,如下所示: <main.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/