pygame显示2D numpy数组

时间:2018-09-18 15:07:17

标签: python numpy pygame

我创建了一个二维的numpy数组20x20,其随机值为0、1或2。 我想要的是让这些值中的每一个都具有相应的颜色值,并使pygame显示这些相应的颜色值的网格。例如,0变为白色方块,1变为红色方块,而2变为绿色方块。我似乎找不到解决办法。目前,我的代码基本上是一堆教程,但都没有真正起作用,但是在这里您可以:

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 个答案:

答案 0 :(得分:0)

您可以创建一个包含颜色的数组

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

,并将您的gridarray用作索引数组:colors[gridarray]。您将得到一个这样的数组:

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

将其传递到pygame.surfarray.make_surface,将其变成pygame.Surface,您可以将其放到屏幕上。

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)