Advertisement
Guest User

Untitled

a guest
Feb 3rd, 2014
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.63 KB | None | 0 0
  1. let rnd : int -> int =
  2.   let gen = new System.Random()
  3.   fun max -> gen.Next(max)
  4.  
  5. // randomly choose an element of a list
  6. let choose (xs:_ list) = xs.[rnd xs.Length]
  7.  
  8. type Maze(width, height) =
  9.   // (x,y) -> have we been here before?
  10.   let visited = Array2D.create width height false
  11.   // (x,y) -> is there a wall between (x,y) and (x+1,y)?
  12.   let horizWalls = Array2D.create width height true
  13.   // (x,y) -> is there a wall between (x,y) and (x,y+1)?
  14.   let vertWalls = Array2D.create width height  true
  15.  
  16.   let isLegalPoint (x,y) =
  17.     x >= 0 && x < width && y >= 0 && y < height
  18.  
  19.   let neighbours (x,y) =
  20.     [(x-1,y);(x+1,y);(x,y-1);(x,y+1)] |> List.filter isLegalPoint
  21.  
  22.   let removeWallBetween (x1,y1) (x2,y2) =
  23.     if x1 <> x2 then
  24.       horizWalls.[min x1 x2, y1] <- false
  25.     else
  26.       vertWalls.[x1, min y1 y2] <- false
  27.  
  28.   let rec visit (x,y as p) =
  29.     let rec loop ns =
  30.       let (nx,ny) as n = choose ns
  31.       if not visited.[nx,ny] then
  32.         removeWallBetween p n
  33.         visit n
  34.       match List.filter ((<>) n) ns with
  35.       | [] -> ()
  36.       | others -> loop others
  37.  
  38.     visited.[x,y] <- true
  39.     loop (neighbours p)
  40.  
  41.   do visit (rnd width, rnd height)
  42.  
  43.   member x.Print() =
  44.     ("+" + (String.replicate width "-+")) ::
  45.     [for y in 0..(height-1) do
  46.        yield "\n|"
  47.        for x in 0..(width-1) do
  48.          yield if horizWalls.[x,y] then " |" else "  "
  49.        yield "\n+"
  50.        for x in 0..(width-1) do
  51.          yield if vertWalls.[x,y] then "-+" else " +"
  52.     ]
  53.     |> String.concat ""
  54.     |> printfn "%s"
  55.  
  56. let m = new Maze(25,25)
  57. m.Print()
  58. System.Console.ReadKey() |> ignore
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement