有pygame可以将整数识别为颜色的两种方式:
- RGB的3元素序列,其中每个元素的范围介于0-255之间。
- 映射的整数值。
如果您希望能够有一个数组,其中0-255之间的每个整数代表灰度阴影,则可以使用此信息创建自己的灰度数组。您可以通过定义一个类来创建自己的数组。
第一种方法是创建一个numpy数组,每个元素是一个3元素序列。
class GreyArray(object):
def __init__(self, size, value=0):
self.array = np.zeros((size[0], size[1], 3), dtype=np.uint8)
self.array.fill(value)
def fill(self, value):
if 0 <= value <= 255:
self.array.fill(value)
def render(self, surface):
pygame.surfarray.blit_array(surface, self.array)
创建基于映射的整数值的类可以是一个有点抽象。我不知道这些值是如何映射的,但通过快速测试,可以很容易地确定每个灰色阴影的分隔值为16843008
,从0
的黑色开始。
class GreyArray(object):
def __init__(self, size, value=0):
self.array = np.zeros(size, dtype=np.uint32)
self.array.fill(value)
def fill(self, value):
if 0 <= value <= 255:
self.array.fill(value * 16843008) # 16843008 is the step between every shade of gray.
def render(self, surface):
pygame.surfarray.blit_array(surface, self.array)
简短的演示。按1-6更改灰色阴影。
import pygame
import numpy as np
pygame.init()
s = 300
screen = pygame.display.set_mode((s, s))
# Put one of the class definitions here!
screen_array = GreyArray(size=(s, s))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
screen_array.fill(0)
elif event.key == pygame.K_2:
screen_array.fill(51)
elif event.key == pygame.K_3:
screen_array.fill(102)
elif event.key == pygame.K_4:
screen_array.fill(153)
elif event.key == pygame.K_5:
screen_array.fill(204)
elif event.key == pygame.K_6:
screen_array.fill(255)
screen_array.render(screen)
pygame.display.update()
pygame使用颜色作为三个数字(红色,绿色,蓝色),所以白色是(0,0,0),黑色是(255,255,255) – furas