HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoMinor

Creating random maze in Go

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
creatingrandommaze

Problem

/*
Create a random maze
*/

package main

import (
    "fmt"
    "math/rand"
    "time"
)

const (
    mazewidth   = 15
    mazeheight  = 15
)

type room struct {
    x, y int
}

func (r room) String() string {
    return fmt.Sprintf("(%d,%d)", r.x, r.y)
}

func (r room) id() int {
    return (r.y * mazewidth) + r.x
}

// whetwher walls are  open or not.
// There are (num_rooms * 2) walls. Some are on borders, but nevermind them ;)
type wallregister [mazewidth * mazeheight * 2]bool

var wr = wallregister{}

// rooms are visited or not
type roomregister [mazewidth * mazeheight]bool

var rr = roomregister{}

func main() {
    rand.Seed(time.Now().Unix())

    stack := make([]room, 0, mazewidth*mazeheight)
    start := room{0, 0}

    // mark start position visited
    rr[start.id()] = true

    // put start position on stack 
    stack = append(stack, room{0, 0})

    for len(stack) > 0 {
        // current node is in top of the stack
        current := stack[len(stack)-1]

        // Slice of neighbors we can move
        availneighbrs := current.nonvisitedneighbors()

        // cannot move. Remove this room from stack and continue
        if len(availneighbrs)  0 {
        rslice = append(rslice, room{r.x - 1, r.y})
    }
    if r.y  0 {
        rslice = append(rslice, room{r.x, r.y - 1})
    }
    return rslice
}

// return rooms that are not visited yet
func (r room) nonvisitedneighbors() []room {
    rslice := make([]room, 0, 4)
    for _, r := range r.neighbors() {
        if rr[r.id()] == false {
            rslice = append(rslice, r)
        }
    }
    return rslice
}

// order to rooms by closeness to origin (upperleft)
func orderrooms(room1, room2 room) (room, room) {
    dist1 := room1.x*room1.x + room1.y*room1.y
    dist2 := room2.x*room2.x + room2.y*room2.y
    if dist1 < dist2 {
        return room1, room2
    }
    return room2, room1
}


http://play.golang.org/p/8W_FbBfUjb (You can run it here. But since time.Now() is fixed there, you will alw

Solution

General notes:

  • the code would benefit from splitting it into more methods,



  • go uses camelCaseConvention, not onlylowerletters.



Now, some particulars.

stack = append(stack, room{0, 0})


You can use start variable here.

func (r room) neighbors() []room {


In this function, it'd be more idiomatic to use switch { ... } instead of sequence of ifs. Same for the if-elses in the main().

Also it may be more efficient to have a single global re-used [4]room array and have neighbors/nonvisitedneighbors returns slices on it instead of make-ing a new one each call.

Code Snippets

stack = append(stack, room{0, 0})
func (r room) neighbors() []room {

Context

StackExchange Code Review Q#15539, answer score: 3

Revisions (0)

No revisions yet.