knp.de

– Simple Mazes with Mathematica

Simple Mazes with Mathematica

04/06/2015

This post is the start of a series of posts. It shows how you can draw amazing mazes with Mathematica.

Simple Mazes

It uses algorithms from the great book Mazes for Programmers by Jamis Buck.

It is currently in beta but can be bought from The Pragmatic Bookshelf.

This time we will start with the Binary Tree Algorithm.

Mazes for Programmers

by Jamis Buck

The Binary Tree Algorithm

Each cell contains two bits to signal, if there is a wall to the right or at top.

walls on a cell

Every cell chooses at random, if it should have a right or top wall.

inner[c_, r_] :=
  Table[
    RandomInteger[] + 1,
    {c}, {r}
  ]

Only the topmost and rightmost cells have no walls.

If you want to know why this works, please look at the book.

binaryTreeMaze[c_, r_] :=
  Append[
    Map[
      Append[#, 0] &,
      inner[c - 1, r - 1]
    ],
    Table[0, {r}]
  ]

The result is mirrored, because the coordinate system in Mathematica increases from bottom to top.

{
 {2, 2, 2, 1, 0},
 {1, 1, 1, 1, 0},
 {1, 2, 1, 2, 0},
 {2, 2, 1, 2, 0},
 {0, 0, 0, 0, 0}
}

Drawing the maze

First we need methods to generate the lines for the walls.

rw[x_, y_] :=
  Line[{{x, y - 1},
    {x, y}}];
  
tw[x_, y_] :=
  Line[{{x - 1, y},
    {x, y}}];

Then we have a method, that creates the lines for any cell.

lineify[v_, p_] :=
  Switch[v, 
   0, {}, 
   1, {Apply[rw, p]}, 
   2, {Apply[tw, p]},
   3, {Apply[rw, p],
       Apply[tw, p]}
   ];

We can apply this function to each cell.

conv[m_] :=
  Flatten[
    MapIndexed[
      lineify, m, {2}
    ]
  ]

To draw a box around the maze, we need its width and height.

w[m_] := Length[m];
h[m_] := Length[m[[1]]];

Putting it all together, the following code draws the maze.

drawMaze[m_] :=
  Graphics[Append[
    conv[m],
    Line[{{0, 0},
      {w[m], 0},
      {w[m], h[m]},
      {0, h[m]}, {0, 0}}]
    ]
  ]]

Here is the result.


Comments

Would you like to expand or correct an entry? Please send an e-mail to timm@knp.de. I will gladly publish interesting contributions on this site.