在 haskell 中为游戏板画正方形
Draw squares for a game board in haskell
我希望能够使用 haskell 和光泽来绘制棋盘之类的东西。
我可以用任何其他语言做类似的事情
for( i=0; i < 10; i++){
for( j=0; j < 10; j++){
drawSquare(radius, i, j)
}
}
就是这样,但我是 haskell 的新手,我不知道如何做到这一点。我正在使用 Gloss 并且我能够手动绘制东西,但我希望能够在绘制 100 个正方形之前按程序创建它们而不是 1 乘 1。
如果您在 IO monad 内部工作,则可以使用相同的样式。例如
printSquares :: IO ()
printSquares =
forM_ [0..9] $ \x ->
forM_ [0..9] $ \y -> do
putStrLn "Here's a square!"
putStrLn ("Square(" ++ show x ++ ", " ++ show y ++ ")")
-- add here the actual drawing Gloss commands
我不熟悉 Gloss 来建议实际的绘图命令。
更新:Gloss 的界面似乎与上面使用 IO 的界面不同。你可能需要像
这样的东西
squares :: Picture
squares = Pictures [ square x y | x<-[0..9], y<-[0..9] ]
square :: Float -> Float -> Picture
square x y = Polygon [(x,y), (x+1,y), (x+1,y+1), (x,y+1) ]
-- even better: use rectangleWire and then translate
-- rectangleUpperWire also seems useful
虽然我不熟悉 gloss 库,但您可能正在寻找类似列表理解的东西:
drawBoard :: Int -> Int -> IO ()
drawBoard w h = sequence_ [drawSquare radius i j | i <- [0 .. w], j <- [0 .. h]]
我希望能够使用 haskell 和光泽来绘制棋盘之类的东西。
我可以用任何其他语言做类似的事情
for( i=0; i < 10; i++){
for( j=0; j < 10; j++){
drawSquare(radius, i, j)
}
}
就是这样,但我是 haskell 的新手,我不知道如何做到这一点。我正在使用 Gloss 并且我能够手动绘制东西,但我希望能够在绘制 100 个正方形之前按程序创建它们而不是 1 乘 1。
如果您在 IO monad 内部工作,则可以使用相同的样式。例如
printSquares :: IO ()
printSquares =
forM_ [0..9] $ \x ->
forM_ [0..9] $ \y -> do
putStrLn "Here's a square!"
putStrLn ("Square(" ++ show x ++ ", " ++ show y ++ ")")
-- add here the actual drawing Gloss commands
我不熟悉 Gloss 来建议实际的绘图命令。
更新:Gloss 的界面似乎与上面使用 IO 的界面不同。你可能需要像
这样的东西squares :: Picture
squares = Pictures [ square x y | x<-[0..9], y<-[0..9] ]
square :: Float -> Float -> Picture
square x y = Polygon [(x,y), (x+1,y), (x+1,y+1), (x,y+1) ]
-- even better: use rectangleWire and then translate
-- rectangleUpperWire also seems useful
虽然我不熟悉 gloss 库,但您可能正在寻找类似列表理解的东西:
drawBoard :: Int -> Int -> IO ()
drawBoard w h = sequence_ [drawSquare radius i j | i <- [0 .. w], j <- [0 .. h]]