// On generates a maze on a given grid by using a sidewinder algorithm. func (sw sidewinder) On(grid maze.Grid) { for _, row := range grid.EachRow() { run := make([]*maze.Cell, 0, len(row)) for _, cell := range row { run = append(run, cell) atEasternBoundary := cell.East == nil atNorthanBoundary := cell.North == nil shouldCloseOut := atEasternBoundary || (!atNorthanBoundary && sw.r.Intn(2) == 0) if shouldCloseOut { idx := sw.r.Intn(len(run)) member := run[idx] if member.North != nil { member.Link(member.North) } run = run[:0] } else { cell.Link(cell.East) } } } }
// On generates a maze on a given grid by using a binary tree algorithm. func (bt binaryTree) On(grid maze.Grid) { for _, cell := range grid.EachCell() { var neighbors []*maze.Cell if cell.North != nil { neighbors = append(neighbors, cell.North) } if cell.East != nil { neighbors = append(neighbors, cell.East) } if len(neighbors) < 1 { continue } idx := bt.r.Intn(len(neighbors)) neighbor := neighbors[idx] cell.Link(neighbor) } }
func main() { var ( grid maze.Grid al alg.Algorithm ) // choose grid type if dijkstra { grid = maze.NewDistanceGrid(row, col) } else { grid = maze.NewNormalGrid(row, col) } // choose algorithm to use switch flag.Arg(0) { case "binarytree": al = alg.NewBinaryTree() case "sidewinder": al = alg.NewSidewinder() case "recursivebacktracker": al = alg.NewRecursiveBacktracker(grid.Random()) default: panic("unknown algorithm") } // generate a maze by al al.On(grid) fmt.Println(grid.String()) fmt.Printf("%d dead-ends\n", len(grid.DeadEnds())) // braid grid.Braid(braid) if dijkstra { start := grid.Get(0, 0) grid.(*maze.DistanceGrid).Distances = start.Distances() } fmt.Println(grid.String()) fmt.Printf("%d dead-ends\n", len(grid.DeadEnds())) }