请使用C++编写一个随机地形生成的示例大小为10241024
这里是一个简单的随机地形生成示例,使用了Perlin噪声算法:
#include
const int SIZE = 1024; const int OCTAVES = 8; const float PERSISTENCE = 0.5f;
float lerp(float a, float b, float t) { return a + t * (b - a); }
float smoothstep(float t) { return t * t * (3 - 2 * t); }
float perlin(float x, float y) { float total = 0.0f; float frequency = 1.0f; float amplitude = 1.0f; float maxAmplitude = 0.0f;
for (int i = 0; i < OCTAVES; ++i) {
total += amplitude * (1.0f + std::sin(x * frequency + y * frequency * 37.0f)) / 2.0f;
maxAmplitude += amplitude;
amplitude *= PERSISTENCE;
frequency *= 2.0f;
}
return total / maxAmplitude;
}
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution
float terrain[SIZE][SIZE];
for (int y = 0; y < SIZE; ++y) {
for (int x = 0; x < SIZE; ++x) {
float nx = (float)x / SIZE - 0.5f;
float ny = (float)y / SIZE - 0.5f;
terrain[y][x] = perlin(nx * 8.0f, ny * 8.0f);
}
}
for (int y = 0; y < SIZE; ++y) {
for (int x = 0; x < SIZE; ++x) {
float height = terrain[y][x];
if (height < 0.3f) {
std::cout << "\033[44m \033[0m"; // blue for water
}
else if (height < 0.5f) {
std::cout << "\033[43m \033[0m"; // yellow for sand
}
else if (height < 0.8f) {
std::cout << "\033[42m \033[0m"; // green for grass
}
else {
std::cout << "\033[47m \033[0m"; // white for snow
}
}
std::cout << std::endl;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/bFM9 著作权归作者所有。请勿转载和采集!