用pygame程序将屏幕划分为N个矩形



我有一个来自多个";通道";并且我想要使用CCD_ 1来表示屏幕的一部分内的每个频道的数据流。

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

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

这应该使用Surface和某种循环来完成吗?只是在寻找一些指导,因为这种类型的编程对我来说是新的。我在地理数据方面看到了一些模糊的相似之处(比如这样(,但使用显示器和pygame的背景足以让我有点不确定。

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

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

目前,我只是用随机的颜色填充子屏幕,但你可以在子屏幕上(在while循环中或之外(闪电战任何你想要的东西,因为它们只是一款很好的旧游戏。表面。

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

最新更新