Created
May 21, 2012 23:50
-
-
Save supercleanse/2765459 to your computer and use it in GitHub Desktop.
Some Fun code to generate a maze
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Uses a depth first traversal algorithm to generate a maze | |
# You can change the width & height by altering the w & h variables | |
w=24;h=12;g=[];v=[] | |
# Setup the grid | |
(h+1).times{|y|g[y]=[];(w+1).times{|x|g[y]<<[x==w ? 0 : 1,y==h ? 0 : 1]}} | |
# Opening for the start and end & set the end cell | |
g[h][w-1][0]=g[0][0][0]=0;c=[w-1,h-1] | |
# Where the magic happens | |
def t(c,v,w,h,g) | |
# add cell to visited & get list of neighbors | |
v<<c;x=c[0];y=c[1];n=[[x,y-1],[x+1,y],[x,y+1],[x-1,y]].map{|j|j if(j[0]>=0&&j[0]<w&&j[1]>=0&&j[1]<h)}.compact | |
# visit neighbors in a random order ... remove the wall between this cell and neighbor if it hasn't already been visited | |
n.shuffle.each{|d| | |
if(!v.include?(d)) | |
o=(d[0]>x)? d[0]: x | |
p=(d[1]>y)? d[1]: y | |
(d[0]!=x)? g[p][o][1]=0 : g[p][o][0]=0 | |
t(d,v,w,h,g) | |
end | |
} | |
end | |
t(c,v,w,h,g) | |
# Print out the maze with simple text | |
g.each{|r| r.each{|c| print "+"+((c[0]==1)? "-": " ")};print "\n";r.each{|c|print ((c[1]==1)? "|": " ") + " "};print "\n"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment