using System;
using System.Collections.Generic;
public class Test
{
static Random
rand = new Random
(); static int width = 79;
static int height = 24;
static char[] cells = new char[width * height];
// Cells are ordered left-to-right, top-to-bottom
public static void Main()
{
GenerateRandomTerrain();
// pick a point on the surface as the cave entrance
int caveX = 35;
int caveY = 0;
while (cells[caveY * width + caveX] == ' ')
{
caveY++;
}
// drill down until we are deep underground
while (cells[caveY * width + caveX - 1] == ' ' ||
cells[caveY * width + caveX + 1] == ' ')
{
cells[caveY * width + caveX] = '.';
caveY++;
}
// starting from the entrance, walk randomly within the terrain,
// "carving out" the cave
// make sure we do not create new entrances; the carving must not go
// adjacent to an "open air" cell
for (int i = 0; i < 1000; i++)
{
// "carve out" the current cell
cells[caveY * width + caveX] = '.';
// Get random direction:
// 0: up
// 1: right
// 2: down
// 3: left
switch (dir)
{
case 0: // up
if (IsValidCaveCell(caveX, caveY + 1))
{
caveY++;
}
break;
case 1: // right
if (IsValidCaveCell(caveX + 1, caveY))
{
caveX++;
}
break;
case 2: // down
if (IsValidCaveCell(caveX, caveY - 1))
{
caveY--;
}
break;
case 3: // left
if (IsValidCaveCell(caveX - 1, caveY))
{
caveX--;
}
break;
}
}
// Show our results
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
System.Console.Write(cells[y * width + x]);
}
System.Console.WriteLine();
}
}
static void GenerateRandomTerrain()
{
for (int x = 0; x < width; x++)
{
int elevation
= rand.
Next(height
* 4 / 5, height
); for (int y = 0; y < height; y++)
{
if (y < height - elevation)
{
// Open air
cells[y * width + x] = ' ';
}
else
{
// Ground
cells[y * width + x] = 'X';
}
}
}
}
static bool IsValidCaveCell(int x, int y)
{
// a cave cell is valid if:
// - it doesn't exceed the world boundaries
// - it isn't adjacent to an "open air" cell
if (x < 0 || x >= width || y < 0 || y >= height)
{
// out of world bounds
return false;
}
for (int dx = -1; dx <= 1; dx++)
{
if (x + dx < 0 || x + dx >= width)
{
continue;
}
for (int dy = -1; dy <= 1; dy++)
{
if (y + dy < 0 || y + dy >= height)
{
continue;
}
if (cells[(y + dy) * width + (x + dx)] == ' ')
{
// adjacent to "open air" cell
return false;
}
}
}
return true;
}
}