1

I've created a 2D numpy array, 20x20, that has a random value of either 0, 1, or 2. What I want is for each of these values to have a corresponding colour value, and for pygame to display a grid of these corresponding colour values. A 0 becomes a white square, a 1 becomes a red square, and a 2 becomes a green square, for instance. I can't seem to find a way of doing this. My code at the moment is basically a mishmash of tutorials and none of it really works, but here you go:

import numpy
import pygame

gridarray = numpy.random.randint(3, size=(20, 20))
print(gridarray)

colour0=(120,250,90)
colour1=(250,90,120)
colour2=(255,255,255)

(width,height)=(300,300)

screen = pygame.pixelcopy.make_surface(gridarray)
pygame.display.flip()
screen.fill(colour2)

running = True
while running:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      running = False

1 Answer 1

2

You could create an array which contains the colors

colors = np.array([[120, 250, 90], [250, 90, 120], [255, 255, 255]])

and use your gridarray as an index array: colors[gridarray]. You'll get an array such as this:

array([[[120, 250,  90],
        [250,  90, 120],
        [250,  90, 120],
        ...,

Pass it to pygame.surfarray.make_surface to turn it into a pygame.Surface which you can blit onto the screen.

import pygame as pg
import numpy as np


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()

colors = np.array([[120, 250, 90], [250, 90, 120], [255, 255, 255]])
gridarray = np.random.randint(3, size=(20, 20))
surface = pg.surfarray.make_surface(colors[gridarray])
surface = pg.transform.scale(surface, (200, 200))  # Scaled a bit.

running = True
while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False

    screen.fill((30, 30, 30))
    screen.blit(surface, (100, 100))
    pg.display.flip()
    clock.tick(60)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.