如何从 perlin-noise 获得 2D tile 输出?

问题描述

我的计划是让 Perlin noise 生成 2D 地形, 我在互联网上四处寻找解决方案,但要么无法理解代码,要么尝试过但没有成功。

import pygame
import numpy as np
from pygame import *

# source images to the game display
# Tiling thing from https://markbadiola.com/2012/01/22/rendering-background-image-using-pygame-in-python-2-7/

# assigns source image
SOURCE = pygame.image.load('tiles.png')

p = pygame.Rect(288,32,32) # pavement
g = pygame.Rect(416,32) # grass
s = pygame.Rect(288,160,32) # sand/dirt
b = pygame.Rect(288,320,32) # bush

# matrix containing the pattern of tiles to be rendered

import numpy as np
import sys
np.set_printoptions(threshold=sys.maxsize)
from scipy.ndimage.interpolation import zoom
arr = np.random.uniform(size=(4,4))
arr = zoom(arr,8)
arr = arr > 0.5
arr = np.where(arr,'-','#')
arr = np.array_str(arr,max_line_width=500)
print(arr)

代码提供了一个漂亮的数组,但我的其余代码无法使用它。我得到的错误消息是无效的 rectstyle 参数。如果我能够将 '-' 和 '#' 更改为 g 和 s,我相信这会起作用,但这也不起作用。

for y in range(len(map1.arr)):
  for x in range(len(map1.arr[y])):
    location = (x * 32,y * 32)
    screen.blit(map1.soURCE,location,map1.arr[y][x])

解决方法

Surface.blit 想要一个 rect 作为 area 参数。你传递一个字符串。

您可以做的是创建一个映射,将字符串转换为您已经定义的正确矩形,如下所示:

mapping = { '#': s,'-': g }

tile = map1.arr[y][x]
area = mapping[tile]
screen.blit(map1.SOURCE,location,area)

您还想删除

arr = np.array_str(arr,max_line_width=500)

行,因为这会将 arr 转换为字符串。