简体   繁体   中英

Haskell gloss IO textures

I am making a game, for which i use textures. These textures are loaded in in Gloss from BMP files and give a IO Picture.

Now i have a list of IO Pictures, which i want to render. The render takes a picture, and you can compose multiple pictures into one, with pictures

Now

Render :: IO()
texture1 <- loadBMP "D:/t1.bmp"

display window background (pictures [translate 10 50 $ texture1])

works, however, i want to use a list of textures. As this works with small numbers, but it becomes too much with 100s of textures.

Now for some reason, the pictures function, which takes Picture, now works with IO, which i believe has something to do with the do.

My question is, is there a way to put this into a function? If it were all Picture, it would be easy, but because of the IO Picture, I dont know how to do it

something like

func :: [IO Picture] -> [?]
func [] = []
func (x:xs) =  do
               x' <- x
               x' ++ func xs

and then

 display window background (pictures func)

There's a helper function that gets you almost all of the way there:

sequence :: [IO a] -> IO [a]

Ie it combines a list of IO actions into a single action that (when run) returns a list of the results.

You can't use this "inside" of the call to pictures (because that's pure Haskell code, which can't run IO actions, so there's no way to get that [a] ), but you can do it the other way:

(>>=) :: IO a -> (a -> IO b) -> IO b

Use >>= to push your function "into" IO:

sequence (map loadBMP myBMPFiles) >>= (\textures -> display window background (pictures textures))

(By the way, I'm assuming you have a list of filenames called myBMPFiles here.)

The same code can also be written using do notation:

do
    textures <- sequence (map loadBMP myBMPFiles)
    display window background (pictures textures)

And finally, sequence and map can be combined into mapM (also in the standard library):

do
    textures <- mapM loadBMP myBMPFiles
    display window background (pictures textures)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM