当然可以,以下是使用 C# 实现的一段生成线条沙漠的代码:
using System;
using System.Drawing;
namespace SandGenerator
{
class Program
{
static void Main(string[] args)
{
int width = 512;
int height = 512;
int numPoints = 20;
int maxIterations = 2000;
int[,] grid = GenerateSandGrid(width, height, numPoints, maxIterations);
Bitmap bmp = new Bitmap(width, height);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
bmp.SetPixel(x, y, grid[x,y] == 1 ? Color.FromArgb(50, 50, 50) : Color.White);
}
}
bmp.Save("sand.png");
}
static int[,] GenerateSandGrid(int width, int height, int numPoints, int maxIterations)
{
int[,] grid = new int[width, height];
Random rand = new Random();
// Initial placement of random points
Point[] points = new Point[numPoints];
for (int i = 0; i < numPoints; i++)
{
points[i] = new Point(rand.Next(width), rand.Next(height));
}
// Run simulation
for (int iteration = 0; iteration < maxIterations; iteration++)
{
int count = rand.Next(numPoints);
for (int i = 0; i < count; i++)
{
Point point = points[rand.Next(numPoints)];
Point nextPoint = Point.Empty;
double minDistanceSquared = double.MaxValue;
for (int x = point.X - 1; x <= point.X + 1; x++)
{
if (x < 0 || x >= width) continue;
for (int y = point.Y - 1; y <= point.Y + 1; y++)
{
if (y < 0 || y >= height) continue;
if (x == point.X && y == point.Y) continue;
double distanceSquared = DistanceSquared(point, new Point(x, y));
if (distanceSquared < minDistanceSquared)
{
minDistanceSquared = distanceSquared;
nextPoint = new Point(x, y);
}
}
}
if (minDistanceSquared != double.MaxValue)
{
grid[nextPoint.X, nextPoint.Y] = 1;
}
}
}
return grid;
}
static double DistanceSquared(Point a, Point b)
{
double dx = a.X - b.X;
double dy = a.Y - b.Y;
return dx * dx + dy * dy;
}
}
}
这里的实现采用了随机位置点的方式,并使用模拟旁边的地点最有可能会有沙子来向地图中添加沙子的方式来模拟线条箭头状的沙漠形态。最终将生成的结果保存为 PNG 格式图片。