Skip to content

Instantly share code, notes, and snippets.

@TheBuzzSaw
Created November 9, 2019 17:42
Show Gist options
  • Save TheBuzzSaw/b929d476985ac3a6449a36e7211266f9 to your computer and use it in GitHub Desktop.
Save TheBuzzSaw/b929d476985ac3a6449a36e7211266f9 to your computer and use it in GitHub Desktop.
MazeRunner
using System;
using System.Drawing;
namespace MazeRunner
{
class Maze
{
public int Width { get; }
public int Height { get; }
private readonly uint[] _bits;
private bool IsSet(int index)
{
int arrayIndex = index / 32;
int bitIndex = index - arrayIndex * 32;
uint mask = (uint)1 << bitIndex;
return (_bits[arrayIndex] & mask) != 0;
}
private void Set(int index)
{
int arrayIndex = index / 32;
int bitIndex = index - arrayIndex * 32;
uint mask = (uint)1 << bitIndex;
_bits[arrayIndex] |= mask;
}
public Maze(int width, int height)
{
Width = width;
Height = height;
int bitCount = width * height * 2;
int wordCount = (bitCount + 31) / 32;
_bits = new uint[wordCount];
}
public void RandomFill(Random random)
{
for (int i = 0; i < _bits.Length; ++i)
{
uint hi = (uint)(random.Next() & 0xffff);
uint lo = (uint)(random.Next() & 0xffff);
_bits[i] = (hi << 16) | lo;
}
}
public Bitmap CreateBitmap(int edge = 1)
{
int cellEdge = edge + 1;
var black = Color.FromKnownColor(KnownColor.Black);
var white = Color.FromKnownColor(KnownColor.White);
var result = new Bitmap(cellEdge * Width + 1, cellEdge * Height + 1);
for (int y = 0; y < Height; ++y)
for (int x = 0; x < Width; ++x)
{
int top = y * cellEdge;
int left = x * cellEdge;
result.SetPixel(left, top, black);
int index = (y * Width + x) * 2;
var topColor = y == 0 || IsSet(index + 1) ? black : white;
for (int i = 1; i < cellEdge; ++i)
result.SetPixel(left + i, top, topColor);
var leftColor = x == 0 || IsSet(index) ? black : white;
for (int i = 1; i < cellEdge; ++i)
{
result.SetPixel(left, top + i, leftColor);
for (int j = 1; j < cellEdge; ++j)
result.SetPixel(left + j, top + i, white);
}
}
int lastColumn = result.Width - 1;
for (int i = 0; i < result.Height; ++i)
result.SetPixel(lastColumn, i, black);
int lastRow = result.Height - 1;
for (int i = 0; i < result.Width; ++i)
result.SetPixel(i, lastRow, black);
return result;
}
}
}
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace MazeRunner
{
class Program
{
static void Main(string[] args)
{
var maze = new Maze(64, 64);
maze.RandomFill(new Random());
maze.CreateBitmap().Save("maze_1.bmp", ImageFormat.Bmp);
maze.CreateBitmap(4).Save("maze_4.bmp", ImageFormat.Bmp);
maze.CreateBitmap(16).Save("maze_16.bmp", ImageFormat.Bmp);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment