How to resolve the algorithm Maze generation step by step in the Picat programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Maze generation step by step in the Picat programming language

Table of Contents

Problem Statement

Generate and show a maze, using the simple Depth-first search algorithm.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Maze generation step by step in the Picat programming language

Source code in the picat programming language

main =>
    gen_maze(8,8).

main([RStr,CStr]) =>
    MaxR = to_int(RStr),
    MaxC = to_int(CStr),
    gen_maze(MaxR,MaxC).

gen_maze(MaxR,MaxC) =>
    Maze = new_array(MaxR,MaxC),
    foreach (R in 1..MaxR, C in 1..MaxC)
        Maze[R,C] = 0
    end,
    gen_maze(Maze,MaxR,MaxC,1,1),
    display_maze(Maze,MaxR,MaxC).

gen_maze(Maze,MaxR,MaxC,R,C) =>
    Dirs = shuffle([left, right, up, down]),
    foreach (Dir in Dirs)
        dir(Dir,Dr,Dc,B,OB),
        R1 := R+Dr,
        C1 := C+Dc,
        if (R1 >= 1 && R1 =< MaxR && C1 >= 1 && C1 =< MaxC && Maze[R1,C1] == 0) then
            Maze[R,C] := Maze[R,C] \/ B,
            Maze[R1,C1] := Maze[R1,C1] \/ OB,
            gen_maze(Maze,MaxR,MaxC,R1,C1)
        end
    end.

% dir(direction, Dr, Dc, Bit, OppBit)
dir(left,  0, -1, 1, 2).
dir(right, 0,  1, 2, 1).
dir(up,    -1, 0, 4, 8).
dir(down,  1,  0, 8, 4).

shuffle(Arr) = Res =>
    foreach (_ in 1..10)
        I1 = random() mod 4 + 1,
        I2 = random() mod 4 + 1,
        T := Arr[I1],
        Arr[I1] := Arr[I2],
        Arr[I2] := T
    end,
    Res = Arr.

display_maze(Maze,MaxR,MaxC) =>
    foreach (R in 1..MaxR)
        foreach (C in 1..MaxC)
            printf("%s", cond(Maze[R,C] /\ 4 == 0, "+---", "+   "))
        end,
        println("+"),
        foreach (C in 1..MaxC)
            printf("%s", cond(Maze[R,C] /\ 1 == 0, "|   ", "    ")),
        end,
        println("|")
    end,
    foreach (C in 1..MaxC)
        print("+---")
    end,
    println("+").

  

You may also check:How to resolve the algorithm Man or boy test step by step in the Swift programming language
You may also check:How to resolve the algorithm Literals/Floating point step by step in the zkl programming language
You may also check:How to resolve the algorithm Draw a pixel step by step in the Julia programming language
You may also check:How to resolve the algorithm Set consolidation step by step in the Clojure programming language
You may also check:How to resolve the algorithm List rooted trees step by step in the Go programming language