嵌套循环,二维数组

时间:2019-03-14 16:45:42

标签: python arrays python-3.x pygame nested-loops

我有一个文本文档,其中只有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。

1 个答案:

答案 0 :(得分:0)

有很多嵌套循环。遍历二维数组只需要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
相关问题