嵌套循环,二维数组

Nested loops, two-dimensional array

我有一个文本文件,其中只有 1 和 0 以 80 x 80 正方形的形式写入,即 80 行和 80 列,其中只写入 1 和 0。我需要创建一个代码来绘制一个 80 x 80 的正方形并将这些框填充为红色,而不是 1。

import pygame
import os
# create path to find my document

path = os.path.realpath('future.txt')
task = open(path, mode = 'r',encoding = 'utf-8')
#create screen
screen = pygame.display.set_mode((800,800))

white = [255, 255, 255]
red = [255, 0, 0]

x = 0
y = 0
#intepreter string as a list
for line in task:
    line = line.replace('\n', '')
    line = list(line)

# nested loop
    for j in range(0,80):

        for i in range(0,79):

            pygame.draw.rect(screen, white, (x, y, 10, 10), 1)

            x += 10


            if line[i] == '1':
                pygame.draw.rect(screen, red, (x, y, 9, 9))


            if x == 800:
                x = 0
                y += 10

while pygame.event.wait().type != pygame.QUIT:
    pygame.display.flip()

这是我的代码。 Python 版本 3.

嵌套循环太多了。遍历一个二维数组只需要2个嵌套循环。

留置权由以下人员遍历:

for line in task:
    line = line.replace('\n', '')

并且列被

遍历
for j in range(0,80):

像这样更改您的代码:

y = 0
for line in task:
    line = line.replace('\n', '')

    x = 0
    for elem in list(line):
        pygame.draw.rect(screen, white, (x, y, 10, 10), 1)
        if elem == '1':
            pygame.draw.rect(screen, red, (x+1, y+1, 8, 8))
        x += 10

    y += 10