Просто зациклите свои данные и увеличьте y
для каждой ячейки, затем увеличьте x
для каждой строки.
Вот как это может выглядеть:
import pygame
import pygame.freetype
def recursive_draw(surf, x, y, width, height):
"""Recursive rectangle function."""
pygame.draw.rect(surf, (0, 0, 0), [x, y, width, height], 1)
if y >= 600: # Screen bottom reached.
return
# Is the rectangle wide enough to draw again?
elif x < 750 - width: # Right screen edge not reached.
x += width
# Recursively draw again.
recursive_draw(surf, x, y, width, height)
else:
# Increment y and reset x to 0 and start drawing the next row.
x = 0
y += height
recursive_draw(surf, x, y, width, height)
data = [
(1, 'RED', 23, 'dog', 41),
(2, 'BLUE', 12, 'cat', 42),
(3, 'YELLOW', 12, 'horse', 43),
(4, 'GREEN', 99, 'bear', 55),
(5, 'CYAN', 52, 'snake', 14)
]
def main():
pygame.init()
font = pygame.freetype.SysFont("Arial", 25, True, False)
size = [750, 550]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
screen.fill((255, 255, 255))
background = screen.copy()
recursive_draw(background, 0, 0, 150, 50)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
screen.blit(background, (0, 0))
# let's have a padding of 15px inside the cell
x = 15
y = 15
for row in data:
for cell in row:
font.render_to(screen, (x, y), str(cell), pygame.Color('dodgerblue'))
x += 150 # should be a constant
y += 50 # should be a constant
x = 15 # should be a constant, too :-)
pygame.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
pygame.quit()
Вы можете использовать тот же подход для рисования прямоугольников, поэтому вам не нужна рекурсивная функция.Для этого достаточно вложенного цикла.
Для чтения из файла, подобного этому (data.txt
):
1, 'RED', 23, 'dog', 41
2, 'BLUE', 12, 'cat', 42
3, 'YELLOW', 12, 'horse', 43
4, 'GREEN', 99, 'bear', 55
5, 'CYAN', 52, 'snake', 14
импортируйте модуль csv
и используйте
data = []
with open('data.txt', newline='') as csvfile:
reader = csv.reader(csvfile, quotechar="'", skipinitialspace=True)
for row in reader:
data.append(row)
вместо
data = [
(1, 'RED', 23, 'dog', 41),
...
]