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

Programmatically divide screen into N-rectangles with pygame

我有来自多个“通道”的输入数据流,我想使用 pygame.

在屏幕的一部分中表示每个通道的数据流

流数据在 pandas data.frame 中捕获并每隔几秒汇总一次。现在,我仅使用 pygame(即 scr = pygame.display.set_mode((0, 0), pygame.FULLSCREEN))中的第一个数据通道和全屏模式对此进行了原型制作。

我尝试划分屏幕的方式是 a lot like this,但我希望参考 [=] 中的列数,而不是创建固定数量的子屏幕28=] data.frame 以编程方式划分屏幕。

是否应该使用 Surface 和某种循环来完成?只是在寻找一些指导,因为这种类型的编程对我来说是新的。我看到了一些与地理数据有些相似的东西(比如 ),但是使用显示和 pygame 的上下文足以让我有点不确定。

我确实会使用 pygame.Surfaces 和一个循环。

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

现在我只是用随机颜色填充子屏幕,但你可以在子屏幕上(在 while 循环内或外)blit 任何你想要的东西,因为它们很旧 pygame.Surfaces.

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()