Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Maze and Snake!

by chipmunk (Parson)
on Aug 15, 2001 at 19:55 UTC ( #105074=obfuscated: print w/replies, xml ) Need Help??

You've probably seen a maze-solving program before. For example, there are many screen savers that draw a maze on the screen and then solve it. Here are two companion scripts that implement this as a JAPH!


The first one is, the maze-generating script. By default, it draws a 9 by 33 maze (21 characters by 70 characters), but you can also specify height and width on the command line, such as perl 8 20 .

$x=1+rand($w=pop||33);$y=1+rand($h=pop||9);sub p{print@_}@m=($t=[10 ,(8)x($w+1)],(map[(2,(0)x$w,2)],1..$h),$t);sub w{$m[$y][$x]|=$_}{(@d= ($m[$y-1][$x]?():1,$m[$y+1][$x]?():2,$m[$y][$x-1]?():4,$m[$y][$x+1]?() :8))?(@d>1?$q[@q]=[$y,$x]:1,$_=$d[rand@d],w,s/1/$y--;2/e||s/2/$y++;1/e ||s/4/$x--;8/e||s/8/$x++;4/e,w):(($y,$x)=@{shift@q||last});redo}sub r{ $m[pop][1+rand$w]|=2}r;r-2;for$y(0..$h){p$",$m[$y][$_]&8?$":'#'for@w= 0..$w;sub P{p" \n"}P;p$m[$y][$_]&2?$":'#','#'for@w;P}p$"x(2+$w*2);P

The second one is, which solves a maze generated by It does the old trick of always following the right-hand wall.

$|=@j='Just another Perl hacker, '=~/./gs;sub p{print@_}p$H="\e[H", "\e[J",map@$_,@m=map[//g],<>;@y=$"='';$_="@{$m[1]}";/\S+/g;p"$H ",' ' x($x[0]=pos);$_=C;{$o=0;$y=$y[-1];$x=$x[-1];s|A|$m[$y][++$x]=~/ /?$o=C :D|e||s|C|$m[++$y][$x]=~/ /?$o=B:A|e||s|B|$m[$y][--$x]=~/ /?$o=D:C|e|| s|D|$m[--$y][$x]=~/ /?$o=A:B|e;$o||redo;$y^$y[-2]||$x^$x[-2]?($y[@y]=$ y,$x[@x]=$x):(--$#y,$#x--,$j-=2,p"\e[D ");$y&&$x&&$y<$#m&$x<$#{$m[0]} &&do{p"\e[$_\e[D$j[$j++]";$j%=@j;select$,,$,,$,,.06;redo}}p$H,$/x@m

You can pass the output from directly into (perl | perl or you can save the maze to a file and solve it later (perl > mymaze; perl mymaze).

A few caveats for these scripts:

  • They're not quite warning safe. Sorry. :)
  • uses console escape sequences to move around the screen, so it may not work on all platforms.
  • If you use a maze that is bigger than your window, the snake won't be lined up with the walls.
  • Similarly, if you type any characters in the window where is running, the snake won't stay lined up with the walls. Instead just sit back and enjoy.

The maze generating algorithm was taken from Games::MazeD2 by John M. Gamble.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: obfuscated [id://105074]
Approved by root
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2018-05-25 08:04 GMT
Find Nodes?
    Voting Booth?