Печать слов из списка по определенным координатам в Pygame - PullRequest
0 голосов
/ 17 декабря 2018

Эй, ребята, я хочу напечатать слова и цифры из списка.Он будет содержать список имен, а затем отдельный список для возраста. Я хочу напечатать это в «превосходном» виде документа, который я сделал с рекурсивными прямоугольниками печати.В идеальном мире я мог бы составить список каждого поля с требованием и, возможно, использовать цикл с указанием начать печать с определенной позиции х и печатать каждое слово с определенным х вниз при прохождении цикла, легко заполняя строки.Любая помощь будет оценена.Я пытался найти какой-то код печати для этого сценария, но не смог его найти.Спасибо!

import pygame
pygame.font.init()
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
font = pygame.font.SysFont("Arial", 25, True, False)




def main():
    def recursive_draw(x, y, width, height):
        """Recursive rectangle function."""
        pygame.draw.rect(screen, BLACK, [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(x, y, width, height)
        else:
            # Increment y and reset x to 0 and start drawing the next row.
            x = 0
            y += height
            recursive_draw(x, y, width, height)

    pygame.init()
    size = [750, 550]
    screen = pygame.display.set_mode(size)
    clock = pygame.time.Clock()
    screen.fill(WHITE)
    recursive_draw(0, 0, 150, 50)

    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True



        pygame.display.flip()
        clock.tick(60)


main()

pygame.quit()

1 Ответ

0 голосов
/ 17 декабря 2018

Просто зациклите свои данные и увеличьте 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()

enter image description here

Вы можете использовать тот же подход для рисования прямоугольников, поэтому вам не нужна рекурсивная функция.Для этого достаточно вложенного цикла.


Для чтения из файла, подобного этому (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),
    ...
]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...