gpt4 book ai didi

python - Pygame显示2D numpy数组

转载 作者:太空宇宙 更新时间:2023-11-03 21:47:26 25 4
gpt4 key购买 nike

我创建了一个 2D numpy 数组 20x20,其随机值为 0、1 或 2。我想要的是每个值都有一个相应的颜色值,并且 pygame 显示这些相应颜色值的网格。例如,0 变成白色方 block ,1 变成红色方 block ,2 变成绿色方 block 。我似乎找不到办法做到这一点。我目前的代码基本上是教程的大杂烩,没有一个真正有效,但你看:

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

最佳答案

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

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)

关于python - Pygame显示2D numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52389624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com