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 maze.pl, 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 maze.pl 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 snake.pl, which solves a maze generated by maze.pl. 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 maze.pl directly into snake.pl (perl maze.pl | perl snake.pl) or you can save the maze to a file and solve it later (perl maze.pl > mymaze; perl snake.pl mymaze).

A few caveats for these scripts:

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

Enjoy!

Replies are listed 'Best First'.
Re: Maze and Snake!
by Anonymous Monk on Mar 31, 2021 at 21:45 UTC
    Utterly superb