There are two ways pygame can recognize integers as colors:
- A 3-element sequence of RGB where each element ranges between 0-255.
- A mapped integer value.
If you want to be able to have an array where every integer between 0-255 represent a shade of grey, you can create your own grey scale array using this information. You can create your own array by defining a class.
The first way would be to create a numpy array were each element is a 3-element sequence.
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)
Creating a class based on the mapped integer value can be a bit abstract. I don't know how the values are mapped, but with a quick test it was easy to determined that every shade of grey was separated with a value of 16843008
, starting with black at 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)
Short demonstration. Press 1-6 to change the shade of grey.
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()