嵌套循环,二维数组

问题描述 投票:2回答:1

我有一个文本文档,其中只有1和0以80×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。

python arrays python-3.x pygame nested-loops
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.