Skip to content

Instantly share code, notes, and snippets.

@fumobox
Created February 16, 2019 16:10
Show Gist options
  • Save fumobox/90d0de1f1d9346f50559df2f00045d65 to your computer and use it in GitHub Desktop.
Save fumobox/90d0de1f1d9346f50559df2f00045d65 to your computer and use it in GitHub Desktop.
MazeModel
using System;
using System.Collections;
using System.Collections.Generic;
using Random = UnityEngine.Random;
public class MazeModel
{
BlockMap _map = new BlockMap();
public BlockMap Map => _map;
public MazeModel()
{
Random.InitState(99);
var block = BlockFactory.CreateRootBlock(_map);
BlockFactory.CreateNextBlock(block, _map);
}
}
public class Block: IEnumerable
{
public int X { get; }
public int Y { get; }
public int Z { get; }
public Block[] AdjacentBlocks { get; }
public int Distance { get; }
public Block(int x, int y, int z, int distance)
{
X = x;
Y = y;
Z = z;
AdjacentBlocks = new Block[6];
Distance = distance;
}
public IEnumerator GetEnumerator()
{
return AdjacentBlocks.GetEnumerator();
}
public override String ToString()
{
return X + "," + Y + "," + Z + ","
+ (AdjacentBlocks[0] == null ? "#" : "_")
+ (AdjacentBlocks[1] == null ? "#" : "_")
+ (AdjacentBlocks[2] == null ? "#" : "_")
+ (AdjacentBlocks[3] == null ? "#" : "_")
+ (AdjacentBlocks[4] == null ? "#" : "_")
+ (AdjacentBlocks[5] == null ? "#" : "_");
}
}
public static class BlockFactory
{
static readonly int[] XAdd = {0, 1, 0, -1};
static readonly int[] YAdd = {1, 0, -1, 0};
static readonly int[] PairIndex = {2, 3, 0, 1, 5, 4};
public static Block CreateRootBlock(BlockMap map)
{
var block = new Block(0, 0, 0, 0);
map.Add(block);
return block;
}
public static void CreateNextBlock(Block target, BlockMap map)
{
if (target.Distance == 10)
{
return;
}
for (int i = 0; i < 4; i++)
{
if (target.AdjacentBlocks[i] != null) continue;
var adjacentBlock = map.Find(target.X + XAdd[i], 0, target.Z + YAdd[i]);
if (adjacentBlock == null)
{
if (Random.value > 0.1)
{
var block = new Block(target.X + XAdd[i], 0, target.Z + YAdd[i], target.Distance + 1);
target.AdjacentBlocks[i] = block;
block.AdjacentBlocks[PairIndex[i]] = target;
map.Add(block);
CreateNextBlock(block, map);
}
}
else
{
if (Random.value > 0.8)
{
adjacentBlock.AdjacentBlocks[PairIndex[i]] = target;
}
}
}
}
}
public class BlockMap
{
List<Block> _blocks = new List<Block>();
public List<Block> Blocks => _blocks;
public void Add(Block block)
{
_blocks.Add(block);
}
public Block Find(int x, int y, int z)
{
foreach (var block in _blocks)
{
if (block.X == x && block.Y == y && block.Z == z)
return block;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment