Pygame显示2D numpy阵列

2024-06-28 11:22:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个2dnumpy数组,20x20,它的随机值为0、1或2。 我想要的是这些值中的每一个都有一个对应的颜色值,pygame要显示这些相应颜色值的网格。例如,0变成了一个绿色的正方形,一个正方形变成了一个红色的正方形。我好像找不到一个办法来做这个。我现在的代码基本上是一堆教程,没有一个真正有效,但是现在你可以:

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

Tags: importnumpyevent网格颜色数组screenpygame
1条回答
网友
1楼 · 发布于 2024-06-28 11:22:57

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

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

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

^{pr2}$

将其传递给pygame.surfarray.make_surface,将其转换为pygame.Surface,您可以将其blit显示在屏幕上。在

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)

相关问题 更多 >