简体   繁体   English

使用数组存储窗口的像素

[英]Using Array to Store Pixels of Window

Is it possible (in terms of performance) to have a single multi-dimensional array that contains one 8-bit integer per pixel, for each pixel in the game window? 对于游戏窗口中的每个像素,是否有可能(在性能方面)拥有一个包含每个像素一个8位整数的单个多维数组? I need to update the game window in a timely manner based on this array. 我需要根据这个数组及时更新游戏窗口。

I'm aiming for something like the following: 我的目标是以下内容:

import numpy
window_array = numpy.zeros((600, 600), dtype=numpy.int8)

#draw the screen
for (y, x), value in numpy.ndenumerate(window_array):
    if value == 1:
        rgb = (0, 0, 0)
    elif value == 2:
        rgb = (50, 50, 50)
    blit_pixel(x, y, rgb)

I'd like to be going 30-60 FPS, but so far my tests have yielded results that were much too slow to run at even a bad framerate. 我想要以30-60 FPS的速度运行,但到目前为止,我的测试已经产生的结果太慢了,甚至在一个糟糕的帧速率下也无法运行。 Is it possible to do, and if so, how? 有可能吗,如果可以,怎么做?

I have never used pygame, so take my anwser with a grain of salt... 我从未使用过pygame,所以带上我的anwser一粒盐...

That said, it seems very unlikely that you are going to get any decent frame rate if you are iterating over 360,000 pixels with a python loop and doing a python function call at each one. 也就是说,如果你使用python循环迭代360,000像素并在每个像素上执行python函数调用,那么你似乎不太可能获得任何不错的帧速率。

I learned from this other question (read the comment thread) that the pygame.surfarray module will give you a reference to the array holding the actual screen data. 我从另一个问题 (阅读注释线程)中了解到, pygame.surfarray模块将为您提供对包含实际屏幕数据的数组的引用。 pygame.surfarray.pixels3d should return a reference to an array of shape (rows, cols, 3) where the last dimension holds the RGB values on screen. pygame.surfarray.pixels3d应返回对形状数组(rows, cols, 3)的引用(rows, cols, 3)其中最后一个维度在屏幕上保存RGB值。 With that reference, you can change the pixels on screen directly, without needing a python loop doing something like: 使用该引用,您可以直接更改屏幕上的像素,而无需执行以下操作:

import numpy
surf_array = pygame.surfarray.pixels3d(surface)
window_array = numpy.zeros(surf_array.shape[:2], dtype=numpy.int8)
...
surf_array[numpy.nonzero(window_array == 1)] = np.array([0, 0, 0])
surf_array[numpy.nonzero(window_array == 2)] = np.array([50, 50, 50])

Not sure if a call to pygame.display.update is needed to actually show your changes, but this approach will sustain a much, much higher frame rate than what you had in mind. 不确定是否需要调用pygame.display.update来实际显示您的更改,但这种方法将维持比您想象的更高,更高的帧速率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM