地图中有水果、房子、树木和道路。道路能通到水果旁。
代码:
using UnityEngine;
using System.Collections.Generic;
using System.Text;
public class TilemapGenerator : MonoBehaviour
{
public int mapWidth = 30;
public int mapHeight = 20;
private int[,] map;
void Start()
{
GenerateTilemap();
PrintTilemap();
}
void GenerateTilemap()
{
map = new int[mapWidth, mapHeight];
// 初始化地图为障碍物 (0)
for (int x = 0; x < mapWidth; x++)
{
for (int y = 0; y < mapHeight; y++)
{
map[x, y] = 0;
}
}
// 生成道路并放置元素
System.Random rand = new System.Random();
GenerateRoadsAndPlaceElements(rand, 2, 10); // 苹果
GenerateRoadsAndPlaceElements(rand, 3, 10); // 胡萝卜
GenerateRoadsAndPlaceElements(rand, 4, 10); // 橙子
// 在非道路区域放置额外的树木和房子
PlaceElementsRandomly(5, 15); // 树木
PlaceElementsRandomly(6, 5); // 房子
}
void GenerateRoadsAndPlaceElements(System.Random rand, int element, int count)
{
for (int i = 0; i < count; i++)
{
int x = rand.Next(mapWidth);
int y = rand.Next(mapHeight);
// 确保初始位置未被占用
while (map[x, y] != 0)
{
x = rand.Next(mapWidth);
y = rand.Next(mapHeight);
}
// 放置元素
map[x, y] = element;
// 生成通向此元素的道路
GenerateRoadToElement(rand, x, y);
}
}
void GenerateRoadToElement(System.Random rand, int targetX, int targetY)
{
int x = rand.Next(mapWidth);
int y = rand.Next(mapHeight);
// 确保起始位置未被占用并且在边缘
while (map[x, y] != 0 || (x != 0 && x != mapWidth - 1 && y != 0 && y != mapHeight - 1))
{
x = rand.Next(mapWidth);
y = rand.Next(mapHeight);
}
while (x != targetX || y != targetY)
{
if (x < targetX) x++;
else if (x > targetX) x--;
else if (y < targetY) y++;
else if (y > targetY) y--;
if (map[x, y] == 0) map[x, y] = 1; // 标记为道路
}
}
void PlaceElementsRandomly(int element, int count)
{
System.Random rand = new System.Random();
for (int i = 0; i < count; i++)
{
int x, y;
do
{
x = rand.Next(mapWidth);
y = rand.Next(mapHeight);
} while (map[x, y] == 1); // 确保位置不是道路
map[x, y] = element;
}
}
void PrintTilemap()
{
StringBuilder sb = new StringBuilder();
for (int y = mapHeight - 1; y >= 0; y--)
{
for (int x = 0; x < mapWidth; x++)
{
sb.Append(map[x, y].ToString() + " ");
}
sb.AppendLine();
}
Debug.Log(sb.ToString());
}
}