我正在尝试通过迭代2D数组和绘图框来制作简单蛇游戏的背景大批。当我运行程序时,没有错误,但是在Pygame屏幕上没有任何错误。
我已经打印了每个子列表的长度,该长度显示为20,这是我所需的网格大小。我还刚刚打印了整个数组,该数组显示了我认为是类的实例,类似的内容:< main .backgroundCube对象在0x111186E090>将是列表中的一个条目。所以我相信问题在于我如何绘制矩形。
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()
。将其添加到主循环之前。