I have a text document where only 1 and 0 are written in the form of an 80 by 80 square, i.e. 80 lines and 80 columns where only 1 and 0 are written. I need to create a code that draws an 80 by 80 square and fills those boxes in red, instead of which 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()
This is my code yet. Python version 3.
There is one nested loop to much. Only 2 nested loops are needed to traverse a 2 dimensional array.
The liens are traversed by:
for line in task: line = line.replace('\n', '')
And the columns are traversed by
for j in range(0,80):
Change your code like this:
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