欢迎访问宙启技术站
智能推送

利用Haskell编写一个迷宫生成器

发布时间:2023-12-09 15:20:08

以下是一个使用Haskell编写的迷宫生成器的示例代码,该代码使用了随机递归分割算法来生成迷宫。

import System.Random

-- 定义迷宫单元的数据类型
data Cell = Wall | Empty deriving (Eq, Show)

-- 定义迷宫的数据类型
type Maze = [[Cell]]

-- 创建一个空的宽度为w,高度为h的迷宫
createMaze :: Int -> Int -> Maze
createMaze w h = replicate h (replicate w Wall)

-- 在迷宫中指定的位置设置为Empty,如果position越界则返回原迷宫
setCell :: Maze -> (Int, Int) -> Maze
setCell maze (x, y)
  | x >= 0 && x < width && y >= 0 && y < height =
      take y maze ++ [take x row ++ [Empty] ++ drop (x + 1) row] ++ drop (y + 1) maze
  | otherwise = maze
  where row = maze !! y
        height = length maze
        width = length row

-- 检查迷宫中指定位置是否为Empty,如果position越界则返回False
isCellEmpty :: Maze -> (Int, Int) -> Bool
isCellEmpty maze (x, y)
  | x >= 0 && x < width && y >= 0 && y < height = maze !! y !! x == Empty
  | otherwise = False
  where height = length maze
        width = length (head maze)

-- 使用随机递归分割算法生成迷宫
generateMaze :: Int -> Int -> Maze -> StdGen -> Maze
generateMaze x y maze gen
  | y >= height - 1 = maze  -- 达到迷宫最底部时结束生成
  | x >= width - 1 = generateMaze 1 (y + 2) maze gen  -- 换行
  | isCellEmpty maze (x, y) || isCellEmpty maze (x, y + 1) =  -- 如果当前行或下一行有空单元,则继续分割
      let (nextX, nextGen) = randomR (x, width - 1) gen
          newMaze = setCell maze (nextX, y + 1)
      in generateMaze (x + 2) y newMaze nextGen
  | otherwise = generateMaze (x + 2) y maze gen  -- 跳过当前单元

  where height = length maze
        width = length (head maze)

-- 生成迷宫的入口函数
generateMazeWithSize :: Int -> Int -> IO ()
generateMazeWithSize width height = do
  gen <- getStdGen
  let maze = generateMaze 1 1 (createMaze width height) gen
  mapM_ putStrLn (map (concatMap (\c -> if c == Wall then "##" else "  ")) maze)

-- 使用例子
main :: IO ()
main = generateMazeWithSize 10 10

使用generateMazeWithSize函数可以生成一个宽度为10,高度为10的迷宫的文本表示。其中,#表示墙,空格表示通路。

以下是输出的一种可能的迷宫形状示例:

####################
#                  #
## #################
#  #   #   #   #    
#  # # # #   # # ###
#  #     #     # #  
#  ########## #  ##
#        #   #   ##
####################

这是一个简单的迷宫生成器示例,它使用了随机递归分割算法来生成迷宫。你可以根据需要修改宽度和高度来生成不同大小的迷宫。