使用 pygame 以编程方式将屏幕划分为 N 个矩形

Programmatically divide screen into N-rectangles with pygame

提问人:Hack-R 提问时间:12/10/2021 最后编辑:Hack-R 更新时间:12/10/2021 访问量:207

问:

我有来自多个“通道”的输入数据流,我想在屏幕的某个部分内表示每个通道的数据流。pygame

流数据在 data.frame 中捕获,并每隔几秒钟汇总一次。现在,我仅使用pygame中的第一个数据通道和全屏模式(即)。pandasscr = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

我尝试划分屏幕的方式很像这样,但我希望引用 pandas data.frame 中的列数以编程方式划分屏幕,而不是创建固定数量的子屏幕。

这应该使用某种循环来完成吗?只是在寻找一些指导,因为这种类型的编程对我来说是新的。我已经在地理数据(像这样)中看到了一些模糊的相似之处,但是使用显示器的上下文足以让我有点不确定。Surfacepygame

蟒蛇 熊猫 pygame

评论


答:

2赞 Andre 12/10/2021 #1

我确实会使用 s 和 a loop。pygame.Surface

我学习了pygame的入门知识(我的首选是:https://realpython.com/pygame-a-primer/),并添加了我将如何实现多个sub_screens(或下面的脚本中的s)。我希望我的代码和评论足够清晰,可以了解发生了什么,否则就问吧!surf

现在,我只是用随机颜色填充子屏幕,但您可以在子屏幕上(在 while 循环内或外)上播放任何您想要的东西,因为它们只是很好的旧 pygame。表面。

import pygame
import random

# init pygame
pygame.init()

# set up parameters
n_rows = 5
n_cols = 3

screen_width = 800
screen_height = 500

# Create a dict with the row and column as key,
# and a tuple containing a Surface and its topleft coordinate as value
surf_width = round(screen_width / n_cols)
surf_height = round(screen_height / n_rows)

surfaces_dct = {}
for row in range(n_rows):
    for col in range(n_cols):

        # create a surface with given size
        surf = pygame.Surface(size=(surf_width, surf_height))
        # get its top left coordinate
        top_left = (col*surf_width, row*surf_height)

        # put it in the dict as a tuple
        surfaces_dct[(row, col)] = (surf, top_left)


# Here you can blit anything to each surface/sub-screen (defined by it's row and column):
for key, value in surfaces_dct.items():
    # unpack the key, value pairs
    (row, col) = key
    (surf, top_left) = value
    
    # I just fill each surface with a random color for demonstration
    (r, g, b) = [random.randint(0, 255) for i in range(3)]
    surf.fill((r, g, b))


# Set up the drawing window
screen = pygame.display.set_mode([screen_width, screen_height])

# Run until the user asks to quit
running = True
while running:

    # Did the user click the window close button?
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # You can also run this for-loop here, inside the main while-loop
    # to dynamically change what's on each surf
    # as you see you can also unpack the key and value like this
    for (row, col), (surf, top_left) in surfaces_dct.items():
        # I'll leave it blank here
        pass


    # Finally place(/blit) the surfaces on the screen given
    screen.blits(list(surfaces_dct.values()))

    #### the above is the same as doing:
    # for surf, top_left in surfaces_dct.values():
    #     screen.blit(surf, top_left)

    # Update the display
    pygame.display.update()